diff options
Diffstat (limited to 'tools')
327 files changed, 25090 insertions, 19436 deletions
diff --git a/tools/Godot.app/Contents/Info.plist b/tools/Godot.app/Contents/Info.plist index 3a4b51e2fe..cb2db17807 100755 --- a/tools/Godot.app/Contents/Info.plist +++ b/tools/Godot.app/Contents/Info.plist @@ -9,11 +9,11 @@ <key>CFBundleName</key> <string>Godot</string> <key>CFBundleGetInfoString</key> - <string>(c) 2007-2014 Juan Linietsky, Ariel Manzur</string> + <string>(c) 2007-2016 Juan Linietsky, Ariel Manzur</string> <key>CFBundleIconFile</key> <string>Godot.icns</string> <key>CFBundleIdentifier</key> - <string>com.okamstudio.godot</string> + <string>org.godotengine.godot</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundlePackageType</key> @@ -25,7 +25,7 @@ <key>CFBundleVersion</key> <string>1.0.0</string> <key>NSHumanReadableCopyright</key> - <string>© 2007-2014 Juan Linietsky, Ariel Manzur</string> + <string>© 2007-2016 Juan Linietsky, Ariel Manzur</string> <key>LSMinimumSystemVersion</key> <string>10.6.0</string> <key>LSMinimumSystemVersionByArchitecture</key> @@ -61,7 +61,7 @@ <true/> <key>LSItemContentTypes</key> <array> - <string>com.okamstudio.scn</string> + <string>org.godotengine.scn</string> </array> </dict> </array> diff --git a/tools/Godot.app/Contents/Resources/Godot.icns b/tools/Godot.app/Contents/Resources/Godot.icns Binary files differindex 18bc68d6ea..4a3dc0415a 100644 --- a/tools/Godot.app/Contents/Resources/Godot.icns +++ b/tools/Godot.app/Contents/Resources/Godot.icns diff --git a/tools/SCsub b/tools/SCsub index ce7df2c35b..f046e9ad08 100644 --- a/tools/SCsub +++ b/tools/SCsub @@ -11,11 +11,10 @@ if (env["tools"]!="no"): SConscript('collada/SCsub'); SConscript('docdump/SCsub'); SConscript('freetype/SCsub'); + SConscript('pe_bliss/SCsub'); SConscript('doc/SCsub') SConscript('pck/SCsub') lib = env.Library("tool",env.tool_sources) env.Prepend(LIBS=[lib]) - - diff --git a/tools/addheader/addheader.py b/tools/addheader/addheader.py index 038cec96d0..0252eb396d 100644 --- a/tools/addheader/addheader.py +++ b/tools/addheader/addheader.py @@ -6,7 +6,7 @@ header="""\ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/addheader/header.txt b/tools/addheader/header.txt index 359949cc3b..e4efb2dcfc 100644 --- a/tools/addheader/header.txt +++ b/tools/addheader/header.txt @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /*************************************************/ /* Source code within this file is: */ -/* (c) 2007-2010 Juan Linietsky, Ariel Manzur */ +/* (c) 2007-2016 Juan Linietsky, Ariel Manzur */ /* All Rights Reserved. */ /*************************************************/ diff --git a/tools/collada/SCsub b/tools/collada/SCsub index c8eaa596d1..34524f10ef 100644 --- a/tools/collada/SCsub +++ b/tools/collada/SCsub @@ -3,5 +3,3 @@ Import('env') env.add_source_files(env.tool_sources,"*.cpp") Export('env') - - diff --git a/tools/collada/collada.cpp b/tools/collada/collada.cpp index deec5f60c7..07da72718e 100644 --- a/tools/collada/collada.cpp +++ b/tools/collada/collada.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -1683,8 +1683,12 @@ Collada::Node* Collada::_parse_visual_scene_node(XMLParser& parser) { if ( parser.has_attribute("sid") ) { //bones may not have sid joint->sid=parser.get_attribute_value("sid"); // state.bone_map[joint->sid]=joint; - } else if (state.idref_joints.has(name)) + } else if (state.idref_joints.has(name)) { joint->sid=name; //kind of a cheat but.. + } else if (parser.has_attribute("name")) { + joint->sid=parser.get_attribute_value_safe("name"); + } + if (joint->sid!="") { state.sid_to_node_map[joint->sid]=id; diff --git a/tools/collada/collada.h b/tools/collada/collada.h index 81f51a1f3d..8983b8faf0 100644 --- a/tools/collada/collada.h +++ b/tools/collada/collada.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/doc/SCsub b/tools/doc/SCsub index c8eaa596d1..34524f10ef 100644 --- a/tools/doc/SCsub +++ b/tools/doc/SCsub @@ -3,5 +3,3 @@ Import('env') env.add_source_files(env.tool_sources,"*.cpp") Export('env') - - diff --git a/tools/doc/doc_data.cpp b/tools/doc/doc_data.cpp index 432f358627..a039c58ff4 100644 --- a/tools/doc/doc_data.cpp +++ b/tools/doc/doc_data.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -187,12 +187,13 @@ void DocData::generate(bool p_basic_types) { arginfo=E->get().return_val; - if (arginfo.type==Variant::NIL) - continue; +#ifdef DEBUG_METHODS_ENABLED if (m && m->get_return_type()!=StringName()) method.return_type=m->get_return_type(); - else + else if (arginfo.type!=Variant::NIL) { +#endif method.return_type=(arginfo.hint==PROPERTY_HINT_RESOURCE_TYPE)?arginfo.hint_string:Variant::get_type_name(arginfo.type); + } } else { @@ -583,7 +584,10 @@ void DocData::generate(bool p_basic_types) { md.name=mi.name; if (mi.return_val.name!="") md.return_type=mi.return_val.name; - else + else if (mi.name.find(":")!=-1) { + md.return_type=mi.name.get_slice(":",1); + md.name=mi.name.get_slice(":",0); + } else md.return_type=Variant::get_type_name(mi.return_val.type); for(int i=0;i<mi.arguments.size();i++) { @@ -593,8 +597,9 @@ void DocData::generate(bool p_basic_types) { ArgumentDoc ad; ad.name=pi.name; + if (pi.type==Variant::NIL) - ad.type="var"; + ad.type="Variant"; else ad.type=Variant::get_type_name( pi.type ); diff --git a/tools/doc/doc_data.h b/tools/doc/doc_data.h index b62eb21b4a..877f30defb 100644 --- a/tools/doc/doc_data.h +++ b/tools/doc/doc_data.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/docdump/SCsub b/tools/docdump/SCsub index c8eaa596d1..34524f10ef 100644 --- a/tools/docdump/SCsub +++ b/tools/docdump/SCsub @@ -3,5 +3,3 @@ Import('env') env.add_source_files(env.tool_sources,"*.cpp") Export('env') - - diff --git a/tools/docdump/class_list.xml b/tools/docdump/class_list.xml deleted file mode 100644 index 3d07f84177..0000000000 --- a/tools/docdump/class_list.xml +++ /dev/null @@ -1,13625 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<doc version="0.99.1384-pre-beta" name="Engine Types"> -<class name="Animation" inherits="Resource" category="Resources"> - <brief_description> - Contains data used to animate everything in the engine. - </brief_description> - <description> - An Animation resource contains data used to animate everything in the engine. Animations are divided into tracks, and each track must be linked to a node. The state of that node can be changed through time, by adding timed keys (signals) to the track. [html br/] Animations are just data containers, and must be added to odes such as an [AnimationPlayer] or [AnimationTreePlayer] to be played back. - </description> - <methods> - <method name="add_track" > - <argument index="0" name="type" type="int"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - Add a track to the Animation. The track type must be specified as any of the values in te TYPE_* enumeration. - </description> - </method> - <method name="remove_track" > - <argument index="0" name="idx" type="int"> - </argument> - <description> - Remove a track by specifying the track index. - </description> - </method> - <method name="get_track_count" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the amount of tracks in the animation. - </description> - </method> - <method name="track_get_type" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <description> - Get the type of a track. - </description> - </method> - <method name="track_get_path" qualifiers="const" > - <return type="NodePath"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <description> - Get the path of a track. for more information on the path format, see [method track_set_path] - </description> - </method> - <method name="track_set_path" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="path" type="NodePath"> - </argument> - <description> - Set the path of a track. Paths must be valid scene-tree paths to a node, and must be specified starting from the parent node of the node that will reproduce the animation. Tracks that control properties or bones must append their name after the path, separated by ":". Example: "character/skeleton:ankle" or "character/mesh:transform/local:" - </description> - </method> - <method name="track_move_up" > - <argument index="0" name="idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="track_move_down" > - <argument index="0" name="idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="transform_track_insert_key" > - <return type="int"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="time" type="real"> - </argument> - <argument index="2" name="loc" type="Vector3"> - </argument> - <argument index="3" name="rot" type="Quat"> - </argument> - <argument index="4" name="scale" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="track_insert_key" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="key" type="real"> - </argument> - <argument index="2" name="arg2" type="var"> - </argument> - <argument index="3" name="arg3" type="real"> - </argument> - <description> - </description> - </method> - <method name="track_remove_key" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="key_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="track_get_key_count" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <description> - Return the amount of keys in a given track. - </description> - </method> - <method name="track_get_key_value" qualifiers="const" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="track_get_key_time" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - Return the time at which the key is located. - </description> - </method> - <method name="track_find_key" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="time" type="real"> - </argument> - <argument index="2" name="exact" type="bool" default="false"> - </argument> - <description> - </description> - </method> - <method name="track_set_interpolation_type" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="interpolation" type="int"> - </argument> - <description> - </description> - </method> - <method name="track_get_interpolation_type" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="transform_track_interpolate" qualifiers="const" > - <return type="Array"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="time_sec" type="real"> - </argument> - <description> - </description> - </method> - <method name="value_track_interpolate" qualifiers="const" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="time_sec" type="real"> - </argument> - <description> - </description> - </method> - <method name="blend_track_interpolate" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="time_sec" type="real"> - </argument> - <description> - </description> - </method> - <method name="property_track_get_key_indices" qualifiers="const" > - <return type="IntArray"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="time_sec" type="real"> - </argument> - <argument index="2" name="delta" type="real"> - </argument> - <description> - </description> - </method> - <method name="property_track_get_key_value" qualifiers="const" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="key_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="property_track_get_name" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="key_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="method_track_get_key_indices" qualifiers="const" > - <return type="IntArray"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="time_sec" type="real"> - </argument> - <argument index="2" name="delta" type="real"> - </argument> - <description> - </description> - </method> - <method name="method_track_get_name" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="key_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="method_track_get_params" qualifiers="const" > - <return type="Array"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="key_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_length" > - <argument index="0" name="time_sec" type="real"> - </argument> - <description> - Set the total length of the animation (in seconds). Note that length is not delimited by the last key, as this one may be before or after the end to ensure correct interpolation and looping. - </description> - </method> - <method name="get_length" qualifiers="const" > - <return type="real"> - </return> - <description> - Return the total length of the animation (in seconds). - </description> - </method> - <method name="set_loop" > - <argument index="0" name="enabled" type="bool"> - </argument> - <description> - Set a flag indicating that the animation must loop. This is uses for correct interpolation of animation cycles, and for hinting the player that it must restart the animation once it's over. - </description> - </method> - <method name="has_loop" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return wether the animation has the loop flag set. - </description> - </method> - </methods> - <constants> - <constant name="INTERPOLATION_CUBIC" value="2"> - </constant> - <constant name="TYPE_TRANSFORM" value="0"> - Transform tracks are used to change node local transforms or skeleton pose bones. Transitions are Interpolated. - </constant> - <constant name="TYPE_BLEND" value="4"> - </constant> - <constant name="TYPE_PROPERTY" value="2"> - TODO will be changed and bleh - </constant> - <constant name="TYPE_VALUE" value="1"> - Value tracks set values in node properties, but only those which can be Interpolated. - </constant> - <constant name="INTERPOLATION_NEAREST" value="0"> - </constant> - <constant name="INTERPOLATION_LINEAR" value="1"> - </constant> - <constant name="TYPE_METHOD" value="3"> - </constant> - </constants> -</class> -<class name="AnimationPlayer" inherits="Misc" category="Nodes/Animation Nodes"> - <brief_description> - Container and player of [Animaton] resources. - </brief_description> - <description> - An animation player is used for general purpose playback of [Animation] resources. It contains a dictionary of animations (referenced by name) and custom blend times between their transitions. Additionally, animations can be played and blended in diferent channels. - </description> - <methods> - <method name="add_animation" > - <return type="int"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="animation" type="Object"> - </argument> - <description> - Add an animation resource to the player, which will be later referenced by the "name" argument. - </description> - </method> - <method name="remove_animation" > - <argument index="0" name="name" type="String"> - </argument> - <description> - Remove an animation from the player (by supplying the same name used to add it). - </description> - </method> - <method name="rename_animation" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="newname" type="String"> - </argument> - <description> - </description> - </method> - <method name="has_animation" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <description> - Request wether an [Animation] name exist within the player. - </description> - </method> - <method name="get_animation" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <description> - Get an [Animation] resource by requesting a name. - </description> - </method> - <method name="get_animation_list" qualifiers="const" > - <return type="StringArray"> - </return> - <description> - Get the list of names of the animations stored in the player. - </description> - </method> - <method name="set_blend_time" > - <argument index="0" name="anim_from" type="String"> - </argument> - <argument index="1" name="anim_to" type="String"> - </argument> - <argument index="2" name="sec" type="real"> - </argument> - <description> - Specify a blend time (in seconds) between two animations, referemced by their names. - </description> - </method> - <method name="get_blend_time" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="anim_from" type="String"> - </argument> - <argument index="1" name="anim_to" type="String"> - </argument> - <description> - Get the blend time between two animations, referemced by their names. - </description> - </method> - <method name="play" > - <argument index="0" name="name" type="String" default=""""> - </argument> - <argument index="1" name="channel" type="int" default="0"> - </argument> - <description> - Start playback of an animation (referenced by "name"). Optionally a channel can be specified. - </description> - </method> - <method name="stop" > - <argument index="0" name="channel" type="int" default="0"> - </argument> - <description> - Start playback of an animation channel. (or channel 0 if none is provided). - </description> - </method> - <method name="stop_all" > - <description> - Stop playback on all animation channels. - </description> - </method> - <method name="is_playing" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="channel" type="int" default="0"> - </argument> - <description> - Return wether an animation chanel is playing (or channel 0 if none is provided). - </description> - </method> - <method name="get_current_animation" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="channel" type="int" default="0"> - </argument> - <description> - Return the name of the animation being played in a channel (or channel 0 if none is provided). - </description> - </method> - <method name="set_pause" > - <argument index="0" name="paused" type="bool"> - </argument> - <description> - Pause the playback in all animation channels. - </description> - </method> - <method name="is_paused" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return [html i]true[html /i] if all playback is paused. - </description> - </method> - <method name="set_speed" > - <argument index="0" name="speed" type="real"> - </argument> - <argument index="1" name="channel" type="int" default="0"> - </argument> - <description> - Set a speed scaling ratio in a given animation channel (or channel 0 if none is provided). Default ratio is [html i]1[html /i] (no scaling). - </description> - </method> - <method name="get_speed" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="channel" type="int" default="0"> - </argument> - <description> - Get the speed scaling ratio in a given animation channel (or channel 0 if none is provided). Default ratio is [html i]1[html /i] (no scaling). - </description> - </method> - <method name="seek" > - <argument index="0" name="pos_sec" type="real"> - </argument> - <argument index="1" name="channel" type="int" default="0"> - </argument> - <description> - Seek the animation in an animation channel (or channel 0 if none is provided) to a specific position (in seconds). - </description> - </method> - <method name="get_pos" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="channel" type="int" default="0"> - </argument> - <description> - Return the playback position (in seconds) in an animation channel (or channel 0 if none is provided) - </description> - </method> - <method name="find_animation" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="animation" type="Object"> - </argument> - <description> - </description> - </method> - <method name="clear_caches" > - <description> - The animation player creates caches for faster access to the nodes it will animate. However, if a specific node is removed, it may not notice it, so clear_caches will force the player to search for the nodes again. - </description> - </method> - </methods> - <constants> - <constant name="MAX_CHANNELS" value="8"> - Maximum amount of animation channels. - </constant> - </constants> -</class> -<class name="AnimationTreePlayer" inherits="Node" category="Nodes/Animation Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="add_node" > - <argument index="0" name="type" type="int"> - </argument> - <argument index="1" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_node_id" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <description> - </description> - </method> - <method name="node_set_name" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="name" type="String"> - </argument> - <description> - </description> - </method> - <method name="node_get_name" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="node_get_input_count" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="animation_node_set_animation" > - <argument index="0" name="arg0" type="int"> - </argument> - <argument index="1" name="arg1" type="Object"> - </argument> - <description> - </description> - </method> - <method name="animation_node_get_animation" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="arg0" type="int"> - </argument> - <description> - </description> - </method> - <method name="oneshot_node_set_fadein_time" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="time_sec" type="real"> - </argument> - <description> - </description> - </method> - <method name="oneshot_node_get_fadein_time" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="oneshot_node_set_fadeout_time" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="time_sec" type="real"> - </argument> - <description> - </description> - </method> - <method name="oneshot_node_get_fadeout_time" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="oneshot_node_set_autorestart" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="oneshot_node_set_autorestart_delay" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="delay_sec" type="real"> - </argument> - <description> - </description> - </method> - <method name="oneshot_node_set_autorestart_random_delay" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="rand_sec" type="real"> - </argument> - <description> - </description> - </method> - <method name="oneshot_node_has_autorestart" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="oneshot_node_get_autorestart_delay" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="oneshot_node_get_autorestart_random_delay" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="oneshot_node_start" > - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="oneshot_node_stop" > - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="oneshot_node_is_active" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="mix_node_set_amount" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="ratio" type="real"> - </argument> - <description> - </description> - </method> - <method name="mix_node_get_amount" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="blend2_node_set_amount" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="blend" type="real"> - </argument> - <description> - </description> - </method> - <method name="blend2_node_get_amount" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="blend3_node_set_amount" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="blend" type="real"> - </argument> - <description> - </description> - </method> - <method name="blend3_node_get_amount" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="blend4_node_set_amount" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="blend" type="Vector2"> - </argument> - <description> - </description> - </method> - <method name="blend4_node_get_amount" qualifiers="const" > - <return type="Vector2"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="timescale_node_set_scale" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="scale" type="real"> - </argument> - <description> - </description> - </method> - <method name="timescale_node_get_scale" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="timeseek_node_seek" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="pos_sec" type="real"> - </argument> - <description> - </description> - </method> - <method name="transition_node_set_input_count" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="count" type="int"> - </argument> - <description> - </description> - </method> - <method name="transition_node_get_input_count" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="transition_node_delete_input" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="input_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="transition_node_set_input_auto_advance" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="input_idx" type="int"> - </argument> - <argument index="2" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="transition_node_has_input_auto_advance" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="input_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="transition_node_set_xfade_time" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="time_sec" type="real"> - </argument> - <description> - </description> - </method> - <method name="transition_node_get_xfade_time" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="transition_node_set_current" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="input_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="transition_node_get_current" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="node_set_pos" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="screen_pos" type="Vector2"> - </argument> - <description> - </description> - </method> - <method name="node_get_pos" qualifiers="const" > - <return type="Vector2"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="remove_node" > - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="connect" > - <return type="int"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="dst_id" type="int"> - </argument> - <argument index="2" name="dst_input_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="is_connected" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="dst_id" type="int"> - </argument> - <argument index="2" name="dst_input_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="disconnect" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="dst_input_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_active" > - <argument index="0" name="enabled" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_active" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_base_path" > - <argument index="0" name="path" type="NodePath"> - </argument> - <description> - </description> - </method> - <method name="get_base_path" qualifiers="const" > - <return type="NodePath"> - </return> - <description> - </description> - </method> - <method name="reset" > - <description> - </description> - </method> - <method name="recompute_caches" > - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="AudioServer" inherits="Object" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="sample_create" > - <return type="RID"> - </return> - <argument index="0" name="format" type="int"> - </argument> - <argument index="1" name="stereo" type="bool"> - </argument> - <argument index="2" name="length" type="int"> - </argument> - <description> - </description> - </method> - <method name="sample_set_description" > - <argument index="0" name="sample" type="RID"> - </argument> - <argument index="1" name="description" type="String"> - </argument> - <description> - </description> - </method> - <method name="sample_get_description" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="sample" type="RID"> - </argument> - <argument index="1" name="arg1" type="String"> - </argument> - <description> - </description> - </method> - <method name="sample_get_format" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="sample" type="RID"> - </argument> - <description> - </description> - </method> - <method name="sample_is_stereo" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="sample" type="RID"> - </argument> - <description> - </description> - </method> - <method name="sample_get_length" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="sample" type="RID"> - </argument> - <description> - </description> - </method> - <method name="sample_set_signed_data" > - <argument index="0" name="sample" type="RID"> - </argument> - <argument index="1" name="data" type="RealArray"> - </argument> - <description> - </description> - </method> - <method name="sample_set_data" > - <argument index="0" name="sample" type="RID"> - </argument> - <argument index="1" name="arg1" type="RawArray"> - </argument> - <description> - </description> - </method> - <method name="sample_get_data" qualifiers="const" > - <return type="RawArray"> - </return> - <argument index="0" name="sample" type="RID"> - </argument> - <description> - </description> - </method> - <method name="sample_set_mix_rate" > - <argument index="0" name="sample" type="RID"> - </argument> - <argument index="1" name="mix_rate" type="int"> - </argument> - <description> - </description> - </method> - <method name="sample_get_mix_rate" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="sample" type="RID"> - </argument> - <description> - </description> - </method> - <method name="sample_set_loop_format" > - <argument index="0" name="sample" type="RID"> - </argument> - <argument index="1" name="loop_format" type="int"> - </argument> - <description> - </description> - </method> - <method name="sample_get_loop_format" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="sample" type="RID"> - </argument> - <description> - </description> - </method> - <method name="sample_set_loop_begin" > - <argument index="0" name="sample" type="RID"> - </argument> - <argument index="1" name="pos" type="int"> - </argument> - <description> - </description> - </method> - <method name="sample_get_loop_begin" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="sample" type="RID"> - </argument> - <description> - </description> - </method> - <method name="sample_set_loop_end" > - <argument index="0" name="sample" type="RID"> - </argument> - <argument index="1" name="pos" type="int"> - </argument> - <description> - </description> - </method> - <method name="sample_get_loop_end" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="sample" type="RID"> - </argument> - <description> - </description> - </method> - <method name="voice_create" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="voice_play" > - <argument index="0" name="voice" type="RID"> - </argument> - <argument index="1" name="sample" type="RID"> - </argument> - <description> - </description> - </method> - <method name="voice_set_volume" > - <argument index="0" name="voice" type="RID"> - </argument> - <argument index="1" name="volume" type="real"> - </argument> - <description> - </description> - </method> - <method name="voice_set_pan" > - <argument index="0" name="voice" type="RID"> - </argument> - <argument index="1" name="pan" type="real"> - </argument> - <argument index="2" name="depth" type="real" default="0"> - </argument> - <argument index="3" name="height" type="real" default="0"> - </argument> - <description> - </description> - </method> - <method name="voice_set_filter" > - <argument index="0" name="voice" type="RID"> - </argument> - <argument index="1" name="type" type="int"> - </argument> - <argument index="2" name="cutoff" type="real"> - </argument> - <argument index="3" name="resonance" type="real"> - </argument> - <argument index="4" name="gain" type="real" default="0"> - </argument> - <description> - </description> - </method> - <method name="voice_set_chorus" > - <argument index="0" name="voice" type="RID"> - </argument> - <argument index="1" name="chorus" type="real"> - </argument> - <description> - </description> - </method> - <method name="voice_set_reverb" > - <argument index="0" name="voice" type="RID"> - </argument> - <argument index="1" name="room" type="int"> - </argument> - <argument index="2" name="reverb" type="real"> - </argument> - <description> - </description> - </method> - <method name="voice_set_mix_rate" > - <argument index="0" name="voice" type="RID"> - </argument> - <argument index="1" name="rate" type="int"> - </argument> - <description> - </description> - </method> - <method name="voice_set_positional" > - <argument index="0" name="voice" type="RID"> - </argument> - <argument index="1" name="enabled" type="bool"> - </argument> - <description> - </description> - </method> - <method name="voice_get_volume" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="RID"> - </argument> - <description> - </description> - </method> - <method name="voice_get_pan" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="RID"> - </argument> - <description> - </description> - </method> - <method name="voice_get_pan_height" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="RID"> - </argument> - <description> - </description> - </method> - <method name="voice_get_pan_depth" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="RID"> - </argument> - <description> - </description> - </method> - <method name="voice_get_filter_type" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="voice" type="RID"> - </argument> - <description> - </description> - </method> - <method name="voice_get_filter_cutoff" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="RID"> - </argument> - <description> - </description> - </method> - <method name="voice_get_filter_resonance" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="RID"> - </argument> - <description> - </description> - </method> - <method name="voice_get_chorus" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="RID"> - </argument> - <description> - </description> - </method> - <method name="voice_get_reverb_type" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="voice" type="RID"> - </argument> - <description> - </description> - </method> - <method name="voice_get_reverb" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="RID"> - </argument> - <description> - </description> - </method> - <method name="voice_get_mix_rate" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="voice" type="RID"> - </argument> - <description> - </description> - </method> - <method name="voice_is_positional" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="voice" type="RID"> - </argument> - <description> - </description> - </method> - <method name="voice_stop" > - <argument index="0" name="voice" type="RID"> - </argument> - <description> - </description> - </method> - <method name="free" > - <argument index="0" name="rid" type="RID"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - <constant name="SAMPLE_LOOP_PING_PONG" value="2"> - </constant> - <constant name="SAMPLE_FORMAT_IMA_ADPCM" value="2"> - </constant> - <constant name="FILTER_HIPASS" value="3"> - </constant> - <constant name="FILTER_NONE" value="0"> - </constant> - <constant name="REVERB_HALL" value="3"> - </constant> - <constant name="REVERB_MEDIUM" value="1"> - </constant> - <constant name="REVERB_SMALL" value="0"> - </constant> - <constant name="FILTER_LOWPASS" value="1"> - </constant> - <constant name="SAMPLE_LOOP_FORWARD" value="1"> - </constant> - <constant name="REVERB_LARGE" value="2"> - </constant> - <constant name="SAMPLE_FORMAT_PCM16" value="1"> - </constant> - <constant name="FILTER_BANDLIMIT" value="6"> - </constant> - <constant name="FILTER_NOTCH" value="4"> - </constant> - <constant name="FILTER_BANDPASS" value="2"> - </constant> - <constant name="SAMPLE_FORMAT_PCM8" value="0"> - </constant> - <constant name="SAMPLE_LOOP_NONE" value="0"> - </constant> - </constants> -</class> -<class name="AudioServerSW" inherits="AudioServer" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="AudioStream" inherits="Resource" category="Resources"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="play" > - <description> - </description> - </method> - <method name="stop" > - <description> - </description> - </method> - <method name="is_playing" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_loop" > - <argument index="0" name="enabled" type="bool"> - </argument> - <description> - </description> - </method> - <method name="has_loop" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="get_stream_name" qualifiers="const" > - <return type="String"> - </return> - <description> - </description> - </method> - <method name="get_loop_count" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="seek_pos" > - <argument index="0" name="pos" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_pos" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="get_update_mode" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="update" > - <description> - </description> - </method> - </methods> - <constants> - <constant name="UPDATE_IDLE" value="1"> - </constant> - <constant name="UPDATE_THREAD" value="2"> - </constant> - <constant name="UPDATE_NONE" value="0"> - </constant> - </constants> -</class> -<class name="AudioStreamOGG" inherits="AudioStream" category="Resources"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="BCSFX" inherits="ScenarioFX" category="Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="BGColorFX" inherits="ScenarioFX" category="Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="BGImageFX" inherits="ScenarioFX" category="Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="BaseButton" inherits="Control" category="Nodes/GUI Nodes"> - <brief_description> - Provides a base class for different kinds of buttons. - </brief_description> - <description> - BaseButton is the abstract base class for buttons, so it shouldn't be used directly (It doesnt display anything). Other types of buttons inherit from it. - </description> - <methods> - <method name="set_pressed" > - <argument index="0" name="pressed" type="bool"> - </argument> - <description> - Set the button to pressed state (only if toggle_mode is active). - </description> - </method> - <method name="is_pressed" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return when the button is pressed (only if toggle_mode is active). - </description> - </method> - <method name="set_toggle_mode" > - <argument index="0" name="enabled" type="bool"> - </argument> - <description> - Set the button toggle_mode property. Toggle mode makes the button flip state between pressed and unpressed each time its area is clicked. - </description> - </method> - <method name="is_toggle_mode" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return the toggle_mode property (see [method set_toggle_mode]). - </description> - </method> - <method name="set_disabled" > - <argument index="0" name="disabled" type="bool"> - </argument> - <description> - Set the button into disabled state. When a button is disabled, it can't be clicked or toggled. - </description> - </method> - <method name="is_disabled" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return wether the button is in disabled state (see [method set_disabled]). - </description> - </method> - <method name="set_click_on_press" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - Set the button click_on_press mode. This mode generates click signals when a mousebutton or key is just pressed (by default signals are generated when the button/keys are released and both press and release occur in the visual area of the Button). - </description> - </method> - <method name="get_click_on_press" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return the state of the click_on_press property (see [method set_click_on_press]). - </description> - </method> - </methods> - <signals> - <signal name="toggled"> - <argument index="0" name="pressed" type="bool"> - </argument> - <description> - This signal is emitted when the button was just toggled between pressed and normal states (only if toggle_mode is active). The new state is contained in the [html i]pressed[html /i] argument. - </description> - </signal> - <signal name="pressed"> - <description> - This signal is emitted every time the button is pressed or toggled. - </description> - </signal> - </signals> - <constants> - </constants> -</class> -<class name="BodyShape" inherits="Spatial" category="Nodes/3D/3D Physics Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="BoxShape" inherits="Shape" category="Resources"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_extents" > - <argument index="0" name="extents" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="get_extents" qualifiers="const" > - <return type="Vector3"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="Button" inherits="BaseButton" category="Nodes/GUI Nodes"> - <brief_description> - Standard themed Button. - </brief_description> - <description> - Button is just the standard themed button: [html image src="images/button_example.png"/] It can contain a text and an icon, and will display them according to the current theme. - </description> - <methods> - <method name="set_text" > - <argument index="0" name="text" type="String"> - </argument> - <description> - Set the button text, which will be displayed inside the button area. - </description> - </method> - <method name="get_text" qualifiers="const" > - <return type="String"> - </return> - <description> - Return the button text. - </description> - </method> - <method name="set_icon" > - <argument index="0" name="texture" type="Object"> - </argument> - <description> - Set the button icon, which will be displayed to the left of the text. - </description> - </method> - <method name="get_icon" qualifiers="const" > - <return type="Object"> - </return> - <description> - Return the button icon. - </description> - </method> - <method name="set_flat" > - <argument index="0" name="enabled" type="bool"> - </argument> - <description> - Set the [html i]flat[html /i] property of a Button. Flat buttons don't display decoration unless hoevered or pressed. - </description> - </method> - <method name="set_clip_text" > - <argument index="0" name="enabled" type="bool"> - </argument> - <description> - Set the [html i]clip_text[html /i] property of a Button. When this property is enabled, text that is too large to fit the button is clipped, when disabled (default) the Button will always be wide enough to hold the text. - </description> - </method> - <method name="get_clip_text" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return the state of the [html i]clip_text[html /i] property (see [method set_clip_text]) - </description> - </method> - <method name="is_flat" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return the state of the [html i]flat[html /i] property (see [method set_flat]) - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="Camera" inherits="Spatial" category="Nodes/3D"> - <brief_description> - Camera node, displays from a point of view. - </brief_description> - <description> - Camera is a special node that displays what is visible from its current location. Cameras register themselves in the nearest [Viewport] node (when ascending the tree). Only one camera can be active per viewport. If no viewport is available ascending the tree, the Camera will register in the global viewport. In other words, a Camera just provides [html i]3D[html /i] display capabilities to a [Viewport], and, without one, a [Scene] registered in that [Viewport] (or higher viewports) can't be displayed. - </description> - <methods> - <method name="project_ray_normal" qualifiers="const" > - <return type="Vector3"> - </return> - <argument index="0" name="screen_point" type="Vector2"> - </argument> - <description> - Return a normal vector in worldspace, that is the result of projecting a point on the [Viewport] rectangle by the camera proyection. This is useful for casting rays in the form of (origin,normal) for object intersection or picking. - </description> - </method> - <method name="project_ray_origin" qualifiers="const" > - <return type="Vector3"> - </return> - <argument index="0" name="screen_point" type="Vector2"> - </argument> - <description> - Return a 3D position in worldspace, that is the result of projecting a point on the [Viewport] rectangle by the camera proyection. This is useful for casting rays in the form of (origin,normal) for object intersection or picking. - </description> - </method> - <method name="unproject_position" qualifiers="const" > - <return type="Vector2"> - </return> - <argument index="0" name="world_point" type="Vector3"> - </argument> - <description> - Return how a 3D point in worldpsace maps to a 2D coordinate in the [Viewport] rectangle. - </description> - </method> - <method name="set_perspective" > - <argument index="0" name="fov" type="real"> - </argument> - <argument index="1" name="z_near" type="real"> - </argument> - <argument index="2" name="z_far" type="real"> - </argument> - <description> - Set the camera projection to perspective mode, by specifying a [html i]FOV[html /i] angle in degrees (FOV means Field of View), and the [html i]near[html /i] and [html i]far[html /i] clip planes in worldspace units. - </description> - </method> - <method name="set_orthogonal" > - <argument index="0" name="size" type="real"> - </argument> - <argument index="1" name="z_near" type="real"> - </argument> - <argument index="2" name="z_far" type="real"> - </argument> - <description> - Set the camera projection to orthogonal mode, by specifying a rectangle and the [html i]near[html /i] and [html i]far[html /i] clip planes in worldspace units. (As a hint, 2D games often use this projection, with values specified in pixels) - </description> - </method> - <method name="make_current" > - <description> - Make this camera the current Camera for the [Viewport] (see class description). If the Camera Node is outside the scene tree, it will attempt to become current once it's added. - </description> - </method> - <method name="clear_current" > - <description> - </description> - </method> - <method name="is_current" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return wether the Camera is the current one in the [Viewport], or plans to become current (if outside the scene tree). - </description> - </method> - <method name="get_camera_transform" qualifiers="const" > - <return type="Transform"> - </return> - <description> - Get the camera transform. Subclassed cameras (such as CharacterCamera) may provide different transforms than the [Node] transform. - </description> - </method> - <method name="get_fov" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - </methods> - <constants> - <constant name="PROJECTION_PERSPECTIVE" value="0"> - Perspective Projection (object's size on the screen becomes smaller when far away). - </constant> - <constant name="PROJECTION_ORTHOGONAL" value="1"> - Orthogonal Projection (objects remain the same size on the screen no matter how far away they are). - </constant> - </constants> -</class> -<class name="CanvasItem" inherits="Node" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="edit_set_state" > - <argument index="0" name="state" type="var"> - </argument> - <description> - </description> - </method> - <method name="edit_get" qualifiers="const" > - <description> - </description> - </method> - <method name="edit_set_rect" > - <argument index="0" name="rect" type="Rect2"> - </argument> - <description> - </description> - </method> - <method name="edit_rotate" > - <argument index="0" name="degrees" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_item_rect" qualifiers="const" > - <return type="Rect2"> - </return> - <description> - </description> - </method> - <method name="get_canvas_item" qualifiers="const" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="is_visible" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="is_hidden" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="show" > - <description> - </description> - </method> - <method name="hide" > - <description> - </description> - </method> - <method name="update" > - <description> - </description> - </method> - <method name="set_as_toplevel" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_set_as_toplevel" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_blend_mode" > - <argument index="0" name="blend_mode" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_blend_mode" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_opacity" > - <argument index="0" name="opacity" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_opacity" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="set_self_opacity" > - <argument index="0" name="self_opacity" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_self_opacity" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - </methods> - <signals> - <signal name="item_rect_changed"> - <description> - </description> - </signal> - <signal name="draw"> - <description> - </description> - </signal> - <signal name="visibility_changed"> - <description> - </description> - </signal> - <signal name="hide"> - <description> - </description> - </signal> - </signals> - <constants> - <constant name="NOTIFICATION_EXIT_CANVAS" value="33"> - </constant> - <constant name="NOTIFICATION_DRAW" value="30"> - </constant> - <constant name="BLEND_MODE_MUL" value="3"> - </constant> - <constant name="BLEND_MODE_MIX" value="0"> - </constant> - <constant name="NOTIFICATION_ENTER_CANVAS" value="32"> - </constant> - <constant name="NOTIFICATION_VISIBILITY_CHANGED" value="31"> - </constant> - <constant name="BLEND_MODE_ADD" value="1"> - </constant> - <constant name="BLEND_MODE_SUB" value="2"> - </constant> - </constants> -</class> -<class name="CapsuleShape" inherits="Shape" category="Resources"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_radius" > - <argument index="0" name="radius" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_radius" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="set_height" > - <argument index="0" name="height" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_height" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="CheckButton" inherits="BaseButton" category="Nodes/GUI Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_text" > - <argument index="0" name="text" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_text" qualifiers="const" > - <return type="String"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="ColorPicker" inherits="Control" category="Nodes/GUI Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_color" > - <argument index="0" name="arg0" type="Color"> - </argument> - <description> - </description> - </method> - <method name="get_color" qualifiers="const" > - <return type="Color"> - </return> - <description> - </description> - </method> - </methods> - <signals> - <signal name="color_changed"> - <argument index="0" name="color" type="Color"> - </argument> - <description> - </description> - </signal> - </signals> - <constants> - </constants> -</class> -<class name="ConcavePolygonShape" inherits="Shape" category="Resources"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_faces" > - <argument index="0" name="faces" type="Vector3Array"> - </argument> - <description> - </description> - </method> - <method name="get_faces" qualifiers="const" > - <return type="Vector3Array"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="ConfirmationDialog" inherits="Popup" category="Nodes/GUI Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="get_ok" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="get_cancel" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="set_text" > - <argument index="0" name="text" type="String"> - </argument> - <description> - </description> - </method> - <method name="set_hide_on_ok" > - <argument index="0" name="enabled" type="bool"> - </argument> - <description> - </description> - </method> - <method name="get_hide_on_ok" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="register_text_enter" > - <argument index="0" name="line_edit" type="Object"> - </argument> - <description> - </description> - </method> - </methods> - <signals> - <signal name="confirmed"> - <description> - </description> - </signal> - </signals> - <constants> - </constants> -</class> -<class name="Control" inherits="CanvasItem" category="Core"> - <brief_description> - Control is the base class Node for all the GUI components. - </brief_description> - <description> - Control is the base class Node for all the GUI components. Every GUI component inherits from it, directly or indirectly. Control Nodes contain positions relative to their parent control nodes. In this way, sections of the scene tree made of contiguous Control Nodes, become user interfaces.[html br/] 	Controls contain a [html i]canvas item[html /i] RID from the visual server, and can draw to it when receiving a NOTIFICATION_DRAW.[html br/] 	TODO: Explain margins and anchors[html br/] 	TODO: explain focus[html br/] - </description> - <methods> - <method name="accept_event" > - <description> - </description> - </method> - <method name="get_minimum_size" qualifiers="const" > - <return type="Vector2"> - </return> - <description> - Return the minimum size this Control can shrink to. A control will never be displayed or resized smaller than its minimum size. - </description> - </method> - <method name="is_window" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return wether this control is a [html i]window[html /i]. Controls are considered windows when their parent [Node] is not a Control. - </description> - </method> - <method name="get_window" qualifiers="const" > - <return type="Object"> - </return> - <description> - Return the [html i]window[html /i] for this control, ascending the scene tree (see [method is_window]). - </description> - </method> - <method name="set_anchor" > - <argument index="0" name="margin" type="int"> - </argument> - <argument index="1" name="anchor_mode" type="int"> - </argument> - <description> - Change the anchor (ANCHOR_BEGIN, ANCHOR_END, ANCHOR_RATIO) type for a margin (MARGIN_LEFT, MARGIN_TOP, MARGIN_RIGHT, MARGIN_BOTTOM). Changing the anchor mode converts the current margin offset from the previos anchor mode to the new one, so margin offsets ([method set_margin]) must be done after setting anchors, or at the same time ([method set_anchor_and_margin]). - </description> - </method> - <method name="get_anchor" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="margin" type="int"> - </argument> - <description> - Return the anchor type (ANCHOR_BEGIN, ANCHOR_END, ANCHOR_RATIO) for a given margin (MARGIN_LEFT, MARGIN_TOP, MARGIN_RIGHT, MARGIN_BOTTOM). - </description> - </method> - <method name="set_margin" > - <argument index="0" name="margin" type="int"> - </argument> - <argument index="1" name="offset" type="real"> - </argument> - <description> - Set a margin offset. Margin can be one of (MARGIN_LEFT, MARGIN_TOP, MARGIN_RIGHT, MARGIN_BOTTOM). Offset value being set depends on the anchor mode. - </description> - </method> - <method name="set_anchor_and_margin" > - <argument index="0" name="margin" type="int"> - </argument> - <argument index="1" name="anchor_mode" type="int"> - </argument> - <argument index="2" name="offset" type="real"> - </argument> - <description> - Change the anchor (ANCHOR_BEGIN, ANCHOR_END, ANCHOR_RATIO) type for a margin (MARGIN_LEFT, MARGIN_TOP, MARGIN_RIGHT, MARGIN_BOTTOM), and also set its offset. This is a helper (see [method set_anchor] and [method set_margin]). - </description> - </method> - <method name="set_begin" > - <argument index="0" name="pos" type="Vector2"> - </argument> - <description> - Sets MARGIN_LEFT and MARGIN_TOP at the same time. This is a helper (see [method set_margin]). - </description> - </method> - <method name="set_end" > - <argument index="0" name="pos" type="Vector2"> - </argument> - <description> - Sets MARGIN_RIGHT and MARGIN_BOTTOM at the same time. This is a helper (see [method set_margin]). - </description> - </method> - <method name="set_pos" > - <argument index="0" name="pos" type="Vector2"> - </argument> - <description> - Move the Control to a new position, relative to the top-left corner of the parent Control, changing all margins if needed and without changing current anchor mode. This is a helper (see [method set_margin]). - </description> - </method> - <method name="set_size" > - <argument index="0" name="size" type="Vector2"> - </argument> - <description> - Changes MARGIN_RIGHT and MARGIN_BOTTOM to fit a given size. This is a helper (see [method set_margin]). - </description> - </method> - <method name="set_global_pos" > - <argument index="0" name="pos" type="Vector2"> - </argument> - <description> - Move the Control to a new position, relative to the top-left corner of the [html i]window[html /i] Control, and without changing current anchor mode. (see [method set_margin]). - </description> - </method> - <method name="get_margin" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="margin" type="int"> - </argument> - <description> - Return a margin offset. Margin can be one of (MARGIN_LEFT, MARGIN_TOP, MARGIN_RIGHT, MARGIN_BOTTOM). Offset value being returned depends on the anchor mode. - </description> - </method> - <method name="get_begin" qualifiers="const" > - <return type="Vector2"> - </return> - <description> - </description> - </method> - <method name="get_end" qualifiers="const" > - <return type="Vector2"> - </return> - <description> - Returns MARGIN_LEFT and MARGIN_TOP at the same time. This is a helper (see [method set_margin]). - </description> - </method> - <method name="get_pos" qualifiers="const" > - <return type="Vector2"> - </return> - <description> - Returns the Control position, relative to the top-left corner of the parent Control and independly of the anchor mode. - </description> - </method> - <method name="get_size" qualifiers="const" > - <return type="Vector2"> - </return> - <description> - Returns the size of the Control, computed from all margins, however the size returned will [html b]never be smaller than the minimum size reported by [method get_minimum_size][html /b]. This means that even if end position of the Control rectangle is smaller than the begin position, the Control will still display and interact correctly. (see description, [method get_minimum_size], [method set_margin], [method set_anchor]). - </description> - </method> - <method name="get_global_pos" qualifiers="const" > - <return type="Vector2"> - </return> - <description> - Returns the Control position, relative to the top-left corner of the parent Control and independent of the anchor mode. - </description> - </method> - <method name="get_rect" qualifiers="const" > - <return type="Rect2"> - </return> - <description> - Return position and size of the Control, relative to the top-left corner of the parent Control. This is a helper (see [method get_pos],[method get_size]). - </description> - </method> - <method name="get_global_rect" qualifiers="const" > - <return type="Rect2"> - </return> - <description> - Return position and size of the Control, relative to the top-left corner of the [html i]window[html /i] Control. This is a helper (see [method get_global_pos],[method get_size]). - </description> - </method> - <method name="set_area_as_parent_rect" > - <description> - Change all margins and anchors, so this Control always takes up the same area as the parent Control. This is a helper (see [method set_anchor],[method set_margin]). - </description> - </method> - <method name="show_modal" > - <argument index="0" name="exclusive" type="bool" default="false"> - </argument> - <description> - Display a Control as modal. Control must be a subwindow (see [method set_as_subwindow]). Modal controls capture the input signals until closed or the area outside them is accessed. When a modal control loses focus, or the ESC key is pressed, they automatically hide. Modal controls are used extensively for popup dialogs and menus. - </description> - </method> - <method name="set_focus_mode" > - <argument index="0" name="mode" type="int"> - </argument> - <description> - Set the focus access mode for the control (FOCUS_NONE, FOCUS_CLICK, FOCUS_ALL). Only one Control can be focused at the same time, and it will receive keyboard signals. - </description> - </method> - <method name="has_focus" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return wether the Control is the current focused control (see [method set_focus_mode]). - </description> - </method> - <method name="grab_focus" > - <description> - Steal the focus from another control and become the focused control (see [method set_focus_mode]). - </description> - </method> - <method name="set_theme" > - <argument index="0" name="theme" type="Object"> - </argument> - <description> - Override whole the [Theme] for this Control and all its children controls. - </description> - </method> - <method name="get_theme" qualifiers="const" > - <return type="Object"> - </return> - <description> - Return a [Theme] override, if one exists (see [method set_theme]). - </description> - </method> - <method name="add_icon_override" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="texture" type="Object"> - </argument> - <description> - Override a single icon ([Texture]) in the theme of this Control. If texture is empty, override is cleared. - </description> - </method> - <method name="add_style_override" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="stylebox" type="Object"> - </argument> - <description> - Override a single stylebox ([Stylebox]) in the theme of this Control. If stylebox is empty, override is cleared. - </description> - </method> - <method name="add_font_override" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="font" type="Object"> - </argument> - <description> - Override a single font (font) in the theme of this Control. If font is empty, override is cleared. - </description> - </method> - <method name="add_color_override" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="color" type="Color"> - </argument> - <description> - </description> - </method> - <method name="add_constant_override" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="constant" type="int"> - </argument> - <description> - Override a single constant (integer) in the theme of this Control. If constant equals Theme.INVALID_CONSTANT, override is cleared. - </description> - </method> - <method name="get_parent_control" qualifiers="const" > - <return type="Object"> - </return> - <description> - Return the parent Control. Unlike get_parent() in [Node], only returns a valid object if the parent is a Control. - </description> - </method> - <method name="set_tooltip" > - <argument index="0" name="tooltip" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_tooltip" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="atpos" type="Vector2" default="Vector2(0,0)"> - </argument> - <description> - </description> - </method> - <method name="set_default_cursor_shape" > - <argument index="0" name="shape" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_default_cursor_shape" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="get_cursor_shape" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="pos" type="Vector2" default="Vector2(0,0)"> - </argument> - <description> - </description> - </method> - <method name="set_focus_neighbour" > - <argument index="0" name="margin" type="int"> - </argument> - <argument index="1" name="neighbour" type="NodePath"> - </argument> - <description> - </description> - </method> - <method name="get_focus_neighbour" qualifiers="const" > - <return type="NodePath"> - </return> - <argument index="0" name="margin" type="int"> - </argument> - <description> - </description> - </method> - </methods> - <signals> - <signal name="focus_enter"> - <description> - </description> - </signal> - <signal name="mouse_enter"> - <description> - </description> - </signal> - <signal name="resized"> - <description> - </description> - </signal> - <signal name="focus_exit"> - <description> - </description> - </signal> - <signal name="input_event"> - <description> - </description> - </signal> - <signal name="mouse_exit"> - <description> - </description> - </signal> - </signals> - <constants> - <constant name="CURSOR_FDIAGSIZE" value="12"> - </constant> - <constant name="CURSOR_CAN_DROP" value="7"> - </constant> - <constant name="CURSOR_DRAG" value="6"> - </constant> - <constant name="CURSOR_IBEAM" value="1"> - </constant> - <constant name="NOTIFICATION_FOCUS_ENTER" value="37"> - Control gained focus. - </constant> - <constant name="CURSOR_MOVE" value="13"> - </constant> - <constant name="NOTIFICATION_MOUSE_ENTER" value="35"> - Mouse pointer entered the area of the Control. - </constant> - <constant name="NOTIFICATION_RESIZED" value="34"> - Control changed size (get_size() reports the new size). - </constant> - <constant name="FOCUS_CLICK" value="1"> - Control can acquire focus only if clicked. - </constant> - <constant name="CURSOR_HELP" value="16"> - </constant> - <constant name="CURSOR_VSIZE" value="9"> - </constant> - <constant name="CURSOR_VSPLIT" value="14"> - </constant> - <constant name="CURSOR_BDIAGSIZE" value="11"> - </constant> - <constant name="CURSOR_CROSS" value="3"> - </constant> - <constant name="CURSOR_POINTING_HAND" value="2"> - </constant> - <constant name="NOTIFICATION_FOCUS_EXIT" value="38"> - Control lost focus. - </constant> - <constant name="FOCUS_NONE" value="0"> - Control can't acquire focus. - </constant> - <constant name="ANCHOR_BEGIN" value="0"> - X is relative to MARGIN_LEFT, Y is relative to MARGIN_TOP, - </constant> - <constant name="CURSOR_HSIZE" value="10"> - </constant> - <constant name="CURSOR_BUSY" value="5"> - </constant> - <constant name="CURSOR_ARROW" value="0"> - </constant> - <constant name="NOTIFICATION_MODAL_CLOSE" value="40"> - </constant> - <constant name="NOTIFICATION_MOUSE_EXIT" value="36"> - Mouse pointer exited the area of the Control. - </constant> - <constant name="FOCUS_ALL" value="2"> - Control can acquire focus if clicked, or by pressing TAB/Directionals in the keyboard from another Control. - </constant> - <constant name="CURSOR_HSPLIT" value="15"> - </constant> - <constant name="ANCHOR_RATIO" value="2"> - X and Y are a ratio (0 to 1) relative to the parent size 0 is left/top, 1 is right/bottom. - </constant> - <constant name="ANCHOR_END" value="1"> - X is relative to -MARGIN_RIGHT, Y is relative to -MARGIN_BOTTOM, - </constant> - <constant name="CURSOR_FORBIDDEN" value="8"> - </constant> - <constant name="CURSOR_WAIT" value="4"> - </constant> - <constant name="NOTIFICATION_THEME_CHANGED" value="39"> - </constant> - </constants> -</class> -<class name="ConvexPolygonShape" inherits="Shape" category="Resources"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_planes" > - <argument index="0" name="planes" type="Array"> - </argument> - <description> - </description> - </method> - <method name="get_planes" qualifiers="const" > - <return type="Array"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="GridMap" inherits="Spatial" category="Nodes/3D"> - <brief_description> - GridMap is like a tile map, but in 3D. - </brief_description> - <description> - GridMap is a 3D Tile map, using [html i]3D Cells[html /i] instead of tiles. On each cell, a mesh and a collision volume can be placed from a [MeshLibrary]. GridMap is used for designing worlds quickly. Despite that GridMaps can contain up to hundreds millions of cells, they are very optimized, and only use resources for the cells that contain items. - </description> - <methods> - <method name="set_theme" > - <argument index="0" name="theme" type="Object"> - </argument> - <description> - Set a MeshLibrary. Cell indices refer to items in the theme. - </description> - </method> - <method name="get_theme" qualifiers="const" > - <return type="Object"> - </return> - <description> - Get the current MeshLibrary (if exists). - </description> - </method> - <method name="set_cell_size" > - <argument index="0" name="size" type="real"> - </argument> - <description> - Set the size of a cell, in worldpsace units. All cells in a GridMap are the same size. - </description> - </method> - <method name="get_cell_size" qualifiers="const" > - <return type="real"> - </return> - <description> - Return the current cell size. - </description> - </method> - <method name="set_octant_size" > - <argument index="0" name="size" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_octant_size" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_width" > - <argument index="0" name="width" type="int"> - </argument> - <description> - Set the width of the GridMap. Width is the amount of cells i the direction of the X coordinate. - </description> - </method> - <method name="get_width" qualifiers="const" > - <return type="int"> - </return> - <description> - Get the width of the GridMap. Width is the amount of cells i the direction of the X coordinate. - </description> - </method> - <method name="set_height" > - <argument index="0" name="height" type="int"> - </argument> - <description> - Set the height of the GridMap. Height is the amount of cells i the direction of the Y coordinate. - </description> - </method> - <method name="get_height" qualifiers="const" > - <return type="int"> - </return> - <description> - Get the height of the GridMap. Height is the amount of cells i the direction of the Y coordinate. - </description> - </method> - <method name="set_depth" > - <argument index="0" name="depth" type="int"> - </argument> - <description> - Set the depth of the GridMap. Depth is the amount of cells i the direction of the Z coordinate. - </description> - </method> - <method name="get_depth" qualifiers="const" > - <return type="int"> - </return> - <description> - Get the depth of the GridMap. Depth is the amount of cells i the direction of the Z coordinate. - </description> - </method> - <method name="set_cell_item" > - <argument index="0" name="x" type="int"> - </argument> - <argument index="1" name="y" type="int"> - </argument> - <argument index="2" name="z" type="int"> - </argument> - <argument index="3" name="item" type="int"> - </argument> - <argument index="4" name="orientation" type="int" default="0"> - </argument> - <description> - Set a cell item (x,y,z pos). Cell items are indices to items in the [MeshLibrary]. - </description> - </method> - <method name="get_cell_item" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="x" type="int"> - </argument> - <argument index="1" name="y" type="int"> - </argument> - <argument index="2" name="z" type="int"> - </argument> - <description> - Get a cell item (x,y,z pos). Cell items are indices to items in the [MeshLibrary]. - </description> - </method> - <method name="get_cell_item_orientation" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="x" type="int"> - </argument> - <argument index="1" name="y" type="int"> - </argument> - <argument index="2" name="z" type="int"> - </argument> - <description> - </description> - </method> - <method name="resource_changed" > - <argument index="0" name="arg0" type="Object"> - </argument> - <description> - </description> - </method> - <method name="set_center_x" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="get_center_x" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_center_y" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="get_center_y" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_center_z" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="get_center_z" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_clip" > - <argument index="0" name="enabled" type="bool"> - </argument> - <argument index="1" name="clipabove" type="bool" default="true"> - </argument> - <argument index="2" name="floor" type="int" default="0"> - </argument> - <argument index="3" name="axis" type="int" default="0"> - </argument> - <description> - </description> - </method> - <method name="crate_area" > - <return type="int"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="area" type="AABB"> - </argument> - <description> - </description> - </method> - <method name="area_get_bounds" qualifiers="const" > - <return type="AABB"> - </return> - <argument index="0" name="area" type="int"> - </argument> - <description> - </description> - </method> - <method name="area_set_exterior_portal" > - <argument index="0" name="area" type="int"> - </argument> - <argument index="1" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="area_set_name" > - <argument index="0" name="area" type="int"> - </argument> - <argument index="1" name="name" type="String"> - </argument> - <description> - </description> - </method> - <method name="area_get_name" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="area" type="int"> - </argument> - <description> - </description> - </method> - <method name="area_is_exterior_portal" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="area" type="int"> - </argument> - <description> - </description> - </method> - <method name="area_set_portal_disable_distance" > - <argument index="0" name="area" type="int"> - </argument> - <argument index="1" name="distance" type="real"> - </argument> - <description> - </description> - </method> - <method name="area_get_portal_disable_distance" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="area" type="int"> - </argument> - <description> - </description> - </method> - <method name="area_set_portal_disable_color" > - <argument index="0" name="area" type="int"> - </argument> - <argument index="1" name="color" type="Color"> - </argument> - <description> - </description> - </method> - <method name="area_get_portal_disable_color" qualifiers="const" > - <return type="Color"> - </return> - <argument index="0" name="area" type="int"> - </argument> - <description> - </description> - </method> - <method name="erase_area" > - <argument index="0" name="area" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_unused_area_id" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - </methods> - <constants> - <constant name="INVALID_CELL_ITEM" value="-1"> - Value indicating that a cell item is not used or invalid. - </constant> - </constants> -</class> -<class name="MeshLibrary" inherits="Resource" category="Resources"> - <brief_description> - Theme for a [GridMap]. - </brief_description> - <description> - MeshLibrary is [Resource] containing the data used in a [GridMap]. It's filled with items, each containing a mesh and a collision shape. - </description> - <methods> - <method name="create_item" > - <argument index="0" name="id" type="int"> - </argument> - <description> - Create a new item, and assign it a given id. - </description> - </method> - <method name="set_item_name" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="name" type="String"> - </argument> - <description> - Set the name of an item, referenced by id. - </description> - </method> - <method name="set_item_mesh" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="mesh" type="Object"> - </argument> - <description> - Set the [Mesh] of an item, referenced by id. - </description> - </method> - <method name="set_item_shape" > - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="shape" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_item_name" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - Get the name of an item, referenced by id. - </description> - </method> - <method name="get_item_mesh" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - Get the [Mesh] of an item, referenced by id. - </description> - </method> - <method name="get_item_shape" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - </description> - </method> - <method name="remove_item" > - <argument index="0" name="id" type="int"> - </argument> - <description> - Remove an item, referenced by id. - </description> - </method> - <method name="clear" > - <description> - Clear all items contained in this resource. - </description> - </method> - <method name="get_item_list" qualifiers="const" > - <return type="IntArray"> - </return> - <description> - Get the list of item IDs contained in this theme. - </description> - </method> - <method name="get_last_unused_item_id" qualifiers="const" > - <return type="int"> - </return> - <description> - Get the last unused item id. This is useful for creating new item IDs. - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="CylinderShape" inherits="Shape" category="Resources"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_radius" > - <argument index="0" name="radius" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_radius" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="set_height" > - <argument index="0" name="height" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_height" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="DOFBlurFX" inherits="ScenarioFX" category="Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="DirectionalLight" inherits="Light" category="Nodes/3D/3D Visual Nodes/3D Light Nodes"> - <brief_description> - Directional Light, such as the Sun or the Moon. - </brief_description> - <description> - A DirectionalLight is a type of [Light] node that emits light constantly in one direction (the negative z axis of the node). It is used lights with strong intensity that are located far away from the scene to model sunlight or moonlight. The worldpace location of the DirectionalLight transform (origin) is ignored, only the basis is used do determine light direction. - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="DynamicBody" inherits="PhysicsBody" category="Nodes/3D"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_mass" > - <argument index="0" name="mass" type="real"> - </argument> - <description> - </description> - </method> - <method name="set_friction" > - <argument index="0" name="friction" type="real"> - </argument> - <description> - </description> - </method> - <method name="set_bounce" > - <argument index="0" name="bounce" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_mass" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="get_friction" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="get_bounce" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="set_linear_velocity" > - <argument index="0" name="linear_velocity" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="get_linear_velocity" qualifiers="const" > - <return type="Vector3"> - </return> - <description> - </description> - </method> - <method name="set_angular_velocity" > - <argument index="0" name="angular_velocity" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="get_angular_velocity" qualifiers="const" > - <return type="Vector3"> - </return> - <description> - </description> - </method> - <method name="set_sleeping" > - <argument index="0" name="sleeping" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_sleeping" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_applied_force" > - <argument index="0" name="applied_force" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="get_applied_force" qualifiers="const" > - <return type="Vector3"> - </return> - <description> - </description> - </method> - <method name="set_applied_torque" > - <argument index="0" name="applied_torque" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="get_applied_torque" qualifiers="const" > - <return type="Vector3"> - </return> - <description> - </description> - </method> - <method name="apply_local_impulse" > - <argument index="0" name="pos" type="Vector3"> - </argument> - <argument index="1" name="impulse" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="set_axis_velocity" > - <argument index="0" name="axis_velocity" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="set_direct_state_control" > - <argument index="0" name="enabled" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_direct_state_control_enabled" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_omit_force_integration" > - <argument index="0" name="enabled" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_omitting_force_integration" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="DynamicCharacterBody" inherits="DynamicBody" category="Nodes/3D"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="DynamicCustomBody" inherits="DynamicBody" category="Nodes/3D"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_mode" > - <argument index="0" name="mode" type="int"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="DynamicRigidBody" inherits="DynamicBody" category="Nodes/3D"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="FileDialog" inherits="Popup" category="Nodes/GUI Nodes"> - <brief_description> - Dialog for selecting files or directories in the filesystem. - </brief_description> - <description> - FileDialog is a preset dialog used to choose files and directories in the filesystem. It supports filter masks. - </description> - <methods> - <method name="clear_filters" > - <description> - Clear all the added filters in the dialog. - </description> - </method> - <method name="add_filter" > - <argument index="0" name="filter" type="String"> - </argument> - <description> - Add a custom filter. Filter format is: "mask ; description. - </description> - </method> - <method name="get_current_dir" qualifiers="const" > - <return type="String"> - </return> - <description> - Get the current working directory of the file dialog. - </description> - </method> - <method name="get_current_file" qualifiers="const" > - <return type="String"> - </return> - <description> - Get the current selected file of the file dialog (empty if none). - </description> - </method> - <method name="get_current_path" qualifiers="const" > - <return type="String"> - </return> - <description> - Get the current selected path (directory and file) of the file dialog (empty if none). - </description> - </method> - <method name="set_current_dir" > - <argument index="0" name="dir" type="String"> - </argument> - <description> - </description> - </method> - <method name="set_current_file" > - <argument index="0" name="file" type="String"> - </argument> - <description> - </description> - </method> - <method name="set_current_path" > - <argument index="0" name="path" type="String"> - </argument> - <description> - </description> - </method> - <method name="set_mode" > - <argument index="0" name="mode" type="int"> - </argument> - <description> - Set the file dialog mode from the MODE_* enum. - </description> - </method> - <method name="get_mode" qualifiers="const" > - <return type="int"> - </return> - <description> - Get the file dialog mode from the MODE_* enum. - </description> - </method> - </methods> - <signals> - <signal name="dir_selected"> - <argument index="0" name="dir" type="String"> - </argument> - <description> - </description> - </signal> - <signal name="file_selected"> - <argument index="0" name="path" type="String"> - </argument> - <description> - Event emitted when the user selects a file (double clicks it or presses the OK button). - </description> - </signal> - </signals> - <constants> - <constant name="MODE_OPEN_DIR" value="1"> - </constant> - <constant name="MODE_OPEN_FILE" value="0"> - Editor will not allow to select nonexistent files. - </constant> - <constant name="MODE_SAVE_FILE" value="2"> - Editor will warn when a file exists. - </constant> - </constants> -</class> -<class name="FixedMaterial" inherits="Material" category="Resources"> - <brief_description> - Simple Material with a fixed parameter set. - </brief_description> - <description> - FixedMaterial is a simple type of material [Resource], which contains a fixed amount of paramters. It is the only type of material supported in fixed-pipeline devices and APIs. It is also an often a better alternative to [ShaderMaterial] for most simple use cases. - </description> - <methods> - <method name="set_shader" > - <argument index="0" name="shader" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_shader" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="set_parameter" > - <argument index="0" name="param" type="int"> - </argument> - <argument index="1" name="value" type="var"> - </argument> - <description> - Set a parameter, parameters are defined in the PARAM_* enum. The type of each parameter may change, so it's best to check the enum. - </description> - </method> - <method name="get_parameter" qualifiers="const" > - <argument index="0" name="param" type="int"> - </argument> - <description> - Return a parameter, parameters are defined in the PARAM_* enum. The type of each parameter may change, so it's best to check the enum. - </description> - </method> - <method name="set_texture" > - <argument index="0" name="param" type="int"> - </argument> - <argument index="1" name="texture" type="Object"> - </argument> - <description> - Set a texture. Textures change parameters per texel and are mapped to the model depending on the texcoord mode (see [method set_texcoord_mode]). - </description> - </method> - <method name="get_texture" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="param" type="int"> - </argument> - <description> - Return a texture. Textures change parameters per texel and are mapped to the model depending on the texcoord mode (see [method set_texcoord_mode]). - </description> - </method> - <method name="set_texgen_mode" > - <argument index="0" name="mode" type="int"> - </argument> - <description> - Set the texture coordinate generation mode. Materials have a unique, texgen mode which can generate texture coordinates on the fly. Texgen mode must be one of the values from the TEXGEN_* enum. TEXGEN can be selected as a texture coordinate mode (see [method set_texcoord_mode]). - </description> - </method> - <method name="get_texgen_mode" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the texture coordinate generation mode. Materials have a unique, texgen mode which can generate texture coordinates on the fly. Texgen mode must be one of the values from the TEXGEN_* enum. TEXGEN can be selected as a texture coordinate mode (see [method set_texcoord_mode]). - </description> - </method> - <method name="set_texcoord_mode" > - <argument index="0" name="param" type="int"> - </argument> - <argument index="1" name="mode" type="int"> - </argument> - <description> - Set the texture coordinate mode. Each texture param (from the PARAM_* enum) has one. It defines how the textures are mapped to the object. - </description> - </method> - <method name="get_texcoord_mode" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="param" type="int"> - </argument> - <description> - Return the texture coordinate mode. Each texture param (from the PARAM_* enum) has one. It defines how the textures are mapped to the object. - </description> - </method> - <method name="set_uv_transform" > - <argument index="0" name="transform" type="Transform"> - </argument> - <description> - Sets a special transform used to post-transform UV coordinates of the uv_xfrom tecoord mode: TEXCOORD_UV_TRANSFORM - </description> - </method> - <method name="get_uv_transform" qualifiers="const" > - <return type="Transform"> - </return> - <description> - Returns the special transform used to post-transform UV coordinates of the uv_xfrom tecoord mode: TEXCOORD_UV_TRANSFORM - </description> - </method> - </methods> - <constants> - <constant name="PARAM_SPECULAR_EXP" value="4"> - Specular Exponent (size of the specular dot) - </constant> - <constant name="PARAM_DETAIL" value="1"> - Detail Layer for diffuse lighting. - </constant> - <constant name="TEXCOORD_UV2" value="2"> - Read texture coordinates from the UV2 array. - </constant> - <constant name="TEXGEN_SCREENZ" value="3"> - Use the screen coordinates as UV, scaled by depth and the screenz coefficient. - </constant> - <constant name="TEXCOORD_UV_TRANSFORM" value="1"> - Read texture coordinates from the UV array and transform them by uv_xform. - </constant> - <constant name="TEXGEN_LOCAL_XY" value="0"> - Use object local X and Y coordinates as UV. - </constant> - <constant name="PARAM_SHADE_PARAM" value="8"> - </constant> - <constant name="PARAM_MAX" value="9"> - Maximum amount of parameters - </constant> - <constant name="PARAM_DIFFUSE" value="0"> - Diffuse Lighting (light scattered from surface). - </constant> - <constant name="PARAM_EMISSION" value="3"> - Emission Lighting (light emitted from the surface) - </constant> - <constant name="PARAM_SPECULAR" value="2"> - Specular Lighting (light reflected from the surface). - </constant> - <constant name="PARAM_DETAIL_MIX" value="6"> - Mix coefficient for the detail layer. - </constant> - <constant name="TEXGEN_SPHERE" value="1"> - Use view normal reflected by object normal as UV. - </constant> - <constant name="PARAM_NORMAL" value="7"> - Normal Map (irregularity map). - </constant> - <constant name="PARAM_GLOW" value="5"> - Glow (Visible emitted scattered light). - </constant> - <constant name="TEXCOORD_UV" value="0"> - Read texture coordinates from the UV array. - </constant> - <constant name="TEXCOORD_TEXGEN" value="3"> - Use texture coordinates from the texgen. - </constant> - <constant name="TEXGEN_SCREEN" value="2"> - Use the screen coordinates as UV. - </constant> - </constants> -</class> -<class name="FogFX" inherits="ScenarioFX" category="Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="FollowCamera" inherits="Camera" category="Nodes/3D"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_orbit" > - <argument index="0" name="orbit" type="Vector2"> - </argument> - <description> - </description> - </method> - <method name="get_orbit" qualifiers="const" > - <return type="Vector2"> - </return> - <description> - </description> - </method> - <method name="set_orbit_x" > - <argument index="0" name="x" type="real"> - </argument> - <description> - </description> - </method> - <method name="set_orbit_y" > - <argument index="0" name="y" type="real"> - </argument> - <description> - </description> - </method> - <method name="set_min_orbit_x" > - <argument index="0" name="x" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_min_orbit_x" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="set_max_orbit_x" > - <argument index="0" name="x" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_max_orbit_x" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="set_height" > - <argument index="0" name="height" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_height" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="set_inclination" > - <argument index="0" name="inclination" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_inclination" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="rotate_orbit" > - <argument index="0" name="arg0" type="Vector2"> - </argument> - <description> - </description> - </method> - <method name="set_distance" > - <argument index="0" name="distance" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_distance" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="set_max_distance" > - <argument index="0" name="max_distance" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_max_distance" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="set_min_distance" > - <argument index="0" name="min_distance" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_min_distance" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="set_clip" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="has_clip" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_autoturn" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="has_autoturn" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_autoturn_tolerance" > - <argument index="0" name="degrees" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_autoturn_tolerance" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="set_autoturn_speed" > - <argument index="0" name="speed" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_autoturn_speed" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="set_smoothing" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="has_smoothing" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_rotation_smoothing" > - <argument index="0" name="amount" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_rotation_smoothing" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="set_translation_smoothing" > - <argument index="0" name="amount" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_translation_smoothing" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="set_use_lookat_target" > - <argument index="0" name="use" type="bool"> - </argument> - <argument index="1" name="lookat" type="Vector3" default="Vector3(0, 0, 0)"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="Font" inherits="Resource" category="Resources"> - <brief_description> - Internationalized font and text drawing support. - </brief_description> - <description> - Font contains an unicode compatible character set, as well as the ability to draw it with variable width, ascent, descent and kerning. For creating fonts from TTF files (or other font formats), see the editor support for fonts. TODO check wikipedia for graph of ascent/baseline/descent/height/etc. - </description> - <methods> - <method name="set_height" > - <argument index="0" name="px" type="real"> - </argument> - <description> - Set the total font height (ascent plus descent) in pixels. - </description> - </method> - <method name="get_height" qualifiers="const" > - <return type="real"> - </return> - <description> - Return the total font height (ascent plus descent) in pixels. - </description> - </method> - <method name="set_ascent" > - <argument index="0" name="px" type="real"> - </argument> - <description> - Set the font ascent (number of pixels above the baseline). - </description> - </method> - <method name="get_ascent" qualifiers="const" > - <return type="real"> - </return> - <description> - Return the font ascent (number of pixels above the baseline). - </description> - </method> - <method name="get_descent" qualifiers="const" > - <return type="real"> - </return> - <description> - Return the font descent (number of pixels below the baseline). - </description> - </method> - <method name="add_kerning_pair" > - <argument index="0" name="char_a" type="int"> - </argument> - <argument index="1" name="char_b" type="int"> - </argument> - <argument index="2" name="kerning" type="int"> - </argument> - <description> - Add a kerning pair to the [Font] as a difference. Kerning pairs are special cases where a typeface advance is determined by the next character. - </description> - </method> - <method name="get_kerning_pair" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="int"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - Return a kerning pair as a difference. Kerning pairs are special cases where a typeface advance is determined by the next character. - </description> - </method> - <method name="add_texture" > - <argument index="0" name="texture" type="Object"> - </argument> - <description> - Add a texture to the [Font]. - </description> - </method> - <method name="add_char" > - <argument index="0" name="character" type="int"> - </argument> - <argument index="1" name="texture" type="int"> - </argument> - <argument index="2" name="rect" type="Rect2"> - </argument> - <argument index="3" name="align" type="Vector2" default="Vector2(0,0)"> - </argument> - <argument index="4" name="advance" type="real" default="-1"> - </argument> - <description> - Add a character to the font, where "character" is the unicode value, "texture" is the texture index, "rect" is the region in the texture (in pixels!), "align" is the (optional) alignment for the character and "advance" is the (optional) advance. - </description> - </method> - <method name="get_char_size" qualifiers="const" > - <return type="Vector2"> - </return> - <argument index="0" name="char" type="int"> - </argument> - <argument index="1" name="next" type="int" default="0"> - </argument> - <description> - Return the size of a character, optionally taking kerning into account if the next character is provided. - </description> - </method> - <method name="get_string_size" qualifiers="const" > - <return type="Vector2"> - </return> - <argument index="0" name="string" type="String"> - </argument> - <description> - Return the size of a string, taking kerning and advance into account. - </description> - </method> - <method name="clear" > - <description> - Clear all the font data. - </description> - </method> - <method name="draw" qualifiers="const" > - <argument index="0" name="canvas_item" type="RID"> - </argument> - <argument index="1" name="pos" type="Vector2"> - </argument> - <argument index="2" name="string" type="String"> - </argument> - <argument index="3" name="modulate" type="Color" default="Color(1,1,1,1)"> - </argument> - <argument index="4" name="clip_w" type="int" default="-1"> - </argument> - <description> - Draw "string" into a canvas item using the font at a given "pos" position, with "modulate" color, and optionally clipping the width. "pos" specifies te baseline, not the top. To draw from the top, [html i]ascent[html /i] must be added to the Y axis. - </description> - </method> - <method name="draw_char" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="canvas_item" type="RID"> - </argument> - <argument index="1" name="pos" type="Vector2"> - </argument> - <argument index="2" name="char" type="int"> - </argument> - <argument index="3" name="next" type="int" default="-1"> - </argument> - <argument index="4" name="modulate" type="Color" default="Color(1,1,1,1)"> - </argument> - <description> - Draw character "char" into a canvas item using the font at a given "pos" position, with "modulate" color, and optionally kerning if "next" is apassed. clipping the width. "pos" specifies te baseline, not the top. To draw from the top, [html i]ascent[html /i] must be added to the Y axis. The width used by the character is returned, making this function useful for drawing strings character by character. - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="GammaFX" inherits="ScenarioFX" category="Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="_Geometry" inherits="Object" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="build_box_planes" > - <return type="Array"> - </return> - <argument index="0" name="extents" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="build_cylinder_planes" > - <return type="Array"> - </return> - <argument index="0" name="radius" type="real"> - </argument> - <argument index="1" name="height" type="real"> - </argument> - <argument index="2" name="sides" type="int"> - </argument> - <argument index="3" name="axis" type="int" default="2"> - </argument> - <description> - </description> - </method> - <method name="build_capsule_planes" > - <return type="Array"> - </return> - <argument index="0" name="radius" type="real"> - </argument> - <argument index="1" name="height" type="real"> - </argument> - <argument index="2" name="sides" type="int"> - </argument> - <argument index="3" name="lats" type="int"> - </argument> - <argument index="4" name="axis" type="int" default="2"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="Globals" inherits="Object" category="Core"> - <brief_description> - Contains global variables accessible from everywhere. - </brief_description> - <description> - Contains global variables accessible from everywhere. Use the normal [Object] API, such as "Globals.get(variable)", "Globals.set(variable,value)" or "Globals.has(variable)" to access them. Variables stored in engine.cfg are also loaded into globals, making this object very useful for reading custom game configuration options. - </description> - <methods> - <method name="has" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <description> - </description> - </method> - <method name="set_order" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="pos" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_order" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <description> - </description> - </method> - <method name="set_persisting" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_persisting" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <description> - </description> - </method> - <method name="clear" > - <argument index="0" name="name" type="String"> - </argument> - <description> - </description> - </method> - <method name="localize_path" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="path" type="String"> - </argument> - <description> - </description> - </method> - <method name="globalize_path" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="path" type="String"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="GlowFX" inherits="ScenarioFX" category="Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="HDRFX" inherits="ScenarioFX" category="Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="HScrollBar" inherits="ScrollBar" category="Nodes/GUI Nodes"> - <brief_description> - Horizontal version of [ScrollBar], which goes from top (min) to bottom (max). - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="HSeparator" inherits="Separator" category="Nodes/GUI Nodes"> - <brief_description> - Horizontal version of [Separator]. - </brief_description> - <description> - Horizontal version of [Separator]. It is used to separate objects vertiacally, though (but it looks horizontal!). - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="HSlider" inherits="Slider" category="Nodes/GUI Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="IP" inherits="Object" category="Networking"> - <brief_description> - IP Protocol support functions. - </brief_description> - <description> - IP contains some support functions for the IPv4 protocol. TCP/IP support is in different classes (see [TCP_Client], [TCP_Server]). IP provides hostname resolution support, both blocking and threaded. - </description> - <methods> - <method name="resolve_hostname" > - <return type="String"> - </return> - <argument index="0" name="host" type="String"> - </argument> - <description> - Resolve a given hostname, blocking. Resolved hostname is returned as an IP. - </description> - </method> - <method name="resolve_hostname_queue_item" > - <return type="int"> - </return> - <argument index="0" name="host" type="String"> - </argument> - <description> - Create a queue item for resolving a given hostname. The queue ID is returned, or RESOLVER_INVALID_ID on error. - </description> - </method> - <method name="get_resolve_item_status" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - Return the status of hostname queued for resolving, given it's queue ID. Returned status can be any of the RESOLVER_STATUS_* enumeration. - </description> - </method> - <method name="get_resolve_item_address" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - Return a resolved item address, or an empty string if an error happened or resolution didn't happen yet (see [method get_resolve_item_status]). - </description> - </method> - <method name="erase_resolve_item" > - <argument index="0" name="id" type="int"> - </argument> - <description> - Erase a queue ID, removing it from the queue if needed. This should be used after a queue is completed to free it and enable more queries to happen. - </description> - </method> - </methods> - <constants> - <constant name="RESOLVER_INVALID_ID" value="-1"> - </constant> - <constant name="RESOLVER_MAX_QUERIES" value="32"> - </constant> - <constant name="RESOLVER_STATUS_NONE" value="0"> - </constant> - <constant name="RESOLVER_STATUS_ERROR" value="3"> - </constant> - <constant name="RESOLVER_STATUS_WAITING" value="1"> - </constant> - <constant name="RESOLVER_STATUS_DONE" value="2"> - </constant> - </constants> -</class> -<class name="IP_Unix" inherits="IP" category="Networking"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="InputMap" inherits="Object" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="Label" inherits="Range" category="Nodes/GUI Nodes"> - <brief_description> - Control that displays formatted text. - </brief_description> - <description> - Label is a control that displays formatted text, optionally autowrapping it to the [Control] area. It inherits from range to be able to scroll wrapped text vertically. - </description> - <methods> - <method name="set_align" > - <argument index="0" name="align" type="int"> - </argument> - <description> - Set the alignmend mode to any of the ALIGN_* enumeration values. - </description> - </method> - <method name="get_align" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the alignmend mode (any of the ALIGN_* enumeration values). - </description> - </method> - <method name="set_text" > - <argument index="0" name="text" type="String"> - </argument> - <description> - Set the label text. Text can contain newlines. - </description> - </method> - <method name="get_text" qualifiers="const" > - <return type="String"> - </return> - <description> - Return the label text. Text can contain newlines. - </description> - </method> - <method name="set_autowrap" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - Set [html i]autowrap[html /i] mode. When enabled, autowrap will fit text to the control width, breaking sentences when they exceed the available horizontal space. When disabled, the label minimum width becomes the width of the longest row, and the minimum height large enough to fit all rows. - </description> - </method> - <method name="has_autowrap" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return the state of the [html i]autowrap[html /i] mode (see [method set_autowrap]). - </description> - </method> - </methods> - <constants> - <constant name="ALIGN_CENTER" value="1"> - Align rows centered. - </constant> - <constant name="ALIGN_LEFT" value="0"> - Align rows to the left (default). - </constant> - <constant name="ALIGN_RIGHT" value="2"> - Align rows to the right (default). - </constant> - <constant name="ALIGN_FILL" value="3"> - Expand row whitespaces to fit the width. - </constant> - </constants> -</class> -<class name="Light" inherits="VisualInstance" category="Nodes/3D/3D Visual Nodes/3D Light Nodes"> - <brief_description> - Provides a base class for different kinds of light nodes. - </brief_description> - <description> - Light is the abstract base class for light nodes, so it shouldn't be used directly (It can't be instanced). Other types of light nodes inherit from it. Light contains the common variables and parameters used for lighting. - </description> - <methods> - <method name="set_parameter" > - <argument index="0" name="variable" type="int"> - </argument> - <argument index="1" name="value" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_parameter" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="arg0" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_color" > - <argument index="0" name="color" type="int"> - </argument> - <argument index="1" name="value" type="Color"> - </argument> - <description> - </description> - </method> - <method name="get_color" qualifiers="const" > - <return type="Color"> - </return> - <argument index="0" name="arg0" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_project_shadows" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="has_project_shadows" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_projector" > - <argument index="0" name="projector" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_projector" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="set_operator" > - <argument index="0" name="operator" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_operator" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - </methods> - <constants> - <constant name="COLOR_DIFFUSE" value="1"> - </constant> - <constant name="PARAM_SPOT_ANGLE" value="1"> - </constant> - <constant name="PARAM_ATTENUATION" value="4"> - </constant> - <constant name="COLOR_SPECULAR" value="2"> - </constant> - <constant name="COLOR_AMBIENT" value="0"> - </constant> - <constant name="PARAM_SHADOW_DARKENING" value="5"> - </constant> - <constant name="PARAM_RADIUS" value="2"> - </constant> - <constant name="PARAM_SPOT_ATTENUATION" value="4"> - </constant> - <constant name="PARAM_ENERGY" value="3"> - </constant> - </constants> -</class> -<class name="LineEdit" inherits="Control" category="Nodes/GUI Nodes"> - <brief_description> - Control that provides single line string editing. - </brief_description> - <description> - LineEdit provides a single line string editor, used for text fields. - </description> - <methods> - <method name="clear" > - <description> - Clear the [LineEdit] text. - </description> - </method> - <method name="select_all" > - <description> - Select the whole string. - </description> - </method> - <method name="set_text" > - <argument index="0" name="text" type="String"> - </argument> - <description> - Set the text in the [LineEdit], clearing the existing one and the selection. - </description> - </method> - <method name="get_text" qualifiers="const" > - <return type="String"> - </return> - <description> - Return the text in the [LineEdit]. - </description> - </method> - <method name="set_cursor_pos" > - <argument index="0" name="pos" type="int"> - </argument> - <description> - Set the cursor position inside the [LineEdit], causing it to scroll if needed. - </description> - </method> - <method name="get_cursor_pos" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the cursor position inside the [LineEdit]. - </description> - </method> - <method name="set_max_length" > - <argument index="0" name="chars" type="int"> - </argument> - <description> - Set the maximum amount of characters the [LineEdit] can edit, and cropping existing text in case it exceeds that limit. Setting 0 removes the limit. - </description> - </method> - <method name="get_max_length" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the maximum amount of characters the [LineEdit] can edit. If 0 is returned, no limit exists. - </description> - </method> - <method name="append_at_cursor" > - <argument index="0" name="text" type="String"> - </argument> - <description> - Append text at cursor, scrolling the [LineEdit] when needed. - </description> - </method> - <method name="set_editable" > - <argument index="0" name="enabled" type="bool"> - </argument> - <description> - Set the [html i]editable[html /i] status of the [LineEdit]. When disabled, existing text can't be modified and new text can't be added. - </description> - </method> - <method name="is_editable" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return the [html i]editable[html /i] status of the [LineEdit] (see [method set_editable]). - </description> - </method> - <method name="set_secret" > - <argument index="0" name="enabled" type="bool"> - </argument> - <description> - Set the [html i]secret[html /i] status of the [LineEdit]. When enabled, every character is displayed as "*". - </description> - </method> - <method name="is_secret" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return the [html i]secret[html /i] status of the [LineEdit] (see [method set_secret]). - </description> - </method> - <method name="select" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - </methods> - <signals> - <signal name="text_entered"> - <argument index="0" name="text" type="String"> - </argument> - <description> - This signal is emitted when the user presses KEY_ENTER on the [LineEdit]. This signal is often used as an alternate confirmation mechanism in dialogs. - </description> - </signal> - <signal name="text_changed"> - <argument index="0" name="text" type="String"> - </argument> - <description> - When the text changes, this signal is emitted. - </description> - </signal> - </signals> - <constants> - </constants> -</class> -<class name="MainLoop" inherits="Object" category="Main Loop"> - <brief_description> - Main loop is the abstract main loop base class. - </brief_description> - <description> - Main loop is the abstract main loop base class. All other main loop classes are derived from it. Upon application start, a [MainLoop] has to be provided to OS, else the application will exit. This happens automatically (and a [SceneMainLoop] is created), unless a main [Script] is supplied, which may or not create and return a [MainLoop]. - </description> - <methods> - </methods> - <constants> - <constant name="NOTIFICATION_WM_QUIT_REQUEST" value="7"> - </constant> - <constant name="NOTIFICATION_WM_FOCUS_IN" value="5"> - </constant> - <constant name="NOTIFICATION_WM_FOCUS_OUT" value="6"> - </constant> - </constants> -</class> -<class name="Material" inherits="Resource" category="Resources"> - <brief_description> - Abstract base [Resource] for coloring and shading geometry. - </brief_description> - <description> - Material is a base [Resource] used for coloring and shading geometry. All materials inherit from it and almost all [VisualInstance] derived nodes carry a Material. A few flags and parameters are shared between all material types and are configured here. - </description> - <methods> - <method name="set_flag" > - <argument index="0" name="flag" type="int"> - </argument> - <argument index="1" name="enable" type="bool"> - </argument> - <description> - Set a [Material] flag, which toggles on or off a behavior when rendering. See enumeration FLAG_* for a list. - </description> - </method> - <method name="get_flag" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="flag" type="int"> - </argument> - <description> - Return a [Material] flag, which toggles on or off a behavior when rendering. See enumeration FLAG_* for a list. - </description> - </method> - <method name="set_hint" > - <argument index="0" name="hint" type="int"> - </argument> - <argument index="1" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="get_hint" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="hint" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_blend_mode" > - <argument index="0" name="mode" type="int"> - </argument> - <description> - Set blend mode for the material, which can be one of BLEND_MODE_MIX (default), BLEND_MODE_ADD, BLEND_MODE_SUB. Keep in mind that only BLEND_MODE_MIX ensures that the material [html i]may[html /i] be opaque, any other blend mode will render with alpha blending enabled in raster-based [VisualServer] implementations. - </description> - </method> - <method name="get_blend_mode" qualifiers="const" > - <return type="int"> - </return> - <description> - Return blend mode for the material, which can be one of BLEND_MODE_MIX (default), BLEND_MODE_ADD, BLEND_MODE_SUB. Keep in mind that only BLEND_MODE_MIX ensures that the material [html i]may[html /i] be opaque, any other blend mode will render with alpha blending enabled in raster-based [VisualServer] implementations. - </description> - </method> - <method name="set_shade_model" > - <argument index="0" name="model" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_shade_model" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_line_width" > - <argument index="0" name="width" type="real"> - </argument> - <description> - Set the line width for geometry drawn with FLAG_WIREFRAME enabled, or LINE primitives. Note that not all hardware or VisualServer backends support this (like DirectX). - </description> - </method> - <method name="get_line_width" qualifiers="const" > - <return type="real"> - </return> - <description> - Return the line width for geometry drawn with FLAG_WIREFRAME enabled, or LINE primitives. Note that not all hardware or VisualServer backends support this (like DirectX). - </description> - </method> - <method name="set_shader_param" > - <argument index="0" name="param" type="String"> - </argument> - <argument index="1" name="arg1" type="var"> - </argument> - <description> - </description> - </method> - <method name="get_shader_param" qualifiers="const" > - <argument index="0" name="arg0" type="String"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - <constant name="SHADE_MODEL_FRESNEL" value="2"> - </constant> - <constant name="SHADE_MODEL_LAMBERT" value="0"> - </constant> - <constant name="HINT_DECAL" value="0"> - </constant> - <constant name="FLAG_WIREFRAME" value="5"> - Triangle geometry is drawn as lines if this flag is enabled. - </constant> - <constant name="SHADE_MODEL_TOON" value="3"> - </constant> - <constant name="SHADE_MODEL_LAMBERT_WRAP" value="1"> - </constant> - <constant name="HINT_NO_SHADOW" value="2"> - </constant> - <constant name="FLAG_DOUBLE_SIDED" value="1"> - Both front facing and back facing triangles are rendered when this flag is enabled. - </constant> - <constant name="FLAG_BILLBOARD_TOGGLE" value="6"> - Geometry world transform is computed as billboard if this flag is enabled, often used for impostors. - </constant> - <constant name="FLAG_UNSHADED" value="3"> - Shading (lighting) is disabled when this flag is enabled. - </constant> - <constant name="BLEND_MODE_MIX" value="0"> - Use the regular alpha blending equation (source and dest colors are faded) (default). - </constant> - <constant name="SHADE_MODEL_CUSTOM_0" value="4"> - </constant> - <constant name="SHADE_MODEL_CUSTOM_1" value="5"> - </constant> - <constant name="FLAG_MAX" value="7"> - Maximum amount of flags - </constant> - <constant name="FLAG_VISIBLE" value="0"> - Geometry is visible when this flag is enabled (default). - </constant> - <constant name="SHADE_MODEL_CUSTOM_2" value="6"> - </constant> - <constant name="HINT_MAX" value="4"> - </constant> - <constant name="HINT_NO_DEPTH_DRAW" value="3"> - </constant> - <constant name="BLEND_MODE_ADD" value="1"> - Use additive blending equation, often used for particle effects such as fire or light decals. - </constant> - <constant name="SHADE_MODEL_CUSTOM_3" value="7"> - </constant> - <constant name="HINT_OPAQUE_PRE_PASS" value="1"> - </constant> - <constant name="FLAG_ONTOP" value="4"> - </constant> - <constant name="BLEND_MODE_SUB" value="2"> - Use substractive blending equation, often used for some smoke effects or types of glass. - </constant> - <constant name="FLAG_INVERT_FACES" value="2"> - Front facing and back facing order is swapped when this flag is enabled. - </constant> - </constants> -</class> -<class name="MenuButton" inherits="Button" category="Nodes/GUI Nodes"> - <brief_description> - Special button that brings up a [PopupMenu] when clicked. - </brief_description> - <description> - Special button that brings up a [PopupMenu] when clicked. That's pretty much all it does, as it's just a helper class when bulding GUIs. - </description> - <methods> - <method name="get_popup" > - <return type="Object"> - </return> - <description> - Return the [PopupMenu] contained in this button. - </description> - </method> - </methods> - <signals> - <signal name="about_to_show"> - <description> - </description> - </signal> - </signals> - <constants> - </constants> -</class> -<class name="Mesh" inherits="Resource" category="Resources"> - <brief_description> - A [Resource] that contains vertex-array based geometry. - </brief_description> - <description> - Mesh is a type of [Resource] that contains vertex-array based geometry, divided in [html i]surfaces[html /i]. Each surface contains a completely separate array and a material used to draw it. Design wise, a mesh with multiple surfaces is prefered to a single surface, because objects created in 3D editing software commonly contain multiple materials. - </description> - <methods> - <method name="add_morph_target" > - <argument index="0" name="name" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_morph_target_count" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="get_morph_target" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="index" type="int"> - </argument> - <description> - </description> - </method> - <method name="clear_morph_targets" > - <description> - </description> - </method> - <method name="add_surface" > - <argument index="0" name="primitive" type="int"> - </argument> - <argument index="1" name="format" type="int"> - </argument> - <argument index="2" name="array_len" type="int"> - </argument> - <argument index="3" name="index_array_len" type="int"> - </argument> - <description> - Create a new surface ([method get_surface_count] will become surf_idx for this.[html br/] 			Surfaces are created to be rendered using a "primitive", which may be PRIMITIVE_POINTS, PRIMITIVE_LINES, PRIMITIVE_LINE_STRIP, PRIMITIVE_LINE_LOOP, PRIMITIVE_TRIANGLES, PRIMITIVE_TRIANGLE_STRIP, PRIMITIVE_TRIANGLE_FAN. (As a note, when using indices, it is recommended to only use just points, lines or triangles).[html br/] 			The format of a surface determines which arrays it will allocate and hold, so "format" is a combination of ARRAY_FORMAT_* mask constants ORed together. ARRAY_FORMAT_VERTEX must be always present. "array_len" determines the amount of vertices in the array (not primitives!). if ARRAY_FORMAT_INDEX is in the format mask, then it means that an index array will be allocated and "index_array_len" must be passed. - </description> - </method> - <method name="get_surface_count" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the amount of surfaces that the [Mesh] holds. - </description> - </method> - <method name="surface_remove" > - <argument index="0" name="surf_idx" type="int"> - </argument> - <description> - Remove a surface at position surf_idx, shifting greater surfaces one surf_idx slot down. - </description> - </method> - <method name="surface_set_array" > - <return type="int"> - </return> - <argument index="0" name="surf_idx" type="int"> - </argument> - <argument index="1" name="array" type="int"> - </argument> - <argument index="2" name="data" type="var"> - </argument> - <description> - Set a surface array, array must be defined in the format (see [method add_surface]), and which array being set in "data" must be indicated passing a value from the ARRAY_* enum (NOT THE ARRAY_FORMAT_ enum!!). A Mesh can't be displayed (error will be reported) if an array that is present in the format was not set. - </description> - </method> - <method name="surface_get_array" qualifiers="const" > - <argument index="0" name="surf_idx" type="int"> - </argument> - <argument index="1" name="array" type="int"> - </argument> - <description> - Return a surface array, array must be defined in the format (see [method add_surface]), and which array being returned must be indicated passing a value from the ARRAY_* enum (NOT THE ARRAY_FORMAT_ enum!!) (see [method add_surface]). - </description> - </method> - <method name="surface_get_array_len" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="surf_idx" type="int"> - </argument> - <description> - Return the length in vertices of the vertex array in the requested surface (see [method add_surface]). - </description> - </method> - <method name="surface_get_array_index_len" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="surf_idx" type="int"> - </argument> - <description> - Return the length in indices of the index array in the requested surface (see [method add_surface]). - </description> - </method> - <method name="surface_get_format" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="surf_idx" type="int"> - </argument> - <description> - Return the format mask of the requested surface (see [method add_surface]). - </description> - </method> - <method name="surface_get_primitive_type" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="surf_idx" type="int"> - </argument> - <description> - Return the primitive type of the requested surface (see [method add_surface]). - </description> - </method> - <method name="surface_set_material" > - <argument index="0" name="surf_idx" type="int"> - </argument> - <argument index="1" name="arg1" type="Object"> - </argument> - <description> - Set a [Material] for a given surface. Surface will be rendered using this material. - </description> - </method> - <method name="surface_get_material" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="surf_idx" type="int"> - </argument> - <description> - Return a [Material] in a given surface. Surface is rendered using this material. - </description> - </method> - </methods> - <constants> - <constant name="PRIMITIVE_LINES" value="1"> - Render array as lines (every two vertices a line is created). - </constant> - <constant name="ARRAY_FORMAT_TEX_UV2" value="32"> - </constant> - <constant name="ARRAY_TEX_UV2" value="5"> - </constant> - <constant name="ARRAY_WEIGHTS_SIZE" value="4"> - Amount of weights/bone indices per vertex (always 4). - </constant> - <constant name="ARRAY_FORMAT_VERTEX" value="1"> - Array format will include vertices (mandatory). - </constant> - <constant name="ARRAY_VERTEX" value="0"> - Vertex array (array of [Vector3]() vertices). - </constant> - <constant name="PRIMITIVE_POINTS" value="0"> - Render array as points (one vertex equals one point). - </constant> - <constant name="ARRAY_FORMAT_BONES" value="64"> - Array format will include bone indices. - </constant> - <constant name="ARRAY_FORMAT_COLOR" value="8"> - Array format will include a color array. - </constant> - <constant name="ARRAY_BONES" value="6"> - Array of bone indices, as a float array. Each element in groups of 4 floats. - </constant> - <constant name="ARRAY_COLOR" value="3"> - Vertex array (array of [Color]() colors). - </constant> - <constant name="ARRAY_FORMAT_INDEX" value="256"> - Index array will be used. - </constant> - <constant name="ARRAY_INDEX" value="8"> - Array of integers, used as indices referencing vertices. No index can be beyond the vertex array size. - </constant> - <constant name="PRIMITIVE_TRIANGLE_STRIP" value="5"> - Render array as triangle strips. - </constant> - <constant name="ARRAY_FORMAT_TANGENT" value="4"> - Array format will include tangents - </constant> - <constant name="ARRAY_FORMAT_NORMAL" value="2"> - Array format will include normals - </constant> - <constant name="ARRAY_TANGENT" value="2"> - Tangent array, array of groups of 4 floats. first 3 floats determine the tangent, and the last the binormal direction as -1 or 1. - </constant> - <constant name="ARRAY_NORMAL" value="1"> - Normal array (array of [Vector3]() normals). - </constant> - <constant name="PRIMITIVE_TRIANGLES" value="4"> - Render array as triangles (every three vertices a triangle is created). - </constant> - <constant name="PRIMITIVE_LINE_LOOP" value="3"> - Render array as line loop (like line strip, but closed). - </constant> - <constant name="PRIMITIVE_LINE_STRIP" value="2"> - Render array as line strip. - </constant> - <constant name="ARRAY_FORMAT_WEIGHTS" value="128"> - Array format will include bone weights. - </constant> - <constant name="ARRAY_FORMAT_TEX_UV" value="16"> - Array format will include UVs. - </constant> - <constant name="ARRAY_WEIGHTS" value="7"> - Array of bone weights, as a float array. Each element in groups of 4 floats. - </constant> - <constant name="ARRAY_TEX_UV" value="4"> - UV array (array of [Vector3]() UVs or float array of groups of 2 floats (u,v)). - </constant> - <constant name="PRIMITIVE_TRIANGLE_FAN" value="6"> - Render array as triangle fans. - </constant> - <constant name="NO_INDEX_ARRAY" value="-1"> - Default value used for index_array_len when no indices are present. - </constant> - </constants> -</class> -<class name="MeshInstance" inherits="VisualInstance" category="Nodes/3D/3D Visual Nodes"> - <brief_description> - Node that instances meshes into a [Scenario]. - </brief_description> - <description> - MeshInstance is a [Node] that takes a [Mesh] resource and adds it to the current [Scenario] by creating an instance of it. This is the class most often used to get 3D geometry rendered and can be used to instance a sigle [Mesh] in many places. This allows to reuse geometry and save on resources. When a [Mesh] has to be instanced more than thousands of times at close proximity, consider using a [MultiMesh] in a [MultiMeshInstance] instead. - </description> - <methods> - <method name="set_mesh" > - <argument index="0" name="mesh" type="Object"> - </argument> - <description> - Set the [Mesh] resource for the instance. - </description> - </method> - <method name="get_mesh" qualifiers="const" > - <return type="Object"> - </return> - <description> - Return the current [Mesh] resource for the instance. - </description> - </method> - <method name="get_aabb" qualifiers="const" > - <return type="AABB"> - </return> - <description> - Return the AABB of the mesh, in local coordinates. - </description> - </method> - <method name="create_trimesh_collision" > - <description> - This helper creates a [StaticBody] child [Node] using the mesh geometry as collision. It's mainly used for testing. - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="Misc" inherits="Node" category="Core"> - <brief_description> - Soon to be removed, bye bye. - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="MultiMesh" inherits="Resource" category="Resources"> - <brief_description> - Provides high perfomance mesh instancing. - </brief_description> - <description> - MultiMesh provides low level mesh instancing. If the amount of [Mesh] instances needed goes from hundreds to thousands (and most need to be visible at close proximity) creating such a large amount of [MeshInstance] nodes may affect performance by using too much CPU or video memory. [html br/]For this case a MultiMesh becomes very useful, as it can draw thousands of instances with little API overhead.[html br/] As a drawback, if the instances are too far away of each other, performance may be reduced as every sigle instance will always rendered (they are spatially indexed as one, for the whole object).[html br/] Since instances may have any behavior, the AABB used for visibility must be provided by the user, or generated with [method generate_aabb]. - </description> - <methods> - <method name="set_mesh" > - <argument index="0" name="arg0" type="Object"> - </argument> - <description> - Set the [Mesh] resource to be drawn in multiple instances. - </description> - </method> - <method name="get_mesh" qualifiers="const" > - <return type="Object"> - </return> - <description> - Return the [Mesh] resource drawn as multiple instances. - </description> - </method> - <method name="set_instance_count" > - <argument index="0" name="arg0" type="int"> - </argument> - <description> - Set the amount of instnces that is going to be drawn. Changing this number will erase all the existing instance transform and color data. - </description> - </method> - <method name="get_instance_count" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the amount of instnces that is going to be drawn. - </description> - </method> - <method name="set_instance_transform" > - <argument index="0" name="arg0" type="int"> - </argument> - <argument index="1" name="arg1" type="Transform"> - </argument> - <description> - Set the transform for a specific instance. - </description> - </method> - <method name="get_instance_transform" qualifiers="const" > - <return type="Transform"> - </return> - <argument index="0" name="arg0" type="int"> - </argument> - <description> - Return the transform of a specific instance. - </description> - </method> - <method name="set_instance_color" > - <argument index="0" name="arg0" type="int"> - </argument> - <argument index="1" name="arg1" type="Color"> - </argument> - <description> - Set the color of a specific instance. - </description> - </method> - <method name="get_instance_color" qualifiers="const" > - <return type="Color"> - </return> - <argument index="0" name="arg0" type="int"> - </argument> - <description> - Get the color of a specific instance. - </description> - </method> - <method name="set_aabb" > - <argument index="0" name="arg0" type="AABB"> - </argument> - <description> - Set the visibility AABB. If not provided, MultiMesh will not be visible. - </description> - </method> - <method name="get_aabb" qualifiers="const" > - <return type="AABB"> - </return> - <description> - Return the visibility AABB. - </description> - </method> - <method name="generate_aabb" > - <description> - Generate a new visibility AABB, using mesh AABB and instance transforms. Since instance information is stored in the [VisualServer], this function is VERY SLOW and must NOT be used often. - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="MultiMeshInstance" inherits="VisualInstance" category="Nodes/3D/3D Visual Nodes"> - <brief_description> - Node that instances a [MultiMesh]. - </brief_description> - <description> - MultiMeshInstance is a [Node] that takes a [MultiMesh] resource and adds it to the current [Scenario] by creating an instance of it (yes, this is an instance of instances). - </description> - <methods> - <method name="set_multimesh" > - <argument index="0" name="multimesh" type="Object"> - </argument> - <description> - Set the [MultiMesh] to be instance. - </description> - </method> - <method name="get_multimesh" qualifiers="const" > - <return type="Object"> - </return> - <description> - Return the [MultiMesh] that is used for instancing. - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="Node" inherits="Object" category="Nodes"> - <brief_description> - Base class for all the "Scene" elements. - </brief_description> - <description> - Nodes can be set as children of other nodes, resulting in a tree arrangement. Any tree of nodes is called a "Scene".[html br/] Scenes can be saved to disk, and then instanced into other scenes. This allows for very high flexibility in the architecture and data model of the projects. Scenes become "active" and part of the "Scene Tree" once they are added as children of a [RootNode].[html br/][html br/] 	As an illustrative example, a Scene (tree of nodes): 	[html div align="center"][html img src="images/scene.png"/][html /div] 	This scene will was edited separatedly, then is added as part of a game (by instancing it), becoming part of a "Scene Tree": 	[html div align="center"][html img src="images/scene_tree.png"/][html /div] 	In short, nodes are an effective all-in-one way to create and organize assets, gameplay and game data. 	When a Node is freed (deleted), it will delete all its children 	nodes. 	TODO: explain better process/signal/group call ordering - </description> - <methods> - <method name="set_name" > - <argument index="0" name="name" type="String"> - </argument> - <description> - Set the name of the [Node]. Name must be unique within parent, and setting an already existing name will cause for the node to be automatically renamed. - </description> - </method> - <method name="get_name" qualifiers="const" > - <return type="String"> - </return> - <description> - Return the name of the [Node]. Name is be unique within parent. - </description> - </method> - <method name="add_child" > - <argument index="0" name="node" type="Node"> - </argument> - <description> - Add a child [Node]. Nodes can have as many children as they want, but every child must have a unique name. Children nodes are automatically deleted when the parent node is deleted, so deleting a whole scene is performed by deleting its topmost node. - </description> - </method> - <method name="remove_child" > - <argument index="0" name="node" type="Node"> - </argument> - <description> - Remove a child [Node]. Node is NOT deleted and will have to be deleted manually. - </description> - </method> - <method name="get_child_count" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the amount of children nodes. - </description> - </method> - <method name="get_child" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <description> - Return a children node by it's index (see [method get_child_count]). This method is often used for iterating all children of a node. - </description> - </method> - <method name="has_node" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="path" type="NodePath"> - </argument> - <description> - </description> - </method> - <method name="get_node" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="path" type="NodePath"> - </argument> - <description> - Fetch a node. "path" must be valid (or else error will occur) and can be either the name of a child node, a relative path (from the current node to another node), or an absolute path to a node.[html br/] Examples ofa paths are: get_node("Sword") , get_node("../Swamp/Alligator") , get_node("/MyGame"). [html br/]Note: fetching absolute paths only works when the node is inside the scene tree (see [method is_inside_tree]). - </description> - </method> - <method name="get_parent" qualifiers="const" > - <return type="Object"> - </return> - <description> - Return the parent [Node] of the current [Node], or an empty Object if the node lacks a parent. - </description> - </method> - <method name="is_inside_scene" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="is_a_parent_of" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="node" type="Node"> - </argument> - <description> - Return [html i]true[html /i] if the "node" argument is a direct or indirect child of the current node, otherwise return [html i]false[html /i]. - </description> - </method> - <method name="is_greater_than" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="node" type="Node"> - </argument> - <description> - Return [html i]true[html /i] if "node" occurs later in the scene hierarchy than the current node, otherwise return [html i]false[html /i]. - </description> - </method> - <method name="get_path" qualifiers="const" > - <return type="NodePath"> - </return> - <description> - Return the absolute path of the current node. This only works if the curent node is inside the scene tree (see [method is_inside_tree]). - </description> - </method> - <method name="get_path_to" qualifiers="const" > - <return type="NodePath"> - </return> - <argument index="0" name="node" type="Node"> - </argument> - <description> - Return the relative path from the current node to the specified node in "node" argument. Both nodes must be in the same scene, or else the function will fail. - </description> - </method> - <method name="add_to_group" > - <argument index="0" name="group" type="String"> - </argument> - <argument index="1" name="arg1" type="bool"> - </argument> - <description> - Add a node to a group. Groups are helpers to name and organize group of nodes, like for example: "Enemies" "Collectables", etc. A [Node] can be in any number of groups. Nodes can be assigned a group at any time, but will not be added to it until they are inside the scene tree (see [method is_inside_tree]). - </description> - </method> - <method name="remove_from_group" > - <argument index="0" name="group" type="String"> - </argument> - <description> - Remove a node from a group. - </description> - </method> - <method name="move_child" > - <argument index="0" name="child_node" type="Node"> - </argument> - <argument index="1" name="to_pos" type="int"> - </argument> - <description> - Move a child node to a different position (order) amongst the other children. Since calls, signals, etc are performed by tree order, changing the order of chilren nodes may be useful. - </description> - </method> - <method name="raise" > - <description> - Move this node to the top of the array of nodes of the parent node. This is often useful on GUIs ([Control]), because their order of drawing fully depends on their order in the tree. - </description> - </method> - <method name="set_owner" > - <argument index="0" name="arg0" type="Object"> - </argument> - <description> - Set the node owner. A node can have any other node as owner (as long as a valid parent, grandparent, etc ascending in the tree). When saving a node (using SceneSaver) all the nodes it owns will be saved with it. This allows to create complex SceneTrees, with instancing and subinstancing. - </description> - </method> - <method name="get_owner" qualifiers="const" > - <return type="Object"> - </return> - <description> - Get the node owner (see [method set_node_owner]). - </description> - </method> - <method name="remove_and_skip" > - <description> - Remove a node and set all its children as childrens of the parent node (if exists). All even subscriptions that pass by the removed node will be unsubscribed. - </description> - </method> - <method name="get_index" qualifiers="const" > - <return type="int"> - </return> - <description> - Get the node index in the parent (assuming it has a parent). - </description> - </method> - <method name="print_tree" > - <description> - Print the screne to stdout. Used mainly for debugging purposes. - </description> - </method> - <method name="set_filename" > - <argument index="0" name="filename" type="String"> - </argument> - <description> - A node can contain a filename. This filename should not be changed by the user, unless writing editors and tools. When a scene is instanced from a file, it topmost node contains the filename from where it was loaded. - </description> - </method> - <method name="get_filename" qualifiers="const" > - <return type="String"> - </return> - <description> - Return a filename that may be containedA node can contained by the node. When a scene is instanced from a file, it topmost node contains the filename from where it was loaded (see [method set_filename]). - </description> - </method> - <method name="propagate_notification" > - <argument index="0" name="what" type="int"> - </argument> - <description> - Notify the current node and all its chldren recursively by calling notification() in all of them. - </description> - </method> - <method name="set_process" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - Enables or disables node processing. When a node is being processed, it will receive a NOTIFICATION_PROCESS on every frame. It is common to check how much time was elapsed since the previous frame by calling [method get_process_time]. If the application is set to run at 60 fps, NOTIFICATION_PROCESS will be received 60 times per second (even if the visuals are running at faster or lower fps). Because of this, nodes that wish to do processing are recommended to use [method set_idle_process] instead, unless strong syncronization is requiered (for example, to modify the behavior of physics objects). - </description> - </method> - <method name="get_process_time" qualifiers="const" > - <return type="real"> - </return> - <description> - Return the amount of time elapsed (in seconds) between two succesive NOTIFICATION_PROCESS notifications. - </description> - </method> - <method name="is_processing" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return wether processing is enabled in the current node. - </description> - </method> - <method name="set_idle_process" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - Enables or disables node idle processing. When a node is being idle-processed, it will receive a NOTIFICATION_IDLE_PROCESS when idle. It is common to check how much time was elapsed since the previous idle time by calling [method get_idle_process_time]. Idle processing is commonly syncronized to [VisualServer] being done rendering a frame, so this type of processing is syncronized to the visible frames per second. To syncronize with the desired frames per second, see [method set_process] instead. - </description> - </method> - <method name="get_idle_process_time" qualifiers="const" > - <return type="real"> - </return> - <description> - Return the amount of time elapsed (in seconds) between two succesive NOTIFICATION_IDLE_PROCESS notifications. - </description> - </method> - <method name="is_idle_processing" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return wether idle processing is enabled in the current node. - </description> - </method> - <method name="set_process_input" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_processing_input" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_process_unhandled_input" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_processing_unhandled_input" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_process_mode" > - <argument index="0" name="mode" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_process_mode" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_world" > - <argument index="0" name="world" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_world" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="get_current_world" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="get_scene" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="duplicate" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="arg0" type="Object"> - </argument> - <argument index="1" name="arg1" type="bool" default="NULL"> - </argument> - <description> - Return a duplicate of the scene, with all nodes and parameters copied. Subscriptions will not be duplicated. - </description> - </method> - <method name="replace_by" > - <argument index="0" name="node" type="Node"> - </argument> - <argument index="1" name="keep_data" type="bool" default="false"> - </argument> - <description> - Replace a node in a scene by a given one. Subscriptions that pass through this node will be lost. - </description> - </method> - </methods> - <signals> - <signal name="enter_scene"> - <description> - </description> - </signal> - <signal name="renamed"> - <description> - </description> - </signal> - <signal name="exit_scene"> - <description> - </description> - </signal> - </signals> - <constants> - <constant name="NOTIFICATION_ENTER_WORLD" value="20"> - </constant> - <constant name="PROCESS_PAUSE" value="1"> - </constant> - <constant name="NOTIFICATION_UNPARENTED" value="19"> - Notification received when a node is unparented (parent removed it from the list of children). - </constant> - <constant name="NOTIFICATION_CHILDREN_CONFIGURED" value="14"> - </constant> - <constant name="NOTIFICATION_PROCESS" value="16"> - Notification received every frame when the process flag is set (see [method set_process]). - </constant> - <constant name="NOTIFICATION_EXIT_SCENE" value="11"> - </constant> - <constant name="PROCESS_ALWAYS" value="2"> - </constant> - <constant name="PROCESS_NORMAL" value="0"> - </constant> - <constant name="NOTIFICATION_EXIT_WORLD" value="21"> - </constant> - <constant name="NOTIFICATION_MOVED_IN_PARENT" value="12"> - </constant> - <constant name="NOTIFICATION_PARENTED" value="18"> - Notification received when a node is set as a child of another node. Note that this doesn't mean that a node entered the Scene Tree. - </constant> - <constant name="NOTIFICATION_ENTER_SCENE" value="10"> - </constant> - <constant name="NOTIFICATION_IDLE_PROCESS" value="17"> - Notification received every time the application enters idle when the idle process flag is set (see [method set_process]). - </constant> - </constants> -</class> -<class name="Node2D" inherits="CanvasItem" category="Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_pos" > - <argument index="0" name="pos" type="Vector2"> - </argument> - <description> - </description> - </method> - <method name="set_rot" > - <argument index="0" name="rot" type="real"> - </argument> - <description> - </description> - </method> - <method name="set_scale" > - <argument index="0" name="scale" type="Vector2"> - </argument> - <description> - </description> - </method> - <method name="get_pos" qualifiers="const" > - <return type="Vector2"> - </return> - <description> - </description> - </method> - <method name="get_rot" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="get_scale" qualifiers="const" > - <return type="Vector2"> - </return> - <description> - </description> - </method> - </methods> - <constants> - <constant name="NOTIFICATION_DRAW" value="30"> - </constant> - </constants> -</class> -<class name="_OS" inherits="Object" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_mouse_show" > - <argument index="0" name="show" type="bool"> - </argument> - <description> - </description> - </method> - <method name="set_mouse_grab" > - <argument index="0" name="grab" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_mouse_grab_enabled" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="get_mouse_pos" qualifiers="const" > - <return type="Vector2"> - </return> - <description> - </description> - </method> - <method name="set_clipboard" > - <argument index="0" name="clipboard" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_clipboard" qualifiers="const" > - <return type="String"> - </return> - <description> - </description> - </method> - <method name="set_video_mode" > - <argument index="0" name="size" type="Vector2"> - </argument> - <argument index="1" name="fullscreen" type="bool"> - </argument> - <argument index="2" name="resizable" type="bool"> - </argument> - <argument index="3" name="screen" type="int" default="0"> - </argument> - <description> - </description> - </method> - <method name="get_video_mode_size" qualifiers="const" > - <return type="Vector2"> - </return> - <argument index="0" name="screen" type="int" default="0"> - </argument> - <description> - </description> - </method> - <method name="is_video_mode_fullscreen" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="screen" type="int" default="0"> - </argument> - <description> - </description> - </method> - <method name="is_video_mode_resizable" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="screen" type="int" default="0"> - </argument> - <description> - </description> - </method> - <method name="get_fullscreen_mode_list" qualifiers="const" > - <return type="Array"> - </return> - <argument index="0" name="screen" type="int" default="0"> - </argument> - <description> - </description> - </method> - <method name="set_iterations_per_second" > - <argument index="0" name="iterations_per_second" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_iterations_per_second" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_low_processor_usage_mode" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_in_low_processor_usage_mode" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="get_executable_path" qualifiers="const" > - <return type="String"> - </return> - <description> - </description> - </method> - <method name="execute" > - <return type="int"> - </return> - <argument index="0" name="path" type="String"> - </argument> - <argument index="1" name="arguments" type="StringArray"> - </argument> - <argument index="2" name="blocking" type="bool"> - </argument> - <description> - </description> - </method> - <method name="kill" > - <return type="int"> - </return> - <argument index="0" name="pid" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_environment" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="environment" type="String"> - </argument> - <description> - </description> - </method> - <method name="has_environment" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="environment" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_name" qualifiers="const" > - <return type="String"> - </return> - <description> - </description> - </method> - <method name="get_cmdline_args" > - <return type="StringArray"> - </return> - <description> - </description> - </method> - <method name="get_main_loop" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="get_date" qualifiers="const" > - <return type="Dictionary"> - </return> - <description> - </description> - </method> - <method name="get_time" qualifiers="const" > - <return type="Dictionary"> - </return> - <description> - </description> - </method> - <method name="delay_usec" qualifiers="const" > - <argument index="0" name="usec" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_ticks_msec" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="can_draw" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="get_frames_drawn" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="is_stdout_verbose" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - </methods> - <constants> - <constant name="MONTH_NOVEMBER" value="10"> - </constant> - <constant name="MONTH_OCTOBER" value="9"> - </constant> - <constant name="MONTH_DECEMBER" value="11"> - </constant> - <constant name="MONTH_SEPTEMBER" value="8"> - </constant> - <constant name="MONTH_MAY" value="4"> - </constant> - <constant name="DAY_FRIDAY" value="5"> - </constant> - <constant name="DAY_TUESDAY" value="2"> - </constant> - <constant name="MONTH_APRIL" value="3"> - </constant> - <constant name="MONTH_FEBRUARY" value="1"> - </constant> - <constant name="DAY_MONDAY" value="1"> - </constant> - <constant name="MONTH_AUGUST" value="7"> - </constant> - <constant name="MONTH_JUNE" value="5"> - </constant> - <constant name="MONTH_JANUARY" value="0"> - </constant> - <constant name="MONTH_MARCH" value="2"> - </constant> - <constant name="MONTH_JULY" value="6"> - </constant> - <constant name="DAY_THURSDAY" value="4"> - </constant> - <constant name="DAY_WEDNESDAY" value="3"> - </constant> - <constant name="DAY_SUNDAY" value="0"> - </constant> - <constant name="DAY_SATURDAY" value="6"> - </constant> - </constants> -</class> -<class name="Object" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="get_type" qualifiers="const" > - <return type="String"> - </return> - <description> - </description> - </method> - <method name="is_type" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="type" type="String"> - </argument> - <description> - </description> - </method> - <method name="set" > - <argument index="0" name="property" type="String"> - </argument> - <argument index="1" name="value" type="var"> - </argument> - <description> - </description> - </method> - <method name="get" qualifiers="const" > - <argument index="0" name="property" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_property_list" qualifiers="const" > - <return type="Array"> - </return> - <description> - </description> - </method> - <method name="notification" > - <argument index="0" name="what" type="int"> - </argument> - <argument index="1" name="arg1" type="bool" default="false"> - </argument> - <description> - </description> - </method> - <method name="get_instance_ID" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_script" > - <argument index="0" name="script" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_script" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="set_meta" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="value" type="var"> - </argument> - <description> - </description> - </method> - <method name="get_meta" qualifiers="const" > - <argument index="0" name="name" type="String"> - </argument> - <description> - </description> - </method> - <method name="has_meta" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_meta_list" qualifiers="const" > - <return type="StringArray"> - </return> - <description> - </description> - </method> - <method name="call" > - <argument index="0" name="method" type="String"> - </argument> - <argument index="1" name="arg1" type="var" default="NULL"> - </argument> - <argument index="2" name="arg2" type="var" default="NULL"> - </argument> - <argument index="3" name="arg3" type="var" default="NULL"> - </argument> - <argument index="4" name="arg4" type="var" default="NULL"> - </argument> - <description> - </description> - </method> - <method name="call_deferred" > - <argument index="0" name="method" type="String"> - </argument> - <argument index="1" name="arg1" type="var" default="NULL"> - </argument> - <argument index="2" name="arg2" type="var" default="NULL"> - </argument> - <argument index="3" name="arg3" type="var" default="NULL"> - </argument> - <argument index="4" name="arg4" type="var" default="NULL"> - </argument> - <description> - </description> - </method> - <method name="add_user_signal" > - <argument index="0" name="signal" type="String"> - </argument> - <argument index="1" name="arguments" type="Array" default="Array()"> - </argument> - <description> - </description> - </method> - <method name="emit_signal" > - <argument index="0" name="signal" type="String"> - </argument> - <argument index="1" name="arguments" type="Array" default="Array()"> - </argument> - <description> - </description> - </method> - <method name="get_signal_list" qualifiers="const" > - <return type="Array"> - </return> - <description> - </description> - </method> - <method name="connect" > - <argument index="0" name="signal" type="String"> - </argument> - <argument index="1" name="target" type="Object"> - </argument> - <argument index="2" name="method" type="String"> - </argument> - <argument index="3" name="binds" type="Array" default="Array()"> - </argument> - <argument index="4" name="flags" type="int" default="0"> - </argument> - <description> - </description> - </method> - <method name="disconnect" > - <argument index="0" name="signal" type="String"> - </argument> - <argument index="1" name="target" type="Object"> - </argument> - <argument index="2" name="method" type="String"> - </argument> - <description> - </description> - </method> - <method name="set_block_signals" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_blocking_signals" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - </methods> - <constants> - <constant name="NOTIFICATION_POSTINITIALIZE" value="0"> - </constant> - <constant name="NOTIFICATION_PREDELETE" value="1"> - </constant> - </constants> -</class> -<class name="OmniLight" inherits="Light" category="Nodes/3D/3D Visual Nodes/3D Light Nodes"> - <brief_description> - OmniDirectional Light, such as a lightbulb or a candle. - </brief_description> - <description> - An OmniDirectional light is a type of [Light] node that emits lights in all directions. The light is attenuated through the distance and this attenuation can be configured by changing the energy, radius and attenuation parameters of [Light]. TODO: Image of an omnilight. - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="OptionButton" inherits="Button" category="Nodes/GUI Nodes"> - <brief_description> - Button control that provides selectable options when pressed. - </brief_description> - <description> - OptionButton is a type button that provides a selectable list of items when pressed. The item selected becomes the "current" item and is displayed as the button text. - </description> - <methods> - <method name="add_item" > - <argument index="0" name="label" type="String"> - </argument> - <argument index="1" name="id" type="int" default="-1"> - </argument> - <description> - Add an item, with text "label" and (optionally) id. If no "id" is passed, "id" becomes the item index. New items are appended at the end. - </description> - </method> - <method name="add_icon_item" > - <argument index="0" name="texture" type="Object"> - </argument> - <argument index="1" name="label" type="String"> - </argument> - <argument index="2" name="id" type="int"> - </argument> - <description> - Add an item, with a "texture" icon, text "label" and (optionally) id. If no "id" is passed, "id" becomes the item index. New items are appended at the end. - </description> - </method> - <method name="set_item_text" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="text" type="String"> - </argument> - <description> - Set the text of an item at index "idx". - </description> - </method> - <method name="set_item_icon" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="texture" type="Object"> - </argument> - <description> - Set the icon of an item at index "idx". - </description> - </method> - <method name="set_item_disabled" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="disabled" type="bool"> - </argument> - <description> - </description> - </method> - <method name="set_item_ID" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="id" type="int"> - </argument> - <description> - Set the ID of an item at index "idx". - </description> - </method> - <method name="set_item_metadata" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="metadata" type="var"> - </argument> - <description> - </description> - </method> - <method name="get_item_text" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <description> - Return the text of the item at index "idx". - </description> - </method> - <method name="get_item_icon" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <description> - Return the icon of the item at index "idx". - </description> - </method> - <method name="get_item_ID" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <description> - Return the ID of the item at index "idx". - </description> - </method> - <method name="get_item_metadata" qualifiers="const" > - <argument index="0" name="idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="is_item_disabled" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_item_count" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the amount of items in the OptionButton. - </description> - </method> - <method name="add_separator" > - <description> - Add a separator to the list of items. Separators help to group items. Separator also takes up an index and is appended at the end. - </description> - </method> - <method name="clear" > - <description> - Clear all the items in the [OptionButton]. - </description> - </method> - <method name="select" > - <argument index="0" name="arg0" type="int"> - </argument> - <description> - Select an item by index and make it the current item. - </description> - </method> - <method name="get_selected" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the current item index - </description> - </method> - <method name="get_selected_ID" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="get_selected_metadata" qualifiers="const" > - <description> - </description> - </method> - </methods> - <signals> - <signal name="item_selected"> - <argument index="0" name="ID" type="int"> - </argument> - <description> - This signal is emitted when the current item was changed by the user. ID of the item selected is passed as argument (if no IDs were added, ID will be just the item index). - </description> - </signal> - </signals> - <constants> - </constants> -</class> -<class name="PacketPeer" inherits="Object" category="Core"> - <brief_description> - Abstraction and base class for packet-based protocols. - </brief_description> - <description> - PacketPeer is an abstration and base class for packet-based protocols (such as UDP). It provides an API for sending and receiving packets both as raw data or variables. This makes it easy to transfer data over a protocol, without having to encode data as low level bytes or having to worry about network ordering. - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="PacketPeerStream" inherits="PacketPeer" category="Core"> - <brief_description> - Wrapper to use a PacketPeer over a StreamPeer. - </brief_description> - <description> - PacketStreamPeer provides a wrapper for working using packets over a stream. This allows for using packet based code with StreamPeers. PacketPeerStream implements a custom protocol over the StreamPeer, so the user should not read or write to the wrapped StreamPeer directly. - </description> - <methods> - <method name="set_stream_peer" > - <argument index="0" name="peer" type="Object"> - </argument> - <description> - Set the StreamPeer object to be wrapped - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="Panel" inherits="Control" category="Nodes/GUI Nodes"> - <brief_description> - Provides an opaque background for [Control] children. - </brief_description> - <description> - Panel is a [Control] that displays an opaque background. It's commoly used as a parent and container for other types of [Control] nodes. 	[html div align="center"][html img src="images/panel_example.png"/][html /div] - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="Particles" inherits="VisualInstance" category="Nodes/3D/3D Visual Nodes"> - <brief_description> - Particle system 3D Node - </brief_description> - <description> - Particles is a particle system 3D [Node] that is used to simulate several types of particle effects, such as explosions, rain, snow, fireflies, or other magical-like shinny sparkles. Particles are drawn using impostors, and given their dynamic behavior, the user must provide a visibility AABB (although helpers to create one automatically exist). - </description> - <methods> - <method name="set_amount" > - <argument index="0" name="amount" type="int"> - </argument> - <description> - Set total amount of particles in the system. - </description> - </method> - <method name="get_amount" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the total amount of particles in the system. - </description> - </method> - <method name="set_emitting" > - <argument index="0" name="enabled" type="bool"> - </argument> - <description> - Set the "emitting" property state. When emitting, the particle system generates new particles at constant rate. - </description> - </method> - <method name="is_emitting" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return the "emitting" property state (see [method set_emitting]). - </description> - </method> - <method name="set_visibility_aabb" > - <argument index="0" name="aabb" type="AABB"> - </argument> - <description> - Set the visibility AABB for the particle system, since the default one will not work properly most of the time. - </description> - </method> - <method name="get_visibility_aabb" qualifiers="const" > - <return type="AABB"> - </return> - <description> - Return the current visibility AABB. - </description> - </method> - <method name="set_emission_half_extents" > - <argument index="0" name="half_extents" type="Vector3"> - </argument> - <description> - Set the half extents for the emission box. - </description> - </method> - <method name="get_emission_half_extents" qualifiers="const" > - <return type="Vector3"> - </return> - <description> - Return the half extents for the emission box. - </description> - </method> - <method name="set_emission_points" > - <argument index="0" name="points" type="Vector3Array"> - </argument> - <description> - </description> - </method> - <method name="get_emission_points" qualifiers="const" > - <return type="Vector3Array"> - </return> - <description> - </description> - </method> - <method name="set_gravity_normal" > - <argument index="0" name="normal" type="Vector3"> - </argument> - <description> - Set the normal vector towards where gravity is pulling (by default, negative Y). - </description> - </method> - <method name="get_gravity_normal" qualifiers="const" > - <return type="Vector3"> - </return> - <description> - Return the normal vector towards where gravity is pulling (by default, negative Y). - </description> - </method> - <method name="set_variable" > - <argument index="0" name="variable" type="int"> - </argument> - <argument index="1" name="value" type="real"> - </argument> - <description> - Set a specific variable for the particle system (see VAR_* enum). - </description> - </method> - <method name="get_variable" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="variable" type="int"> - </argument> - <description> - Return a specific variable for the particle system (see VAR_* enum). - </description> - </method> - <method name="set_randomness" > - <argument index="0" name="variable" type="int"> - </argument> - <argument index="1" name="randomness" type="real"> - </argument> - <description> - Set the randomness for a specific variable of the particle system. Randomness produces small changes from the default each time a particle is emitted. - </description> - </method> - <method name="get_randomness" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="arg0" type="int"> - </argument> - <description> - Return the randomness for a specific variable of the particle system. Randomness produces small changes from the default each time a particle is emitted. - </description> - </method> - <method name="set_color_phase_pos" > - <argument index="0" name="phase" type="int"> - </argument> - <argument index="1" name="pos" type="real"> - </argument> - <description> - Set the position of a color phase (0 to 1) - </description> - </method> - <method name="get_color_phase_pos" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="phase" type="int"> - </argument> - <description> - Return the position of a color phase (0 to 1) - </description> - </method> - <method name="set_color_phase_color" > - <argument index="0" name="phase" type="int"> - </argument> - <argument index="1" name="color" type="Color"> - </argument> - <description> - Set the color of a color phase. - </description> - </method> - <method name="get_color_phase_color" qualifiers="const" > - <return type="Color"> - </return> - <argument index="0" name="phase" type="int"> - </argument> - <description> - Return the color of a color phase. - </description> - </method> - <method name="set_material" > - <argument index="0" name="material" type="Object"> - </argument> - <description> - Set the material used to draw particles - </description> - </method> - <method name="get_material" qualifiers="const" > - <return type="Object"> - </return> - <description> - Return the material used to draw particles - </description> - </method> - <method name="set_emit_timeout" > - <argument index="0" name="arg0" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_emit_timeout" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="set_height_from_velocity" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="has_height_from_velocity" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_color_phases" > - <argument index="0" name="count" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_color_phases" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - </methods> - <constants> - <constant name="VAR_FINAL_SIZE" value="9"> - </constant> - <constant name="VAR_INITIAL_SIZE" value="8"> - </constant> - <constant name="VAR_LINEAR_ACCELERATION" value="5"> - </constant> - <constant name="VAR_MAX" value="13"> - </constant> - <constant name="VAR_DRAG" value="6"> - </constant> - <constant name="VAR_GRAVITY" value="2"> - </constant> - <constant name="VAR_SPREAD" value="1"> - </constant> - <constant name="VAR_LIFETIME" value="0"> - </constant> - <constant name="VAR_HEIGHT_SPEED_SCALE" value="12"> - </constant> - <constant name="VAR_INITIAL_ANGLE" value="10"> - </constant> - <constant name="VAR_TANGENTIAL_ACCELERATION" value="7"> - </constant> - <constant name="VAR_ANGULAR_VELOCITY" value="4"> - </constant> - <constant name="VAR_HEIGHT" value="11"> - </constant> - <constant name="VAR_LINEAR_VELOCITY" value="3"> - </constant> - </constants> -</class> -<class name="Particles2D" inherits="Node2D" category="Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_emitting" > - <argument index="0" name="active" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_emitting" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_amount" > - <argument index="0" name="amount" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_amount" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_lifetime" > - <argument index="0" name="lifetime" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_lifetime" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="set_param" > - <argument index="0" name="param" type="int"> - </argument> - <argument index="1" name="value" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_param" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="param" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_randomness" > - <argument index="0" name="param" type="int"> - </argument> - <argument index="1" name="value" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_randomness" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="param" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_texture" > - <argument index="0" name="texture" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_texture" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="set_emissor_offset" > - <argument index="0" name="offset" type="Vector2"> - </argument> - <description> - </description> - </method> - <method name="get_emissor_offset" qualifiers="const" > - <return type="Vector2"> - </return> - <description> - </description> - </method> - <method name="set_initial_color" > - <argument index="0" name="initial_color" type="Color"> - </argument> - <description> - </description> - </method> - <method name="get_initial_color" qualifiers="const" > - <return type="Color"> - </return> - <description> - </description> - </method> - <method name="set_final_color" > - <argument index="0" name="final_color" type="Color"> - </argument> - <description> - </description> - </method> - <method name="get_final_color" qualifiers="const" > - <return type="Color"> - </return> - <description> - </description> - </method> - <method name="set_use_parent_space" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_using_parent_space" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - </methods> - <constants> - <constant name="PARAM_FINAL_SIZE" value="9"> - </constant> - <constant name="PARAM_INITIAL_SIZE" value="8"> - </constant> - <constant name="PARAM_RADIAL_ACCEL" value="6"> - </constant> - <constant name="PARAM_GRAVITY_STRENGTH" value="5"> - </constant> - <constant name="PARAM_MAX" value="11"> - </constant> - <constant name="PARAM_HUE_VARIATION" value="10"> - </constant> - <constant name="PARAM_TANGENTIAL_ACCEL" value="7"> - </constant> - <constant name="PARAM_GRAVITY_DIRECTION" value="4"> - </constant> - <constant name="PARAM_SPREAD" value="1"> - </constant> - <constant name="PARAM_SPIN_VELOCITY" value="3"> - </constant> - <constant name="PARAM_LINEAR_VELOCITY" value="2"> - </constant> - <constant name="PARAM_DIRECTION" value="0"> - </constant> - </constants> -</class> -<class name="PhysicsBody" inherits="Spatial" category="Nodes/3D"> - <brief_description> - Base class for differnt types of Physics bodies. - </brief_description> - <description> - PhysicsBody is an abstract base class for implementing a physics body. All PhysicsBody types inherit from it. - </description> - <methods> - <method name="add_shape" > - <argument index="0" name="shape" type="Object"> - </argument> - <argument index="1" name="transform" type="Transform" default="Transform()"> - </argument> - <description> - </description> - </method> - <method name="get_shape_count" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_shape" > - <argument index="0" name="shape_idx" type="int"> - </argument> - <argument index="1" name="shape" type="Object"> - </argument> - <description> - </description> - </method> - <method name="set_shape_transform" > - <argument index="0" name="shape_idx" type="int"> - </argument> - <argument index="1" name="transform" type="Transform"> - </argument> - <description> - </description> - </method> - <method name="get_shape" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="shape_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_shape_transform" qualifiers="const" > - <return type="Transform"> - </return> - <argument index="0" name="shape_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="remove_shape" > - <argument index="0" name="shape_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="clear_shapes" > - <description> - </description> - </method> - <method name="get_body" qualifiers="const" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="set_max_contacts_reported" > - <argument index="0" name="contacts" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_max_contacts_reported" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_contacts_reported_depth_treshold" > - <argument index="0" name="depth" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_contacts_reported_depth_treshold" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="PhysicsDirectBodyState" inherits="Object" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="get_total_gravity" qualifiers="const" > - <return type="Vector3"> - </return> - <description> - </description> - </method> - <method name="get_total_density" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="get_inverse_mass" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="get_inverse_inertia_tensor" qualifiers="const" > - <return type="Matrix3"> - </return> - <description> - </description> - </method> - <method name="set_linear_velocity" > - <argument index="0" name="velocity" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="get_linear_velocity" qualifiers="const" > - <return type="Vector3"> - </return> - <description> - </description> - </method> - <method name="set_angular_velocity" > - <argument index="0" name="velocity" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="get_angular_velocity" qualifiers="const" > - <return type="Vector3"> - </return> - <description> - </description> - </method> - <method name="set_transform" > - <argument index="0" name="transform" type="Transform"> - </argument> - <description> - </description> - </method> - <method name="get_transform" qualifiers="const" > - <return type="Transform"> - </return> - <description> - </description> - </method> - <method name="set_sleep_state" > - <argument index="0" name="enabled" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_sleeping" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="get_contact_count" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="get_contact_local_pos" qualifiers="const" > - <return type="Vector3"> - </return> - <argument index="0" name="contact_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_contact_local_normal" qualifiers="const" > - <return type="Vector3"> - </return> - <argument index="0" name="contact_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_contact_local_shape" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="contact_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_contact_collider" qualifiers="const" > - <return type="RID"> - </return> - <argument index="0" name="contact_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_contact_collider_pos" qualifiers="const" > - <return type="Vector3"> - </return> - <argument index="0" name="contact_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_contact_collider_id" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="contact_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_contact_collider_shape" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="contact_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_contact_collider_velocity_at_pos" qualifiers="const" > - <return type="Vector3"> - </return> - <argument index="0" name="contact_idx" type="int"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="PhysicsDirectBodyStateSW" inherits="PhysicsDirectBodyState" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="PhysicsServer" inherits="Object" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="shape_create" > - <return type="RID"> - </return> - <argument index="0" name="shape_type" type="int"> - </argument> - <description> - </description> - </method> - <method name="shape_set_data" > - <argument index="0" name="shape" type="RID"> - </argument> - <argument index="1" name="data" type="var"> - </argument> - <argument index="2" name="margin" type="real" default="-1"> - </argument> - <description> - </description> - </method> - <method name="shape_get_type" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="shape" type="RID"> - </argument> - <description> - </description> - </method> - <method name="shape_get_data" qualifiers="const" > - <argument index="0" name="shape" type="RID"> - </argument> - <description> - </description> - </method> - <method name="space_create" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="area_create" > - <return type="RID"> - </return> - <argument index="0" name="space" type="int"> - </argument> - <argument index="1" name="arg1" type="bool" default="RID()"> - </argument> - <description> - </description> - </method> - <method name="area_set_param" > - <argument index="0" name="area" type="RID"> - </argument> - <argument index="1" name="param" type="int"> - </argument> - <argument index="2" name="value" type="var"> - </argument> - <description> - </description> - </method> - <method name="area_set_shape" > - <argument index="0" name="area" type="RID"> - </argument> - <argument index="1" name="shape" type="RID"> - </argument> - <description> - </description> - </method> - <method name="area_set_bounds" > - <argument index="0" name="area" type="RID"> - </argument> - <argument index="1" name="bounds" type="Dictionary"> - </argument> - <description> - </description> - </method> - <method name="area_set_transform" > - <argument index="0" name="area" type="RID"> - </argument> - <argument index="1" name="transform" type="Transform"> - </argument> - <description> - </description> - </method> - <method name="area_get_param" qualifiers="const" > - <argument index="0" name="area" type="RID"> - </argument> - <argument index="1" name="param" type="int"> - </argument> - <description> - </description> - </method> - <method name="area_get_shape" qualifiers="const" > - <return type="RID"> - </return> - <argument index="0" name="area" type="RID"> - </argument> - <description> - </description> - </method> - <method name="area_get_bounds" qualifiers="const" > - <return type="Dictionary"> - </return> - <argument index="0" name="area" type="RID"> - </argument> - <description> - </description> - </method> - <method name="area_get_transform" qualifiers="const" > - <return type="Transform"> - </return> - <argument index="0" name="area" type="RID"> - </argument> - <description> - </description> - </method> - <method name="body_create" > - <return type="RID"> - </return> - <argument index="0" name="space" type="int"> - </argument> - <argument index="1" name="arg1" type="bool" default="RID()"> - </argument> - <description> - </description> - </method> - <method name="body_set_mode" > - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="mode" type="int"> - </argument> - <description> - </description> - </method> - <method name="body_get_mode" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="body_add_shape" > - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="shape" type="RID"> - </argument> - <argument index="2" name="transform" type="Transform" default="Transform()"> - </argument> - <description> - </description> - </method> - <method name="body_set_shape" > - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="shape_idx" type="int"> - </argument> - <argument index="2" name="shape" type="RID"> - </argument> - <description> - </description> - </method> - <method name="body_set_shape_transform" > - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="shape_idx" type="int"> - </argument> - <argument index="2" name="transform" type="Transform"> - </argument> - <description> - </description> - </method> - <method name="body_get_shape_count" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="body" type="RID"> - </argument> - <description> - </description> - </method> - <method name="body_get_shape" qualifiers="const" > - <return type="RID"> - </return> - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="shape_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="body_get_shape_transform" qualifiers="const" > - <return type="Transform"> - </return> - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="shape_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="body_attach_object_instance_ID" > - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="ID" type="int"> - </argument> - <description> - </description> - </method> - <method name="body_get_object_instance_ID" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="body" type="RID"> - </argument> - <description> - </description> - </method> - <method name="body_set_user_flags" > - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="user_flags" type="int"> - </argument> - <description> - </description> - </method> - <method name="body_get_user_flags" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="body_set_param" > - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="param" type="int"> - </argument> - <argument index="2" name="value" type="real"> - </argument> - <description> - </description> - </method> - <method name="body_get_param" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="param" type="int"> - </argument> - <description> - </description> - </method> - <method name="body_static_simulate_motion" > - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="motion" type="Transform"> - </argument> - <description> - </description> - </method> - <method name="body_set_state" > - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="state" type="int"> - </argument> - <argument index="2" name="value" type="var"> - </argument> - <description> - </description> - </method> - <method name="body_get_state" qualifiers="const" > - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="state" type="int"> - </argument> - <description> - </description> - </method> - <method name="body_set_applied_force" > - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="applied_force" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="body_get_applied_force" qualifiers="const" > - <return type="Vector3"> - </return> - <argument index="0" name="body" type="RID"> - </argument> - <description> - </description> - </method> - <method name="body_set_applied_torque" > - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="applied_torque" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="body_get_applied_torque" qualifiers="const" > - <return type="Vector3"> - </return> - <argument index="0" name="body" type="RID"> - </argument> - <description> - </description> - </method> - <method name="body_set_axis_velocity" > - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="axis_velocity" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="body_apply_impulse" > - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="pos" type="Vector3"> - </argument> - <argument index="2" name="impulse" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="body_add_collision_exception" > - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="against_body" type="RID"> - </argument> - <description> - </description> - </method> - <method name="body_remove_collision_exception" > - <argument index="0" name="body" type="RID"> - </argument> - <argument index="1" name="against_body" type="RID"> - </argument> - <description> - </description> - </method> - <method name="query_create" > - <return type="RID"> - </return> - <argument index="0" name="receiver" type="Object"> - </argument> - <argument index="1" name="callback" type="String"> - </argument> - <argument index="2" name="userdata" type="var"> - </argument> - <argument index="3" name="persist" type="bool" default="true"> - </argument> - <description> - </description> - </method> - <method name="query_body_state" > - <argument index="0" name="query" type="RID"> - </argument> - <argument index="1" name="body" type="RID"> - </argument> - <description> - </description> - </method> - <method name="query_body_direct_state" > - <argument index="0" name="query" type="RID"> - </argument> - <argument index="1" name="body" type="RID"> - </argument> - <description> - </description> - </method> - <method name="query_area" > - <argument index="0" name="query" type="RID"> - </argument> - <argument index="1" name="area" type="RID"> - </argument> - <description> - </description> - </method> - <method name="query_intersection" > - <argument index="0" name="query" type="RID"> - </argument> - <argument index="1" name="space" type="RID"> - </argument> - <argument index="2" name="exclude" type="Array" default="Array()"> - </argument> - <argument index="3" name="usermask" type="int" default="0"> - </argument> - <description> - </description> - </method> - <method name="query_intersection_ray" > - <argument index="0" name="query" type="RID"> - </argument> - <argument index="1" name="origin" type="Vector3"> - </argument> - <argument index="2" name="dir" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="query_intersection_segment" > - <argument index="0" name="query" type="RID"> - </argument> - <argument index="1" name="from" type="Vector3"> - </argument> - <argument index="2" name="to" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="query_intersection_shape" > - <argument index="0" name="query" type="RID"> - </argument> - <argument index="1" name="shape" type="RID"> - </argument> - <argument index="2" name="arg2" type="Transform"> - </argument> - <description> - </description> - </method> - <method name="query_intersection_bounds" > - <argument index="0" name="query" type="RID"> - </argument> - <argument index="1" name="bounds" type="Dictionary"> - </argument> - <argument index="2" name="arg2" type="Transform"> - </argument> - <description> - </description> - </method> - <method name="query_clear" > - <argument index="0" name="query" type="RID"> - </argument> - <description> - </description> - </method> - <method name="query_get_type" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="query" type="RID"> - </argument> - <description> - </description> - </method> - <method name="query_get_target" qualifiers="const" > - <return type="RID"> - </return> - <argument index="0" name="query" type="RID"> - </argument> - <description> - </description> - </method> - <method name="free" > - <argument index="0" name="rid" type="RID"> - </argument> - <description> - </description> - </method> - <method name="set_active" > - <argument index="0" name="active" type="bool"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - <constant name="QUERY_BODY_STATE" value="1"> - </constant> - <constant name="BODY_PARAM_FRICTION" value="1"> - </constant> - <constant name="AREA_PARAM_OVERRIDE_PARAMS" value="0"> - </constant> - <constant name="SHAPE_CUSTOM" value="9"> - </constant> - <constant name="QUERY_INTERSECTION" value="4"> - </constant> - <constant name="BODY_STATE_SLEEPING" value="3"> - </constant> - <constant name="QUERY_AREA_MONITOR" value="3"> - </constant> - <constant name="QUERY_BODY_DIRECT_STATE" value="2"> - </constant> - <constant name="QUERY_NONE" value="0"> - </constant> - <constant name="CONE_TWIST_VAR_RELAXATION" value="4"> - </constant> - <constant name="CONE_TWIST_VAR_BIAS" value="3"> - </constant> - <constant name="CONE_TWIST_VAR_SWING_SPAN_LIMIT_1" value="0"> - </constant> - <constant name="HINGE_VAR_MOTOR_ENABLED" value="5"> - </constant> - <constant name="HINGE_VAR_LIMIT_SOFTNESS" value="3"> - </constant> - <constant name="HINGE_VAR_ANGULAR_ONLY" value="0"> - </constant> - <constant name="BODY_STATE_ANGULAR_VELOCITY" value="2"> - </constant> - <constant name="SHAPE_CAPSULE" value="5"> - </constant> - <constant name="CONE_TWIST_VAR_SWING_SPAN_LIMIT_2" value="1"> - </constant> - <constant name="BODY_STATE_LINEAR_VELOCITY" value="1"> - </constant> - <constant name="BODY_MODE_CHARACTER" value="2"> - </constant> - <constant name="AREA_PARAM_GRAVITY" value="1"> - </constant> - <constant name="SHAPE_CONCAVE_POLYGON" value="7"> - </constant> - <constant name="TYPE_BODY" value="0"> - </constant> - <constant name="HINGE_VAR_MOTOR_TARGET_VELOCITY" value="6"> - </constant> - <constant name="HINGE_VAR_HIGHER_LIMIT" value="2"> - </constant> - <constant name="SHAPE_HEIGHTMAP" value="8"> - </constant> - <constant name="SHAPE_SPHERE" value="2"> - </constant> - <constant name="CONE_TWIST_VAR_TWIST_SPAN_LIMIT" value="2"> - </constant> - <constant name="BODY_MODE_RIGID" value="1"> - </constant> - <constant name="AREA_PARAM_DENSITY" value="5"> - </constant> - <constant name="AREA_PARAM_GRAVITY_VECTOR" value="2"> - </constant> - <constant name="SHAPE_PLANE" value="0"> - </constant> - <constant name="HINGE_VAR_MOTOR_IMPULSE" value="7"> - </constant> - <constant name="HINGE_VAR_RELAXATION" value="4"> - </constant> - <constant name="HINGE_VAR_LOWER_LIMIT" value="1"> - </constant> - <constant name="BODY_STATE_TRANSFORM" value="0"> - </constant> - <constant name="BODY_PARAM_MASS" value="2"> - </constant> - <constant name="BODY_PARAM_BOUNCE" value="0"> - </constant> - <constant name="BODY_MODE_STATIC" value="0"> - </constant> - <constant name="SHAPE_BOX" value="3"> - </constant> - <constant name="TYPE_AREA" value="1"> - </constant> - <constant name="AREA_PARAM_PRIORITY" value="6"> - </constant> - <constant name="AREA_PARAM_GRAVITY_POINT_ATTENUATION" value="4"> - </constant> - <constant name="AREA_PARAM_GRAVITY_IS_POINT" value="3"> - </constant> - <constant name="SHAPE_CONVEX_POLYGON" value="6"> - </constant> - <constant name="SHAPE_CYLINDER" value="4"> - </constant> - </constants> -</class> -<class name="PhysicsServerSW" inherits="PhysicsServer" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="PlaneShape" inherits="Shape" category="Resources"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_plane" > - <argument index="0" name="plane" type="Plane"> - </argument> - <description> - </description> - </method> - <method name="get_plane" qualifiers="const" > - <return type="Plane"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="Popup" inherits="Control" category="Core"> - <brief_description> - Base container control for popups and dialogs. - </brief_description> - <description> - PopUp is a base [Control] used to show dialogs and popups. It's a subwindow and modal by default (see [Control]) and has helpers for custom popup behavior. - </description> - <methods> - <method name="popup_centered" > - <argument index="0" name="size" type="Vector2" default="Vector2(0,0)"> - </argument> - <description> - Popup (show the control in modal form) in the center of the screen, at the curent size, or at a size determined by "size". - </description> - </method> - <method name="popup_centered_ratio" > - <argument index="0" name="ratio" type="real" default="0.75"> - </argument> - <description> - Popup (show the control in modal form) in the center of the screen, scalled at a ratio of size of the screen. - </description> - </method> - <method name="popup" > - <description> - Popup (show the control in modal form). - </description> - </method> - <method name="set_exclusive" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_exclusive" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - </methods> - <signals> - <signal name="about_to_show"> - <description> - This signal is emitted when a popup is about to be shown. (often used in [PopupMenu] for clearing the list of options and creating a new one according to the current context). - </description> - </signal> - </signals> - <constants> - </constants> -</class> -<class name="PopupDialog" inherits="Popup" category="Nodes/GUI Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="PopupMenu" inherits="Popup" category="Nodes/GUI Nodes"> - <brief_description> - PopupMenu displays a list of options. - </brief_description> - <description> - PopupMenu is the typical Control that displays a list of options. They are popular in toolbars or context menus. - </description> - <methods> - <method name="add_icon_item" > - <argument index="0" name="texture" type="Object"> - </argument> - <argument index="1" name="label" type="String"> - </argument> - <argument index="2" name="id" type="int" default="-1"> - </argument> - <argument index="3" name="accel" type="int" default="0"> - </argument> - <description> - Add a new item with text "label" and icon "texture. An id can optonally be provided, as well as an accelerator. If no id is provided, one will be created from the index. - </description> - </method> - <method name="add_item" > - <argument index="0" name="label" type="String"> - </argument> - <argument index="1" name="id" type="int" default="-1"> - </argument> - <argument index="2" name="accel" type="int" default="0"> - </argument> - <description> - Add a new item with text "label". An id can optonally be provided, as well as an accelerator. If no id is provided, one will be created from the index. - </description> - </method> - <method name="add_icon_check_item" > - <argument index="0" name="texture" type="Object"> - </argument> - <argument index="1" name="label" type="String"> - </argument> - <argument index="2" name="id" type="int" default="-1"> - </argument> - <argument index="3" name="accel" type="int" default="0"> - </argument> - <description> - Add a new checkable item with text "label" and icon "texture. An id can optonally be provided, as well as an accelerator. If no id is provided, one will be created from the index. Note that checkable items just display a checkmark, but don't have any built-in checking behavior and must be checked/unchecked manually. - </description> - </method> - <method name="add_check_item" > - <argument index="0" name="label" type="String"> - </argument> - <argument index="1" name="id" type="int" default="-1"> - </argument> - <argument index="2" name="accel" type="int" default="0"> - </argument> - <description> - Add a new checkable item with text "label". An id can optonally be provided, as well as an accelerator. If no id is provided, one will be created from the index. Note that checkable items just display a checkmark, but don't have any built-in checking behavior and must be checked/unchecked manually. - </description> - </method> - <method name="set_item_text" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="text" type="String"> - </argument> - <description> - Set the text of the item at index "idx". - </description> - </method> - <method name="set_item_icon" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="icon" type="Object"> - </argument> - <description> - Set the icon of the item at index "idx". - </description> - </method> - <method name="set_item_accelerator" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="accel" type="int"> - </argument> - <description> - Set the accelerator of the item at index "idx". Accelerators are special combinations of keys that activate the item, no matter which control is fucused. - </description> - </method> - <method name="set_item_metadata" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="metadata" type="var"> - </argument> - <description> - </description> - </method> - <method name="set_item_checked" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="arg1" type="bool"> - </argument> - <description> - Set the checkstate status of the item at index "idx". - </description> - </method> - <method name="set_item_disabled" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="arg1" type="bool"> - </argument> - <description> - </description> - </method> - <method name="set_item_ID" > - <argument index="0" name="idx" type="int"> - </argument> - <argument index="1" name="id" type="int"> - </argument> - <description> - Set the id of the item at index "idx". - </description> - </method> - <method name="get_item_text" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <description> - Return the text of the item at index "idx". - </description> - </method> - <method name="get_item_icon" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <description> - Return the icon of the item at index "idx". - </description> - </method> - <method name="get_item_metadata" qualifiers="const" > - <argument index="0" name="idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_item_accelerator" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <description> - Return the accelerator of the item at index "idx". Accelerators are special combinations of keys that activate the item, no matter which control is fucused. - </description> - </method> - <method name="is_item_checked" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <description> - Return the checkstate status of the item at index "idx". - </description> - </method> - <method name="is_item_disabled" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_item_ID" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <description> - Return the id of the item at index "idx". - </description> - </method> - <method name="get_item_index" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - Find and return the index of the item containing a given id. - </description> - </method> - <method name="get_item_count" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the amount of items. - </description> - </method> - <method name="add_separator" > - <description> - Add a separator between items. Separators also occupy an index. - </description> - </method> - <method name="clear" > - <description> - Clear the popup menu. - </description> - </method> - </methods> - <signals> - <signal name="item_pressed"> - <argument index="0" name="ID" type="int"> - </argument> - <description> - This even is emitted when an item is pressed or its accelerator is activated. The id of the item is returned if it exists, else the index. - </description> - </signal> - </signals> - <constants> - </constants> -</class> -<class name="PopupPanel" inherits="Popup" category="Nodes/GUI Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="Portal" inherits="VisualInstance" category="Nodes/3D/3D Visual Nodes"> - <brief_description> - Portals provide virtual openings to rooms. - </brief_description> - <description> - Portals provide virtual openings to [RoomInstance] nodes, so cameras can look at them from the outside. Note that portals are a visibility optimization technique, and are in no way related to the game of the same name (as in, they are not used for teleportation). For more information on how rooms and portals work, see [RoomInstance]. Portals are represented as 2D convex polygon shapes (in the X,Y local plane), and are placed on the surface of the areas occupied by a [RoomInstance], to indicate that the room can be accessed or looked-at through them. If two rooms are next to each other, and two similar portals in each of them share the same world position (and are parallel and opposed to each other), they will automatically "connect" and form "doors" (for example, the portals that connect a kitchen to a living room are placed in the door they share). Portals must always have a [RoomInstance] node as a parent, grandparent or far parent, or else they will not be active. - </description> - <methods> - <method name="set_shape" > - <argument index="0" name="points" type="Array"> - </argument> - <description> - Set the portal shape. The shape is an array of [Point2] points, representing a convex polygon in the X,Y plane. - </description> - </method> - <method name="get_shape" qualifiers="const" > - <return type="Array"> - </return> - <description> - Return the portal shape. The shape is an array of [Point2] points, representing a convex polygon in the X,Y plane. - </description> - </method> - <method name="set_enabled" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - Enable the portal (it is enabled by defaul though), disabling it will cause the parent [RoomInstance] to not be visible any longer when looking through the portal. - </description> - </method> - <method name="is_enabled" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return wether the portal is active. When disabled it causes the parent [RoomInstance] to not be visible any longer when looking through the portal. - </description> - </method> - <method name="set_disable_distance" > - <argument index="0" name="distance" type="real"> - </argument> - <description> - Set the distance threshold for disabling the portal. Every time that the portal goes beyond "distance", it disables itself, becoming the opaque color (see [method set_disabled_color]). - </description> - </method> - <method name="get_disable_distance" qualifiers="const" > - <return type="real"> - </return> - <description> - Return the distance threshold for disabling the portal. Every time that the portal goes beyond "distance", it disables itself, becoming the opaque color (see [method set_disabled_color]). - </description> - </method> - <method name="set_disabled_color" > - <argument index="0" name="color" type="Color"> - </argument> - <description> - When the portal goes beyond the disable distance (see [method set_disable_distance]), it becomes opaque and displayed with color "color". - </description> - </method> - <method name="get_disabled_color" qualifiers="const" > - <return type="Color"> - </return> - <description> - Return the color for when the portal goes beyond the disable distance (see [method set_disable_distance]) and becomes disabled. - </description> - </method> - <method name="set_connect_range" > - <argument index="0" name="range" type="real"> - </argument> - <description> - Set the range for auto-connecting two portals from different rooms sharing the same space. - </description> - </method> - <method name="get_connect_range" qualifiers="const" > - <return type="real"> - </return> - <description> - Return the range for auto-connecting two portals from different rooms sharing the same space. - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="Range" inherits="Control" category="Core"> - <brief_description> - Abstract base class for range-based controls. - </brief_description> - <description> - Range is a base class for [Control] nodes that change a floating point [html i]value[html /i] between a need a [html i]minimum[html /i], [html i]maximum[html /i], using [html i]step[html /i] and [html i]page[html /i], for example a [ScrollBar]. - </description> - <methods> - <method name="get_val" qualifiers="const" > - <return type="real"> - </return> - <description> - Return the current value. - </description> - </method> - <method name="get_min" qualifiers="const" > - <return type="real"> - </return> - <description> - Return the minimum value. - </description> - </method> - <method name="get_max" qualifiers="const" > - <return type="real"> - </return> - <description> - Return the maximum value. - </description> - </method> - <method name="get_step" qualifiers="const" > - <return type="real"> - </return> - <description> - Return the stepping, if step is 0, stepping is disabled. - </description> - </method> - <method name="get_page" qualifiers="const" > - <return type="real"> - </return> - <description> - Return the page size, if page is 0, paging is disabled. - </description> - </method> - <method name="get_unit_value" qualifiers="const" > - <return type="real"> - </return> - <description> - Return value mapped to 0 to 1 (unit) range. - </description> - </method> - <method name="set_val" > - <argument index="0" name="value" type="real"> - </argument> - <description> - </description> - </method> - <method name="set_min" > - <argument index="0" name="minimum" type="real"> - </argument> - <description> - Set minimum value, clamped range value to it if it's less. - </description> - </method> - <method name="set_max" > - <argument index="0" name="maximum" type="real"> - </argument> - <description> - </description> - </method> - <method name="set_step" > - <argument index="0" name="step" type="real"> - </argument> - <description> - Set step value. If step is 0, stepping will be disabled. - </description> - </method> - <method name="set_page" > - <argument index="0" name="pagesize" type="real"> - </argument> - <description> - Set page size. Page is mainly used for scrollbars or anything that controls text scrolling. - </description> - </method> - <method name="set_unit_value" > - <argument index="0" name="value" type="real"> - </argument> - <description> - Set value mapped to 0 to 1 (unit) range, it will then be converted to the actual value within min and max. - </description> - </method> - <method name="share" > - <argument index="0" name="with" type="Object"> - </argument> - <description> - </description> - </method> - <method name="unshare" > - <description> - </description> - </method> - </methods> - <signals> - <signal name="value_changed"> - <argument index="0" name="value" type="real"> - </argument> - <description> - This signal is emitted when value changes. - </description> - </signal> - <signal name="changed"> - <description> - This signal is emitted when min, max, range or step change. - </description> - </signal> - </signals> - <constants> - </constants> -</class> -<class name="RayShape" inherits="Shape" category="Resources"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_length" > - <argument index="0" name="length" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_length" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="Reference" inherits="Object" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="Resource" inherits="Reference" category="Resources"> - <brief_description> - Base class for all resources. - </brief_description> - <description> - Resource is the base class for all resource types. Resources are primarily data containers. They are reference counted and freed when no longer in use. They are also loaded only once from disk, and further attempts to load the resource will return the same reference (all this in contrast to a [Node], which is not reference counted and can be instanced from disk as many times as desred). Resources can be saved externally on disk or bundled into another object, such as a [Node] or another resource. - </description> - <methods> - <method name="set_path" > - <argument index="0" name="path" type="String"> - </argument> - <description> - Set the path of the resource. This is useful mainly for editors when saving/loading, and shouldn't be changed by anything else. - </description> - </method> - <method name="get_path" qualifiers="const" > - <return type="String"> - </return> - <description> - Return the path of the resource. This is useful mainly for editors when saving/loading, and shouldn't be changed by anything else. - </description> - </method> - <method name="set_name" > - <argument index="0" name="name" type="String"> - </argument> - <description> - Set the name of the resources, any name is ok (it doesn't have to be unique). Name is for descriptive purposes only. - </description> - </method> - <method name="get_name" qualifiers="const" > - <return type="String"> - </return> - <description> - Return the name of the resources, any name is ok (it doesn't have to be unique). Name is for descriptive purposes only. - </description> - </method> - <method name="get_rid" qualifiers="const" > - <return type="RID"> - </return> - <description> - Return the RID of the resource (or an empty RID). Many resources (such as [Texture], [Mesh], etc) are high level abstractions of resources stored in a server, so this function will return the original RID. - </description> - </method> - </methods> - <signals> - <signal name="changed"> - <description> - </description> - </signal> - </signals> - <constants> - </constants> -</class> -<class name="_ResourceLoader" inherits="Object" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="load" > - <return type="Object"> - </return> - <argument index="0" name="path" type="String"> - </argument> - <argument index="1" name="type_hint" type="String" default=""""> - </argument> - <description> - </description> - </method> - <method name="get_recognized_extensions_for_type" > - <return type="StringArray"> - </return> - <argument index="0" name="type" type="String"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="_ResourceSaver" inherits="Object" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="save" > - <return type="int"> - </return> - <argument index="0" name="path" type="String"> - </argument> - <argument index="1" name="resource" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_recognized_extensions" > - <return type="StringArray"> - </return> - <argument index="0" name="type" type="Object"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="RichTextLabel" inherits="Control" category="Nodes/GUI Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="add_text" > - <argument index="0" name="text" type="String"> - </argument> - <description> - </description> - </method> - <method name="add_image" > - <argument index="0" name="image" type="Texture"> - </argument> - <description> - </description> - </method> - <method name="newline" > - <description> - </description> - </method> - <method name="push_font" > - <argument index="0" name="font" type="Object"> - </argument> - <description> - </description> - </method> - <method name="push_color" > - <argument index="0" name="color" type="Color"> - </argument> - <description> - </description> - </method> - <method name="push_align" > - <argument index="0" name="align" type="int"> - </argument> - <description> - </description> - </method> - <method name="push_indent" > - <argument index="0" name="level" type="int"> - </argument> - <description> - </description> - </method> - <method name="push_list" > - <argument index="0" name="type" type="int"> - </argument> - <description> - </description> - </method> - <method name="push_meta" > - <argument index="0" name="data" type="var"> - </argument> - <description> - </description> - </method> - <method name="push_underline" > - <description> - </description> - </method> - <method name="pop" > - <description> - </description> - </method> - <method name="clear" > - <description> - </description> - </method> - <method name="set_meta_underline" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_meta_underlined" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_scroll_active" > - <argument index="0" name="active" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_scroll_active" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_scroll_follow" > - <argument index="0" name="follow" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_scroll_following" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_tab_size" > - <argument index="0" name="spaces" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_tab_size" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - </methods> - <signals> - <signal name="meta_clicked"> - <argument index="0" name="meta" type="Nil"> - </argument> - <description> - </description> - </signal> - </signals> - <constants> - <constant name="ITEM_TEXT" value="1"> - </constant> - <constant name="ITEM_MAIN" value="0"> - </constant> - <constant name="ALIGN_CENTER" value="1"> - </constant> - <constant name="ITEM_UNDERLINE" value="6"> - </constant> - <constant name="ITEM_META" value="10"> - </constant> - <constant name="ITEM_COLOR" value="5"> - </constant> - <constant name="ITEM_FONT" value="4"> - </constant> - <constant name="LIST_DOTS" value="2"> - </constant> - <constant name="ALIGN_LEFT" value="0"> - </constant> - <constant name="LIST_LETTERS" value="1"> - </constant> - <constant name="LIST_NUMBERS" value="0"> - </constant> - <constant name="ITEM_INDENT" value="8"> - </constant> - <constant name="ITEM_NEWLINE" value="3"> - </constant> - <constant name="ALIGN_RIGHT" value="2"> - </constant> - <constant name="ITEM_ALIGN" value="7"> - </constant> - <constant name="ITEM_IMAGE" value="2"> - </constant> - <constant name="ALIGN_FILL" value="3"> - </constant> - <constant name="ITEM_LIST" value="9"> - </constant> - </constants> -</class> -<class name="Room" inherits="Resource" category="Resources"> - <brief_description> - Room data resource. - </brief_description> - <description> - Room contains the data to define the bounds of a scene (using a BSP Tree). It is instanced by a [RoomInstance] node to create rooms. See that class documentation for more information about rooms. - </description> - <methods> - <method name="set_bounds" > - <argument index="0" name="bsp_tree" type="Dictionary"> - </argument> - <description> - Set the bounds of the room as a BSP tree. a BSP Tree is defined a Dictionary: (TODO - see source code on how to create a BSP tree from a dictionary). - </description> - </method> - <method name="get_bounds" qualifiers="const" > - <return type="Dictionary"> - </return> - <description> - Return the bounds of the room as a BSP tree. a BSP Tree is defined a Dictionary: (TODO - see source code on how to create a BSP tree from a dictionary). - </description> - </method> - <method name="set_geometry_hint" > - <argument index="0" name="triangles" type="Vector3Array"> - </argument> - <description> - Set the "geometry" hint of the room. This means, how the room actually looks (an array of [Vector3]s, forming triangles). - </description> - </method> - <method name="get_geometry_hint" qualifiers="const" > - <return type="Vector3Array"> - </return> - <description> - Return the "geometry" hint of the room. This means, how the room actually looks (an array of [Vector3]s, forming triangles). - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="RoomInstance" inherits="VisualInstance" category="Nodes/3D/3D Visual Nodes"> - <brief_description> - Node that instances a Room. - </brief_description> - <description> - RoomInstance is a [Node] that instances a [Room] resource and places it on the world. Rooms are used for defining the areas taken up by [html i]interiors[html /i]. An [html i]interior[html /i] is any closed space that has an entrance/exit (or not) to the outside world, for example the inside of a house, a room in a house, a cave.[html br/]So why is this used? Rooms and Portals ([Portal]) are a common visualization optimization technique, it is used to make interiors invisible (not rendered) when the camera is at the exterior (such as an open field), and also the exterior invisible when inside an interior (such as a house). It is also used to make interior rooms invisible from other interior rooms. [html div align="center"][html img src="images/portals_example.png"/][html /div] - </description> - <methods> - <method name="set_room" > - <argument index="0" name="room" type="Object"> - </argument> - <description> - Set the [Room] resource, containing the room bounds. - </description> - </method> - <method name="get_room" qualifiers="const" > - <return type="Object"> - </return> - <description> - Return the [Room] resource, containing the room bounds. - </description> - </method> - <method name="compute_room_from_subtree" > - <description> - This helper function computes a [Room] from the shapes of all the children [VisualInstance] nodes, and sets it to the node. - </description> - </method> - <method name="set_simulate_acoustics" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_simulating_acoustics" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="SSAOFX" inherits="ScenarioFX" category="Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="Sample" inherits="Resource" category="Resources"> - <brief_description> - Audio Sample (sound) class. - </brief_description> - <description> - Sample provides an audio sample class, containing audio data, together with some information for playback, such as format, mix rate and loop. It is used by sound playback routines. - </description> - <methods> - <method name="create" > - <argument index="0" name="format" type="int"> - </argument> - <argument index="1" name="stereo" type="bool"> - </argument> - <argument index="2" name="length" type="int"> - </argument> - <description> - Create new data for the sample, with format "format" (see FORMAT_* enum), stereo hint, and length in frames (not samples or bytes!) "frame". Calling create overrides previous existing data if it exists. Stereo samples are interleaved pairs of left and right (in that order) points - </description> - </method> - <method name="get_format" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the sample format (see FORMAT_* enum). - </description> - </method> - <method name="is_stereo" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return true if the sample was created stereo. - </description> - </method> - <method name="get_length" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the sample length in frames. - </description> - </method> - <method name="set_data" > - <argument index="0" name="data" type="RawArray"> - </argument> - <description> - Set sample data. Data must be little endian, no matter the host platform, and exactly as long to fit all frames. Example, if data is Stereo, 16 bits, 256 frames, it will be 1024 bytes long. - </description> - </method> - <method name="get_data" qualifiers="const" > - <return type="RawArray"> - </return> - <description> - Return sample data. Data will be endian, no matter with the host platform, and exactly as long to fit all frames. Example, if data is Stereo, 16 bits, 256 frames, it will be 1024 bytes long. - </description> - </method> - <method name="set_mix_rate" > - <argument index="0" name="hz" type="int"> - </argument> - <description> - Set the mix rate for the sample (expected playback frequency). - </description> - </method> - <method name="get_mix_rate" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the mix rate for the sample (expected playback frequency). - </description> - </method> - <method name="set_loop_format" > - <argument index="0" name="format" type="int"> - </argument> - <description> - Set the loop format, see LOOP_* enum - </description> - </method> - <method name="get_loop_format" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the loop format, see LOOP_* enum. - </description> - </method> - <method name="set_loop_begin" > - <argument index="0" name="pos" type="int"> - </argument> - <description> - Set the loop begin position, it must be a valid frame and less than the loop end position. - </description> - </method> - <method name="get_loop_begin" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the loop begin position. - </description> - </method> - <method name="set_loop_end" > - <argument index="0" name="pos" type="int"> - </argument> - <description> - Set the loop end position, it must be a valid frame and greater than the loop begin position. - </description> - </method> - <method name="get_loop_end" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the loop begin position. - </description> - </method> - </methods> - <constants> - <constant name="FORMAT_IMA_ADPCM" value="2"> - Ima-ADPCM Audio. - </constant> - <constant name="LOOP_FORWARD" value="1"> - Forward looping (when playback reaches loop end, goes back to loop begin) - </constant> - <constant name="FORMAT_PCM16" value="1"> - 16-Bits signed little endian PCM audio. - </constant> - <constant name="FORMAT_PCM8" value="0"> - 8-Bits signed little endian PCM audio. - </constant> - <constant name="LOOP_NONE" value="0"> - No loop enabled. - </constant> - <constant name="LOOP_PING_PONG" value="2"> - Ping-Pong looping (when playback reaches loop end, plays backward untilloop begin). Not available in all platforms. - </constant> - </constants> -</class> -<class name="SampleLibrary" inherits="Resource" category="Resources"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="add_sample" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="sample" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_sample" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <description> - </description> - </method> - <method name="has_sample" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <description> - </description> - </method> - <method name="remove_sample" > - <argument index="0" name="name" type="String"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="SamplePlayer" inherits="Node" category="Nodes/Audio Nodes"> - <brief_description> - Sample Player node. - </brief_description> - <description> - SamplePlayer is a [Node] meant for simple sample playback. A library of samples is loaded and played back "as is", without positioning or anything. - </description> - <methods> - <method name="set_sample_library" > - <argument index="0" name="library" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_sample_library" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="set_voice_count" > - <argument index="0" name="max_voices" type="int"> - </argument> - <description> - Set the amount of simultaneous voices that will be used for playback. - </description> - </method> - <method name="get_voice_count" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the amount of simultaneous voices that will be used for playback. - </description> - </method> - <method name="play" > - <return type="int"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="unique" type="bool" default="false"> - </argument> - <description> - Play back sample, given it's identifier "name". if "unique" is true, all othere previous samples will be stopped. The voice allocated for playback will be returned. - </description> - </method> - <method name="stop" > - <argument index="0" name="voice" type="int"> - </argument> - <description> - Stop a voice "voice". (see [method play]). - </description> - </method> - <method name="stop_all" > - <description> - </description> - </method> - <method name="set_mix_rate" > - <argument index="0" name="voice" type="int"> - </argument> - <argument index="1" name="hz" type="int"> - </argument> - <description> - Change the mix rate of a voice "voice" to given "hz". - </description> - </method> - <method name="set_pitch_scale" > - <argument index="0" name="voice" type="int"> - </argument> - <argument index="1" name="ratio" type="real"> - </argument> - <description> - Scale the pitch (mix rate) of a voice by a ratio value "ratio". A ratio of 1.0 means the voice is unscaled. - </description> - </method> - <method name="set_volume" > - <argument index="0" name="voice" type="int"> - </argument> - <argument index="1" name="nrg" type="real"> - </argument> - <description> - Set the volume of a voice, 0db is maximum volume (every about -6db, volume is reduced in half). "db" does in fact go from zero to negative. - </description> - </method> - <method name="set_volume_db" > - <argument index="0" name="voice" type="int"> - </argument> - <argument index="1" name="nrg" type="real"> - </argument> - <description> - </description> - </method> - <method name="set_pan" > - <argument index="0" name="voice" type="int"> - </argument> - <argument index="1" name="pan" type="real"> - </argument> - <argument index="2" name="depth" type="real" default="0"> - </argument> - <argument index="3" name="height" type="real" default="0"> - </argument> - <description> - Set the panning of a voice. Panning goes from -1 (left) to +1 (right). Optionally, if the hardware supports 3D sound, also set depth and height (also in range -1 to +1). - </description> - </method> - <method name="set_filter" > - <argument index="0" name="voice" type="int"> - </argument> - <argument index="1" name="type" type="int"> - </argument> - <argument index="2" name="cutoff_hz" type="real"> - </argument> - <argument index="3" name="resonance" type="real"> - </argument> - <argument index="4" name="gain" type="real" default="0"> - </argument> - <description> - Set and enable a filter of a voice, with type "type" (see FILTER_* enum), cutoff (0 to 22khz) frequency and resonance (0+). - </description> - </method> - <method name="set_chorus" > - <argument index="0" name="voice" type="int"> - </argument> - <argument index="1" name="send" type="real"> - </argument> - <description> - Set the chorus send level of a voice (0 to 1). For setting chorus parameters, see [AudioServer]. - </description> - </method> - <method name="set_reverb" > - <argument index="0" name="voice" type="int"> - </argument> - <argument index="1" name="room_type" type="int"> - </argument> - <argument index="2" name="send" type="real"> - </argument> - <description> - Set the reverb send level and type of a voice (0 to 1). (see REVERB_* enum for type). - </description> - </method> - <method name="get_mix_rate" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="voice" type="int"> - </argument> - <description> - Return the current mix rate for a given voice. - </description> - </method> - <method name="get_pitch_scale" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="int"> - </argument> - <description> - Return the current pitch scale for a given voice. - </description> - </method> - <method name="get_volume" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="int"> - </argument> - <description> - Return the current volume (in db) for a given voice. 0db is maximum volume (every about -6db, volume is reduced in half). "db" does in fact go from zero to negative. - </description> - </method> - <method name="get_volume_db" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_pan" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="int"> - </argument> - <description> - Return the current panning for a given voice. Panning goes from -1 (left) to +1 (right). - </description> - </method> - <method name="get_pan_depth" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="int"> - </argument> - <description> - Return the current pan depth for a given voice (not used unless the hardware supports 3D sound) - </description> - </method> - <method name="get_pan_height" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="int"> - </argument> - <description> - Return the current pan height for a given voice (not used unless the hardware supports 3D sound) - </description> - </method> - <method name="get_filter_type" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="voice" type="int"> - </argument> - <description> - Return the current filter type in use (see FILTER_* enum) for a given voice. - </description> - </method> - <method name="get_filter_cutoff" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="int"> - </argument> - <description> - Return the current filter cutoff for a given voice. Cutoff goes from 0 to 22khz. - </description> - </method> - <method name="get_filter_resonance" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="int"> - </argument> - <description> - Return the current filter resonance for a given voice. Resonance goes from 0 up. - </description> - </method> - <method name="get_filter_gain" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_chorus" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="int"> - </argument> - <description> - Return the current chorus send level for a given voice. (0 to 1). - </description> - </method> - <method name="get_reverb_room" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="int"> - </argument> - <description> - Return the current reverb room type for a given voice (see REVERB_* enum). - </description> - </method> - <method name="get_reverb" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="voice" type="int"> - </argument> - <description> - Return the current reverb send level for a given voice. (0 to 1). - </description> - </method> - <method name="set_default_pitch_scale" > - <argument index="0" name="ratio" type="real"> - </argument> - <description> - </description> - </method> - <method name="set_default_volume" > - <argument index="0" name="nrg" type="real"> - </argument> - <description> - </description> - </method> - <method name="set_default_volume_db" > - <argument index="0" name="db" type="real"> - </argument> - <description> - </description> - </method> - <method name="set_default_pan" > - <argument index="0" name="pan" type="real"> - </argument> - <argument index="1" name="depth" type="real" default="0"> - </argument> - <argument index="2" name="height" type="real" default="0"> - </argument> - <description> - </description> - </method> - <method name="set_default_filter" > - <argument index="0" name="type" type="int"> - </argument> - <argument index="1" name="cutoff_hz" type="real"> - </argument> - <argument index="2" name="resonance" type="real"> - </argument> - <argument index="3" name="gain" type="real" default="0"> - </argument> - <description> - </description> - </method> - <method name="set_default_chorus" > - <argument index="0" name="send" type="real"> - </argument> - <description> - </description> - </method> - <method name="set_default_reverb" > - <argument index="0" name="room_type" type="int"> - </argument> - <argument index="1" name="send" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_default_pitch_scale" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="get_default_volume" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="get_default_volume_db" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="get_default_pan" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="get_default_pan_depth" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="get_default_pan_height" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="get_default_filter_type" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="get_default_filter_cutoff" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="get_default_filter_resonance" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="get_default_filter_gain" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="get_default_chorus" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="get_default_reverb_room" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="get_default_reverb" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - </methods> - <constants> - <constant name="FILTER_HIPASS" value="3"> - HighPass filter is used for voice. - </constant> - <constant name="FILTER_NONE" value="0"> - Filter is disabled for voice. - </constant> - <constant name="REVERB_HALL" value="3"> - Huge reverb room (cathedral, warehouse). - </constant> - <constant name="REVERB_MEDIUM" value="1"> - Medium reverb room (street) - </constant> - <constant name="REVERB_SMALL" value="0"> - Small reverb room (house room). - </constant> - <constant name="FILTER_HIGH_SHELF" value="8"> - </constant> - <constant name="FILTER_PEAK" value="5"> - </constant> - <constant name="FILTER_LOWPASS" value="1"> - Lowpass filter is used for voice. - </constant> - <constant name="REVERB_LARGE" value="2"> - Large reverb room (Theather) - </constant> - <constant name="FILTER_LOW_SHELF" value="7"> - </constant> - <constant name="FILTER_BANDLIMIT" value="6"> - Band-Limit filter is used for voice, in this case resonance is the highpass cutoff. - </constant> - <constant name="FILTER_NOTCH" value="4"> - Notch filter is used for voice. - </constant> - <constant name="FILTER_BANDPASS" value="2"> - Bandpass filter is used for voice. - </constant> - </constants> -</class> -<class name="ScenarioFX" inherits="Node" category="Nodes"> - <brief_description> - </brief_description> - <description> - Deprecated, will go away. - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="SceneMainLoop" inherits="MainLoop" category="Main Loop"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_editor_hint" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_editor_hint" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_pause" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_paused" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="quit" > - <description> - </description> - </method> - </methods> - <signals> - <signal name="screen_resized"> - <description> - </description> - </signal> - <signal name="node_removed"> - <argument index="0" name="node" type="Object"> - </argument> - <description> - </description> - </signal> - <signal name="tree_changed"> - <description> - </description> - </signal> - </signals> - <constants> - </constants> -</class> -<class name="Script" inherits="Resource" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="ScrollBar" inherits="Range" category="Core"> - <brief_description> - Base class for scroll bars. - </brief_description> - <description> - Scrollbars are a [Range] based [Control], that display a draggable area (the size of the page). Horizontal ([HScrollBar]) and Vertical ([VScrollBar]) versions are available. - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="Separator" inherits="Control" category="Nodes/GUI Nodes"> - <brief_description> - Base class for separators. - </brief_description> - <description> - Separator is a [Control] used for sepataring other controls. It's purely a visual decoration. Horizontal ([HSeparator]) and Vertical ([VSeparator]) versions are available. - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="Shader" inherits="Resource" category="Resources"> - <brief_description> - To be changed, ignore. - </brief_description> - <description> - To be changed, ignore. - </description> - <methods> - <method name="set_mode" > - <argument index="0" name="mode" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_mode" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_vertex_code" > - <argument index="0" name="code" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_vertex_code" qualifiers="const" > - <return type="String"> - </return> - <description> - </description> - </method> - <method name="set_fragment_code" > - <argument index="0" name="code" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_fragment_code" qualifiers="const" > - <return type="String"> - </return> - <description> - </description> - </method> - <method name="set_use_world_transform" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_using_world_transform" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_param" > - <argument index="0" name="param" type="String"> - </argument> - <argument index="1" name="value" type="var"> - </argument> - <description> - </description> - </method> - <method name="get_param" qualifiers="const" > - <argument index="0" name="param" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_param_list" qualifiers="const" > - <return type="StringArray"> - </return> - <description> - </description> - </method> - </methods> - <constants> - <constant name="MODE_MATERIAL" value="0"> - </constant> - <constant name="MODE_POST_PROCESS" value="1"> - </constant> - </constants> -</class> -<class name="ShaderMaterial" inherits="Material" category="Resources"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_shader" > - <argument index="0" name="shader" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_shader" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="Shape" inherits="Resource" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="Skeleton" inherits="Spatial" category="Nodes/3D"> - <brief_description> - Skeleton for characters and animated objects. - </brief_description> - <description> - Skeleton provides a hierachial interface for managing bones, including pose, rest and animation (see [Animation]). Skeleton will support rag doll dynamics in the future. - </description> - <methods> - <method name="add_bone" > - <argument index="0" name="name" type="String"> - </argument> - <description> - Add a bone, with name "name". [method get_bone_count] will become the bone index. - </description> - </method> - <method name="find_bone" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <description> - Return the bone index that matches "name" as its name. - </description> - </method> - <method name="get_bone_name" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="bone_idx" type="int"> - </argument> - <description> - Return the name of the bone at index "index" - </description> - </method> - <method name="get_bone_parent" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="bone_idx" type="int"> - </argument> - <description> - Return the bone index which is the parent of the bone at "bone_idx". If -1, then bone has no parent. Note that the parent bone returned will always be less than "bone_idx". - </description> - </method> - <method name="set_bone_parent" > - <argument index="0" name="bone_idx" type="int"> - </argument> - <argument index="1" name="parent_idx" type="int"> - </argument> - <description> - Set the bone index "parent_idx" as the parent of the bone at "bone_idx". If -1, then bone has no parent. Note: "parent_idx" must be less than "bone_idx". - </description> - </method> - <method name="get_bone_count" qualifiers="const" > - <return type="int"> - </return> - <description> - Return the amount of bones in the skeleton. - </description> - </method> - <method name="get_bone_rest" qualifiers="const" > - <return type="Transform"> - </return> - <argument index="0" name="bone_idx" type="int"> - </argument> - <description> - Return the rest transform for a bone "bone_idx". - </description> - </method> - <method name="set_bone_rest" > - <argument index="0" name="bone_idx" type="int"> - </argument> - <argument index="1" name="rest" type="Transform"> - </argument> - <description> - Set the rest transform for bone "bone_idx" - </description> - </method> - <method name="bind_child_node_to_bone" > - <argument index="0" name="bone_idx" type="int"> - </argument> - <argument index="1" name="node" type="Object"> - </argument> - <description> - Deprecated soon - </description> - </method> - <method name="unbind_child_node_from_bone" > - <argument index="0" name="bone_idx" type="int"> - </argument> - <argument index="1" name="node" type="Object"> - </argument> - <description> - Deprecated soon - </description> - </method> - <method name="get_bound_child_nodes_to_bone" qualifiers="const" > - <return type="Array"> - </return> - <argument index="0" name="bone_idx" type="int"> - </argument> - <description> - Deprecated Soon - </description> - </method> - <method name="clear_bones" > - <description> - Clear all the bones in this skeleton. - </description> - </method> - <method name="get_bone_pose" qualifiers="const" > - <return type="Transform"> - </return> - <argument index="0" name="bone_idx" type="int"> - </argument> - <description> - Return the pose transform for bone "bone_idx". - </description> - </method> - <method name="set_bone_pose" > - <argument index="0" name="bone_idx" type="int"> - </argument> - <argument index="1" name="pose" type="Transform"> - </argument> - <description> - Return the pose transform for bone "bone_idx". - </description> - </method> - <method name="get_bone_custom_pose" qualifiers="const" > - <return type="Transform"> - </return> - <argument index="0" name="bone_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_bone_custom_pose" > - <argument index="0" name="bone_idx" type="int"> - </argument> - <argument index="1" name="custom_pose" type="Transform"> - </argument> - <description> - </description> - </method> - <method name="get_bone_transform" qualifiers="const" > - <return type="Transform"> - </return> - <argument index="0" name="bone_idx" type="int"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - <constant name="NOTIFICATION_UPDATE_SKELETON" value="50"> - </constant> - </constants> -</class> -<class name="SkyBoxFX" inherits="ScenarioFX" category="Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="Slider" inherits="Range" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="SoundRoomParams" inherits="Node" category="Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_param" > - <argument index="0" name="param" type="int"> - </argument> - <argument index="1" name="value" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_param" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="param" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_reverb_mode" > - <argument index="0" name="reverb_mode" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_reverb_mode" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_force_params_to_all_sources" > - <argument index="0" name="enabled" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_forcing_params_to_all_sources" > - <return type="bool"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="Spatial" inherits="Node" category="Nodes/3D"> - <brief_description> - Base class for all 3D nodes. - </brief_description> - <description> - Spatial is the base for every type of 3D [Node]. It contains a 3D [Transform] which can be set or get as local or global. If a Spatial [Node] has Spatial children, their transforms will be relative to the parent. - </description> - <methods> - <method name="set_transform" > - <argument index="0" name="local" type="Transform"> - </argument> - <description> - Set the transform locally, relative to the parent spatial node. - </description> - </method> - <method name="get_transform" qualifiers="const" > - <return type="Transform"> - </return> - <description> - Return the local transform, relative to the bone parent. - </description> - </method> - <method name="set_global_transform" > - <argument index="0" name="global" type="Transform"> - </argument> - <description> - Set the transform globally, relative to worldspace. - </description> - </method> - <method name="get_global_transform" qualifiers="const" > - <return type="Transform"> - </return> - <description> - Return the gloal transform, relative to worldspace. - </description> - </method> - <method name="get_parent_spatial" qualifiers="const" > - <return type="Object"> - </return> - <description> - Return the parent [Spatial], or an empty [Object] if no parent exists or parent is not of type [Spatial. - </description> - </method> - <method name="update_gizmo" > - <description> - </description> - </method> - </methods> - <constants> - <constant name="NOTIFICATION_SCENARIO_CHANGED" value="41"> - Spatial nodes receive this notification when the viewport next to it in ascending hierarchy changed the [Scenario]. - </constant> - <constant name="NOTIFICATION_TRANSFORM_CHANGED" value="40"> - Spatial nodes receive this notifacation with their global transform changes. This means that either the current or a parent node changed it's transform. - </constant> - </constants> -</class> -<class name="SpatialPlayer" inherits="Spatial" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="SpatialSamplePlayer" inherits="SpatialPlayer" category="Nodes/3D"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_sample_library" > - <argument index="0" name="library" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_sample_library" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="set_polyphony" > - <argument index="0" name="voices" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_polyphony" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="play" > - <return type="int"> - </return> - <argument index="0" name="sample" type="String"> - </argument> - <argument index="1" name="voice" type="int" default="-2"> - </argument> - <description> - </description> - </method> - <method name="voice_set_pitch_scale" > - <argument index="0" name="voice" type="int"> - </argument> - <argument index="1" name="ratio" type="real"> - </argument> - <description> - </description> - </method> - <method name="voice_set_volume_scale_db" > - <argument index="0" name="voice" type="int"> - </argument> - <argument index="1" name="db" type="real"> - </argument> - <description> - </description> - </method> - <method name="is_voice_active" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="voice" type="int"> - </argument> - <description> - </description> - </method> - <method name="stop_voice" > - <argument index="0" name="voice" type="int"> - </argument> - <description> - </description> - </method> - <method name="stop_all" > - <description> - </description> - </method> - </methods> - <constants> - <constant name="NEXT_VOICE" value="-2"> - </constant> - <constant name="INVALID_VOICE" value="-1"> - </constant> - </constants> -</class> -<class name="SpatialSoundServer" inherits="Object" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="SpatialSoundServerSW" inherits="SpatialSoundServer" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="SpatialStreamPlayer" inherits="SpatialPlayer" category="Nodes/3D"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_stream" > - <argument index="0" name="stream" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_stream" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="play" > - <description> - </description> - </method> - <method name="stop" > - <description> - </description> - </method> - <method name="is_playing" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_loop" > - <argument index="0" name="enabled" type="bool"> - </argument> - <description> - </description> - </method> - <method name="has_loop" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="get_stream_name" qualifiers="const" > - <return type="String"> - </return> - <description> - </description> - </method> - <method name="get_loop_count" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="get_pos" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="seek_pos" > - <argument index="0" name="time" type="real"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="SphereShape" inherits="Shape" category="Resources"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_radius" > - <argument index="0" name="radius" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_radius" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="SpinBox" inherits="Range" category="Nodes/GUI Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_suffix" > - <argument index="0" name="suffix" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_suffix" qualifiers="const" > - <return type="String"> - </return> - <description> - </description> - </method> - <method name="set_prefix" > - <argument index="0" name="prefix" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_prefix" qualifiers="const" > - <return type="String"> - </return> - <description> - </description> - </method> - <method name="set_editable" > - <argument index="0" name="editable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_editable" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="SpotLight" inherits="Light" category="Nodes/3D/3D Visual Nodes/3D Light Nodes"> - <brief_description> - Spotlight Light, such as a reflector spotlight or a latern. - </brief_description> - <description> - A SpotLight light is a type of [Light] node that emits lights in a specific direction, in the shape of a cone. The light is attenuated through the distance and this attenuation can be configured by changing the energy, radius and attenuation parameters of [Light]. TODO: Image of a spotlight. - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="Sprite" inherits="Node2D" category="Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_texture" > - <argument index="0" name="texture" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_texture" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="set_centered" > - <argument index="0" name="centered" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_centered" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_flip_h" > - <argument index="0" name="flip_h" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_flipped_h" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_flip_v" > - <argument index="0" name="flip_v" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_flipped_v" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_frame" > - <argument index="0" name="frame" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_frame" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_vframes" > - <argument index="0" name="vframes" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_vframes" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_hframes" > - <argument index="0" name="hframes" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_hframes" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_modulate" > - <argument index="0" name="modulate" type="Color"> - </argument> - <description> - </description> - </method> - <method name="get_modulate" qualifiers="const" > - <return type="Color"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="SquirrelScript" inherits="Script" category="Resources"> - <brief_description> - Squirrel script language support. - </brief_description> - <description> - [html a href="http://squirrel-lang.org/"]Squirrel Language[html /a] support for the engine. Allows to load a [Script] from a .sq or .nut source or compiled file, or bundled it into scenes. - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="StaticBody" inherits="PhysicsBody" category="Nodes/3D"> - <brief_description> - PhysicsBody for static collision objects. - </brief_description> - <description> - StaticBody implements a static collision [Node], by utilizing a rigid body in the [PhysicsServer]. Static bodies are used for static collision. For more information on physics body nodes, see [PhysicsBody]. - </description> - <methods> - <method name="set_simulated_motion" > - <argument index="0" name="enabled" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_simulating_motion" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="simulate_motion" > - <argument index="0" name="new_transform" type="Transform"> - </argument> - <description> - </description> - </method> - <method name="create_shapes_from_child_meshes" > - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="StreamPeer" inherits="Object" category="Networking"> - <brief_description> - Abstraction and base class for stream-based protocols. - </brief_description> - <description> - StreamPeer is an abstration and base class for stream-based protocols (such as TCP or Unix Sockets). It provides an API for sending and receiving data through streams as raw data or strings. - </description> - <methods> - <method name="put_data" > - <return type="int"> - </return> - <argument index="0" name="data" type="RawArray"> - </argument> - <description> - Send a chunk of data through the connection, blocking if necesary until the data is done sending. This function returns an [Error] code. - </description> - </method> - <method name="put_partial_data" > - <return type="Array"> - </return> - <argument index="0" name="data" type="RawArray"> - </argument> - <description> - Send a chunk of data through the connection, if all the data could not be sent at once, only part of it will. This function returns two values, an [Error] code and an integer, describing how much data was actually sent. - </description> - </method> - <method name="get_data" > - <return type="Array"> - </return> - <argument index="0" name="bytes" type="int"> - </argument> - <description> - Return a chunk data with the received bytes. The amount of bytes to be received can be requested in the "bytes" argument. If not enough bytes are available, the function will block until the desired amount is received. This function returns two values, an [Error] code and a data array. - </description> - </method> - <method name="get_partial_data" > - <return type="Array"> - </return> - <argument index="0" name="bytes" type="int"> - </argument> - <description> - Return a chunk data with the received bytes. The amount of bytes to be received can be requested in the "bytes" argument. If not enough bytes are available, the function will return how many were actually received. This function returns two values, an [Error] code, and a data array. - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="StreamPeerTCP" inherits="StreamPeer" category="Networking/Networking"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="connect" > - <return type="int"> - </return> - <argument index="0" name="host" type="String"> - </argument> - <argument index="1" name="ip" type="int"> - </argument> - <description> - </description> - </method> - <method name="is_connected" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="get_connected_host" qualifiers="const" > - <return type="String"> - </return> - <description> - </description> - </method> - <method name="get_connected_port" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="disconnect" > - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="StreamPlayer" inherits="Node" category="Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_stream" > - <argument index="0" name="stream" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_stream" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="play" > - <description> - </description> - </method> - <method name="stop" > - <description> - </description> - </method> - <method name="is_playing" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_loop" > - <argument index="0" name="enabled" type="bool"> - </argument> - <description> - </description> - </method> - <method name="has_loop" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_volume" > - <argument index="0" name="volume" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_volume" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="set_volume_db" > - <argument index="0" name="db" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_volume_db" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="get_stream_name" qualifiers="const" > - <return type="String"> - </return> - <description> - </description> - </method> - <method name="get_loop_count" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="get_pos" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="seek_pos" > - <argument index="0" name="time" type="real"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="StyleBox" inherits="Resource" category="Core"> - <brief_description> - Base class for dawing stylized boxes for the UI. - </brief_description> - <description> - StyleBox is [Resource] that provides an abstract base class for dawing stylized boxes for the UI. StyleBoxes are used for dawing the styles of buttons, line edit backgrounds, tree backgrounds, etc. and also for testing a transparency mask for pointer signals. If mask test fails on a StyleBox assigned as mask to a control, clicks and motion signals will go through it to the one below. - </description> - <methods> - <method name="test_mask" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="point" type="Vector2"> - </argument> - <argument index="1" name="rect" type="Rect2"> - </argument> - <description> - Test a position in a rectangle, return wether it pases the mask test. - </description> - </method> - <method name="set_default_margin" > - <argument index="0" name="margin" type="int"> - </argument> - <argument index="1" name="offset" type="real"> - </argument> - <description> - Set the default offset "offset" of the margin "margin" (see MARGIN_* enum) for a StyleBox, Controls that draw styleboxes with context inside need to know the margin, so the border of the stylebox is not occluded. - </description> - </method> - <method name="get_default_margin" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="margin" type="int"> - </argument> - <description> - Return the default offset of the margin "margin" (see MARGIN_* enum) of a StyleBox, Controls that draw styleboxes with context inside need to know the margin, so the border of the stylebox is not occluded. - </description> - </method> - <method name="get_margin" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="margin" type="int"> - </argument> - <description> - Return the offset of margin "margin" (see MARGIN_* enum). - </description> - </method> - <method name="get_minimum_size" qualifiers="const" > - <return type="Vector2"> - </return> - <description> - Return the minimum size that this stylebox can be shrunk to. - </description> - </method> - <method name="get_offset" qualifiers="const" > - <return type="Vector2"> - </return> - <description> - Return the "offset" of a stylebox, this is a helper function, like writing Point2( style.get_margin(MARGIN_LEFT), style.get_margin(MARGIN_TOP) ) - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="StyleBoxEmpty" inherits="StyleBox" category="Resources"> - <brief_description> - Empty stylebox (does not display anything). - </brief_description> - <description> - Empty stylebox (really does not display anything). - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="StyleBoxFlat" inherits="StyleBox" category="Resources"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_bg_color" > - <argument index="0" name="color" type="Color"> - </argument> - <description> - </description> - </method> - <method name="get_bg_color" qualifiers="const" > - <return type="Color"> - </return> - <description> - </description> - </method> - <method name="set_light_color" > - <argument index="0" name="color" type="Color"> - </argument> - <description> - </description> - </method> - <method name="get_light_color" qualifiers="const" > - <return type="Color"> - </return> - <description> - </description> - </method> - <method name="set_dark_color" > - <argument index="0" name="color" type="Color"> - </argument> - <description> - </description> - </method> - <method name="get_dark_color" qualifiers="const" > - <return type="Color"> - </return> - <description> - </description> - </method> - <method name="set_border_size" > - <argument index="0" name="size" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_border_size" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_border_blend" > - <argument index="0" name="blend" type="bool"> - </argument> - <description> - </description> - </method> - <method name="get_border_blend" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_draw_center" > - <argument index="0" name="size" type="bool"> - </argument> - <description> - </description> - </method> - <method name="get_draw_center" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="StyleBoxImageMask" inherits="StyleBox" category="Resources"> - <brief_description> - Image mask based StyleBox, for mask test. - </brief_description> - <description> - This StyleBox is similar to [StyleBoxTexture], but only meant to be used for mask testing. It takes an image and applies stretch rules to determine if the poit clicked is masked or not. - </description> - <methods> - <method name="set_image" > - <argument index="0" name="image" type="Image"> - </argument> - <description> - Set the image used for mask testing. Pixels (converted to grey) that have a value, less than 0.5 will fail the test. - </description> - </method> - <method name="get_image" qualifiers="const" > - <return type="Image"> - </return> - <description> - Return the image used for mask testing. (see [method set_imag]). - </description> - </method> - <method name="set_expand" > - <argument index="0" name="expand" type="bool"> - </argument> - <description> - Set the expand property (default). When expanding, the image will use the same rules as [StyleBoxTexture] for expand. If not expanding, the image will always be tested at its original size. - </description> - </method> - <method name="get_expand" qualifiers="const" > - <return type="bool"> - </return> - <description> - Return wether the expand property is set(default). When expanding, the image will use the same rules as [StyleBoxTexture] for expand. If not expanding, the image will always be tested at its original size. - </description> - </method> - <method name="set_expand_margin_size" > - <argument index="0" name="margin" type="int"> - </argument> - <argument index="1" name="size" type="real"> - </argument> - <description> - Set an expand margin size (from enum MARGIN_*). Parts of the image below the size of the margin (and in the direction of the margin) will not expand. - </description> - </method> - <method name="get_expand_margin_size" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="arg0" type="int"> - </argument> - <description> - Return the expand margin size (from enum MARGIN_*). Parts of the image below the size of the margin (and in the direction of the margin) will not expand. - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="StyleBoxTexture" inherits="StyleBox" category="Resources"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_texture" > - <argument index="0" name="texture" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_texture" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="set_margin_size" > - <argument index="0" name="margin" type="int"> - </argument> - <argument index="1" name="size" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_margin_size" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="arg0" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_expand_margin_size" > - <argument index="0" name="margin" type="int"> - </argument> - <argument index="1" name="size" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_expand_margin_size" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="arg0" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_draw_center" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="get_draw_center" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="get_center_size" qualifiers="const" > - <return type="Vector2"> - </return> - <description> - </description> - </method> - <method name="draw" qualifiers="const" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="Rect2"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="SurfaceTool" inherits="Reference" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="begin" > - <argument index="0" name="primitive" type="int"> - </argument> - <description> - </description> - </method> - <method name="add_vertex" > - <argument index="0" name="vertex" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="add_color" > - <argument index="0" name="color" type="Color"> - </argument> - <description> - </description> - </method> - <method name="add_normal" > - <argument index="0" name="normal" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="add_tangent" > - <argument index="0" name="tangent" type="Plane"> - </argument> - <description> - </description> - </method> - <method name="add_uv" > - <argument index="0" name="uv" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="add_uv2" > - <argument index="0" name="uv2" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="add_bones" > - <argument index="0" name="bones" type="IntArray"> - </argument> - <description> - </description> - </method> - <method name="add_weights" > - <argument index="0" name="weights" type="RealArray"> - </argument> - <description> - </description> - </method> - <method name="set_material" > - <argument index="0" name="material" type="Object"> - </argument> - <description> - </description> - </method> - <method name="index" > - <description> - </description> - </method> - <method name="deindex" > - <description> - </description> - </method> - <method name="generate_flat_normals" > - <description> - </description> - </method> - <method name="generate_smooth_normals" > - <description> - </description> - </method> - <method name="generate_tangents" > - <description> - </description> - </method> - <method name="commit" > - <return type="Object"> - </return> - <argument index="0" name="existing" type="Object" default="Object()"> - </argument> - <description> - </description> - </method> - <method name="clear" > - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="TCP_Server" inherits="Object" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="listen" > - <return type="int"> - </return> - <argument index="0" name="port" type="int"> - </argument> - <argument index="1" name="accepted_hosts" type="StringArray" default="StringArray()"> - </argument> - <description> - </description> - </method> - <method name="is_connection_available" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="take_connection" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="stop" > - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="TabContainer" inherits="Control" category="Nodes/GUI Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="get_tab_count" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_current_tab" > - <argument index="0" name="tab_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_current_tab" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_tab_align" > - <argument index="0" name="align" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_tab_align" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_tabs_visible" > - <argument index="0" name="visible" type="bool"> - </argument> - <description> - </description> - </method> - <method name="are_tabs_visible" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_tab_title" > - <argument index="0" name="tab_idx" type="int"> - </argument> - <argument index="1" name="title" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_tab_title" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="tab_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_tab_icon" > - <argument index="0" name="tab_idx" type="int"> - </argument> - <argument index="1" name="icon" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_tab_icon" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="tab_idx" type="int"> - </argument> - <description> - </description> - </method> - </methods> - <signals> - <signal name="tab_changed"> - <argument index="0" name="tab" type="int"> - </argument> - <description> - </description> - </signal> - </signals> - <constants> - </constants> -</class> -<class name="TestCube" inherits="VisualInstance" category="Nodes/3D/3D Visual Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="TextEdit" inherits="Control" category="Nodes/GUI Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_text" > - <argument index="0" name="text" type="String"> - </argument> - <description> - </description> - </method> - <method name="insert_text_at_cursor" > - <argument index="0" name="text" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_line_count" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="get_text" > - <return type="String"> - </return> - <description> - </description> - </method> - <method name="get_line" > - <return type="String"> - </return> - <argument index="0" name="arg0" type="int"> - </argument> - <description> - </description> - </method> - <method name="cursor_set_column" > - <argument index="0" name="column" type="int"> - </argument> - <description> - </description> - </method> - <method name="cursor_set_line" > - <argument index="0" name="line" type="int"> - </argument> - <description> - </description> - </method> - <method name="cursor_get_column" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="cursor_get_line" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_readonly" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="set_wrap" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="set_max_chars" > - <argument index="0" name="amount" type="int"> - </argument> - <description> - </description> - </method> - <method name="cut" > - <description> - </description> - </method> - <method name="copy" > - <description> - </description> - </method> - <method name="paste" > - <description> - </description> - </method> - <method name="select_all" > - <description> - </description> - </method> - <method name="select" > - <argument index="0" name="from_line" type="int"> - </argument> - <argument index="1" name="from_column" type="int"> - </argument> - <argument index="2" name="to_line" type="int"> - </argument> - <argument index="3" name="to_column" type="int"> - </argument> - <description> - </description> - </method> - <method name="is_selection_active" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="get_selection_from_line" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="get_selection_from_column" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="get_selection_to_line" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="get_selection_to_column" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="get_selection_text" qualifiers="const" > - <return type="String"> - </return> - <description> - </description> - </method> - <method name="search" qualifiers="const" > - <return type="IntArray"> - </return> - <argument index="0" name="flags" type="String"> - </argument> - <argument index="1" name="from_line" type="int"> - </argument> - <argument index="2" name="from_column" type="int"> - </argument> - <argument index="3" name="to_line" type="int"> - </argument> - <description> - </description> - </method> - <method name="undo" > - <description> - </description> - </method> - <method name="redo" > - <description> - </description> - </method> - <method name="clear_undo_history" > - <description> - </description> - </method> - <method name="set_syntax_coloring" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_syntax_coloring_enabled" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="add_keyword_color" > - <argument index="0" name="keyword" type="String"> - </argument> - <argument index="1" name="color" type="Color"> - </argument> - <description> - </description> - </method> - <method name="add_color_region" > - <argument index="0" name="begin_key" type="String"> - </argument> - <argument index="1" name="end_key" type="String"> - </argument> - <argument index="2" name="color" type="Color"> - </argument> - <argument index="3" name="line_only" type="bool" default="false"> - </argument> - <description> - </description> - </method> - <method name="set_symbol_color" > - <argument index="0" name="color" type="Color"> - </argument> - <description> - </description> - </method> - <method name="set_custom_bg_color" > - <argument index="0" name="color" type="Color"> - </argument> - <description> - </description> - </method> - <method name="clear_colors" > - <description> - </description> - </method> - </methods> - <signals> - <signal name="text_changed"> - <description> - </description> - </signal> - <signal name="cursor_changed"> - <description> - </description> - </signal> - </signals> - <constants> - <constant name="SEARCH_MATCH_CASE" value="1"> - </constant> - <constant name="SEARCH_BACKWARDS" value="4"> - </constant> - <constant name="SEARCH_WHOLE_WORDS" value="2"> - </constant> - </constants> -</class> -<class name="Texture" inherits="Resource" category="Resources"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="create" > - <argument index="0" name="width" type="int"> - </argument> - <argument index="1" name="height" type="int"> - </argument> - <argument index="2" name="format" type="int"> - </argument> - <argument index="3" name="flags" type="int" default="7"> - </argument> - <description> - </description> - </method> - <method name="create_from_image" > - <argument index="0" name="image" type="Image"> - </argument> - <argument index="1" name="flags" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_flags" > - <argument index="0" name="flags" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_flags" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="get_format" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="load" > - <argument index="0" name="path" type="String"> - </argument> - <description> - </description> - </method> - <method name="blit_rect" > - <argument index="0" name="x" type="int"> - </argument> - <argument index="1" name="y" type="int"> - </argument> - <argument index="2" name="image" type="Image"> - </argument> - <argument index="3" name="cube_side" type="int" default="0"> - </argument> - <description> - </description> - </method> - <method name="get_rect" qualifiers="const" > - <return type="Image"> - </return> - <argument index="0" name="x" type="int"> - </argument> - <argument index="1" name="y" type="int"> - </argument> - <argument index="2" name="width" type="int"> - </argument> - <argument index="3" name="height" type="int"> - </argument> - <argument index="4" name="cube_side" type="int" default="0"> - </argument> - <description> - </description> - </method> - <method name="get_width" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="get_height" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="get_size" qualifiers="const" > - <return type="Vector2"> - </return> - <description> - </description> - </method> - <method name="get_rid" qualifiers="const" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="has_alpha" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="draw" qualifiers="const" > - <argument index="0" name="canvas_item" type="RID"> - </argument> - <argument index="1" name="pos" type="Vector2"> - </argument> - <argument index="2" name="modulate" type="Color" default="Color(1,1,1,1)"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - <constant name="CUBEMAP_BACK" value="5"> - </constant> - <constant name="CUBEMAP_FRONT" value="4"> - </constant> - <constant name="FLAG_CUBEMAP" value="8"> - </constant> - <constant name="CUBEMAP_TOP" value="3"> - </constant> - <constant name="CUBEMAP_LEFT" value="0"> - </constant> - <constant name="FLAG_FILTER" value="4"> - </constant> - <constant name="FLAG_MIPMAPS" value="1"> - </constant> - <constant name="CUBEMAP_BOTTOM" value="2"> - </constant> - <constant name="FLAGS_DEFAULT" value="7"> - </constant> - <constant name="CUBEMAP_RIGHT" value="1"> - </constant> - <constant name="FLAG_REPEAT" value="2"> - </constant> - </constants> -</class> -<class name="TextureButton" inherits="BaseButton" category="Nodes/GUI Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_normal_texture" > - <argument index="0" name="texture" type="Object"> - </argument> - <description> - </description> - </method> - <method name="set_pressed_texture" > - <argument index="0" name="texture" type="Object"> - </argument> - <description> - </description> - </method> - <method name="set_hover_texture" > - <argument index="0" name="texture" type="Object"> - </argument> - <description> - </description> - </method> - <method name="set_disabled_texture" > - <argument index="0" name="texture" type="Object"> - </argument> - <description> - </description> - </method> - <method name="set_focused_texture" > - <argument index="0" name="texture" type="Object"> - </argument> - <description> - </description> - </method> - <method name="set_click_mask" > - <argument index="0" name="texture" type="Image"> - </argument> - <description> - </description> - </method> - <method name="get_normal_texture" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="get_pressed_texture" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="get_hover_texture" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="get_disabled_texture" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="get_focused_texture" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="get_click_mask" qualifiers="const" > - <return type="Image"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="TextureFrame" inherits="Control" category="Nodes/GUI Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_texture" > - <argument index="0" name="texture" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_texture" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="set_expand" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="has_expand" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="Theme" inherits="Resource" category="Resources"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_icon" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <argument index="2" name="texture" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_icon" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <description> - </description> - </method> - <method name="has_icon" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <description> - </description> - </method> - <method name="clear_icon" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_icon_list" qualifiers="const" > - <return type="StringArray"> - </return> - <argument index="0" name="arg0" type="String"> - </argument> - <description> - </description> - </method> - <method name="set_stylebox" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <argument index="2" name="texture" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_stylebox" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <description> - </description> - </method> - <method name="has_stylebox" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <description> - </description> - </method> - <method name="clear_stylebox" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_stylebox_list" qualifiers="const" > - <return type="StringArray"> - </return> - <argument index="0" name="arg0" type="String"> - </argument> - <description> - </description> - </method> - <method name="set_font" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <argument index="2" name="font" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_font" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <description> - </description> - </method> - <method name="has_font" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <description> - </description> - </method> - <method name="clear_font" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_font_list" qualifiers="const" > - <return type="StringArray"> - </return> - <argument index="0" name="arg0" type="String"> - </argument> - <description> - </description> - </method> - <method name="set_color" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <argument index="2" name="color" type="Color"> - </argument> - <description> - </description> - </method> - <method name="get_color" qualifiers="const" > - <return type="Color"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <description> - </description> - </method> - <method name="has_color" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <description> - </description> - </method> - <method name="clear_color" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_color_list" qualifiers="const" > - <return type="StringArray"> - </return> - <argument index="0" name="arg0" type="String"> - </argument> - <description> - </description> - </method> - <method name="set_constant" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <argument index="2" name="constant" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_constant" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <description> - </description> - </method> - <method name="has_constant" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <description> - </description> - </method> - <method name="clear_constant" > - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="type" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_constant_list" qualifiers="const" > - <return type="StringArray"> - </return> - <argument index="0" name="arg0" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_type_list" qualifiers="const" > - <return type="StringArray"> - </return> - <argument index="0" name="arg0" type="String"> - </argument> - <description> - </description> - </method> - <method name="copy_default_theme" > - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="Timer" inherits="Node" category="Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_wait_time" > - <argument index="0" name="time_sec" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_wait_time" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - <method name="set_one_shot" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_one_shot" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_autostart" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="has_autostart" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="start" > - <description> - </description> - </method> - <method name="stop" > - <description> - </description> - </method> - <method name="get_time_left" qualifiers="const" > - <return type="real"> - </return> - <description> - </description> - </method> - </methods> - <signals> - <signal name="timeout"> - <description> - </description> - </signal> - </signals> - <constants> - </constants> -</class> -<class name="Tree" inherits="Control" category="Nodes/GUI Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="clear" > - <description> - </description> - </method> - <method name="create_item" > - <return type="Object"> - </return> - <argument index="0" name="arg0" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_root" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="set_column_min_width" > - <argument index="0" name="arg0" type="int"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_column_expand" > - <argument index="0" name="arg0" type="int"> - </argument> - <argument index="1" name="arg1" type="bool"> - </argument> - <description> - </description> - </method> - <method name="get_column_width" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_hide_root" > - <argument index="0" name="arg0" type="bool"> - </argument> - <description> - </description> - </method> - <method name="get_next_selected" > - <return type="Object"> - </return> - <argument index="0" name="arg0" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_selected" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="get_selected_column" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="get_pressed_button" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="set_select_mode" > - <argument index="0" name="arg0" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_columns" > - <argument index="0" name="amount" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_columns" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="get_edited" qualifiers="const" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="get_edited_column" qualifiers="const" > - <return type="int"> - </return> - <description> - </description> - </method> - <method name="get_custom_popup_rect" qualifiers="const" > - <return type="Rect2"> - </return> - <description> - </description> - </method> - <method name="get_item_rect" qualifiers="const" > - <return type="Rect2"> - </return> - <argument index="0" name="item" type="Object"> - </argument> - <argument index="1" name="column" type="int" default="-1"> - </argument> - <description> - </description> - </method> - <method name="ensure_cursor_is_visible" > - <description> - </description> - </method> - <method name="set_column_titles_visible" > - <argument index="0" name="visible" type="bool"> - </argument> - <description> - </description> - </method> - <method name="are_column_titles_visible" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_column_title" > - <argument index="0" name="column" type="int"> - </argument> - <argument index="1" name="title" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_column_title" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="column" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_scroll" qualifiers="const" > - <return type="Vector2"> - </return> - <description> - </description> - </method> - </methods> - <signals> - <signal name="multi_selected"> - <description> - </description> - </signal> - <signal name="custom_popup_edited"> - <argument index="0" name="arrow_clicked" type="bool"> - </argument> - <description> - </description> - </signal> - <signal name="item_edited"> - <description> - </description> - </signal> - <signal name="item_selected"> - <description> - </description> - </signal> - <signal name="item_doubleclicked"> - <description> - </description> - </signal> - <signal name="cell_selected"> - <description> - </description> - </signal> - <signal name="button_pressed"> - <argument index="0" name="item" type="Object"> - </argument> - <argument index="1" name="column" type="int"> - </argument> - <argument index="2" name="id" type="int"> - </argument> - <description> - </description> - </signal> - </signals> - <constants> - <constant name="SELECT_ROW" value="1"> - </constant> - <constant name="SELECT_SINGLE" value="0"> - </constant> - <constant name="SELECT_MULTI" value="2"> - </constant> - </constants> -</class> -<class name="TreeItem" inherits="Object" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_cell_mode" > - <argument index="0" name="column" type="int"> - </argument> - <argument index="1" name="mode" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_cell_mode" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="column" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_checked" > - <argument index="0" name="column" type="int"> - </argument> - <argument index="1" name="checked" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_checked" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="column" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_text" > - <argument index="0" name="column" type="int"> - </argument> - <argument index="1" name="text" type="String"> - </argument> - <description> - </description> - </method> - <method name="get_text" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="column" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_icon" > - <argument index="0" name="column" type="int"> - </argument> - <argument index="1" name="texture" type="Object"> - </argument> - <description> - </description> - </method> - <method name="get_icon" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="column" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_range" > - <argument index="0" name="column" type="int"> - </argument> - <argument index="1" name="value" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_range" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="column" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_range_config" > - <argument index="0" name="column" type="int"> - </argument> - <argument index="1" name="min" type="real"> - </argument> - <argument index="2" name="max" type="real"> - </argument> - <argument index="3" name="step" type="real"> - </argument> - <description> - </description> - </method> - <method name="get_range_config" > - <return type="Dictionary"> - </return> - <argument index="0" name="column" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_metadata" > - <argument index="0" name="column" type="int"> - </argument> - <argument index="1" name="meta" type="var"> - </argument> - <description> - </description> - </method> - <method name="get_metadata" qualifiers="const" > - <argument index="0" name="column" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_collapsed" > - <argument index="0" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_collapsed" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="get_next" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="get_prev" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="get_parent" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="get_children" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="get_next_visible" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="get_prev_visible" > - <return type="Object"> - </return> - <description> - </description> - </method> - <method name="remove_child" > - <argument index="0" name="child" type="Object"> - </argument> - <description> - </description> - </method> - <method name="set_selectable" > - <argument index="0" name="column" type="int"> - </argument> - <argument index="1" name="selectable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_selected" > - <return type="bool"> - </return> - <argument index="0" name="column" type="int"> - </argument> - <description> - </description> - </method> - <method name="select" > - <argument index="0" name="column" type="int"> - </argument> - <description> - </description> - </method> - <method name="deselect" > - <argument index="0" name="column" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_editable" > - <argument index="0" name="column" type="int"> - </argument> - <argument index="1" name="enabled" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_editable" > - <return type="bool"> - </return> - <argument index="0" name="column" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_custom_color" > - <argument index="0" name="column" type="int"> - </argument> - <argument index="1" name="color" type="Color"> - </argument> - <description> - </description> - </method> - <method name="clear_custom_color" > - <argument index="0" name="column" type="int"> - </argument> - <description> - </description> - </method> - <method name="set_custom_bg_color" > - <argument index="0" name="column" type="int"> - </argument> - <argument index="1" name="color" type="Color"> - </argument> - <description> - </description> - </method> - <method name="clear_custom_bg_color" > - <argument index="0" name="column" type="int"> - </argument> - <description> - </description> - </method> - <method name="add_button" > - <argument index="0" name="column" type="int"> - </argument> - <argument index="1" name="button" type="Object"> - </argument> - <argument index="2" name="arg2" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_button_count" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="column" type="int"> - </argument> - <description> - </description> - </method> - <method name="get_button" qualifiers="const" > - <return type="Object"> - </return> - <argument index="0" name="column" type="int"> - </argument> - <argument index="1" name="button_idx" type="int"> - </argument> - <description> - </description> - </method> - <method name="erase_button" > - <argument index="0" name="column" type="int"> - </argument> - <argument index="1" name="button_idx" type="int"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - <constant name="CELL_MODE_ICON" value="3"> - </constant> - <constant name="CELL_MODE_CUSTOM" value="4"> - </constant> - <constant name="CELL_MODE_RANGE" value="2"> - </constant> - <constant name="CELL_MODE_CHECK" value="1"> - </constant> - <constant name="CELL_MODE_STRING" value="0"> - </constant> - </constants> -</class> -<class name="VScrollBar" inherits="ScrollBar" category="Nodes/GUI Nodes"> - <brief_description> - Vertical version of [ScrollBar], which goes from left (min) to right (max). - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="VSeparator" inherits="Separator" category="Nodes/GUI Nodes"> - <brief_description> - Vertical version of [Separator]. - </brief_description> - <description> - Vertical version of [Separator]. It is used to separate objects horizontally, though (but it looks vertical!). - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="VSlider" inherits="Slider" category="Nodes/GUI Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -<class name="Viewport" inherits="Node" category="Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="set_rect" > - <argument index="0" name="rect" type="Rect2"> - </argument> - <description> - </description> - </method> - <method name="get_rect" qualifiers="const" > - <return type="Rect2"> - </return> - <description> - </description> - </method> - <method name="get_visible_rect" qualifiers="const" > - <return type="Rect2"> - </return> - <description> - </description> - </method> - <method name="get_viewport" qualifiers="const" > - <return type="RID"> - </return> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="VisualInstance" inherits="Spatial" category="Nodes/3D/3D Visual Nodes"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="override_material_param" > - <argument index="0" name="param" type="String"> - </argument> - <argument index="1" name="value" type="var"> - </argument> - <description> - </description> - </method> - <method name="set_visible" > - <argument index="0" name="visible" type="bool"> - </argument> - <description> - </description> - </method> - <method name="is_visible" qualifiers="const" > - <return type="bool"> - </return> - <description> - </description> - </method> - <method name="set_base" > - <argument index="0" name="base" type="RID"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - </constants> -</class> -<class name="VisualServer" inherits="Object" category="Core"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - <method name="texture_create" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="texture_create_from_image" > - <return type="RID"> - </return> - <argument index="0" name="arg0" type="Image"> - </argument> - <argument index="1" name="arg1" type="int" default="7"> - </argument> - <description> - </description> - </method> - <method name="texture_allocate" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="int"> - </argument> - <argument index="3" name="arg3" type="int"> - </argument> - <argument index="4" name="arg4" type="int" default="7"> - </argument> - <description> - </description> - </method> - <method name="texture_blit_rect" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="int"> - </argument> - <argument index="3" name="arg3" type="Image"> - </argument> - <argument index="4" name="arg4" type="int" default="0"> - </argument> - <description> - </description> - </method> - <method name="texture_set_flags" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="texture_get_flags" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="texture_get_width" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="texture_get_height" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="shader_create" > - <return type="RID"> - </return> - <argument index="0" name="mode" type="int" default="0"> - </argument> - <description> - </description> - </method> - <method name="shader_set_mode" > - <argument index="0" name="shader" type="RID"> - </argument> - <argument index="1" name="mode" type="int"> - </argument> - <description> - </description> - </method> - <method name="shader_get_mode" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="shader" type="RID"> - </argument> - <description> - </description> - </method> - <method name="shader_set_vertex_code" > - <argument index="0" name="shader" type="RID"> - </argument> - <argument index="1" name="code" type="String"> - </argument> - <description> - </description> - </method> - <method name="shader_get_vertex_code" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="shader" type="RID"> - </argument> - <description> - </description> - </method> - <method name="shader_set_fragment_code" > - <argument index="0" name="shader" type="RID"> - </argument> - <argument index="1" name="code" type="String"> - </argument> - <description> - </description> - </method> - <method name="shader_get_fragment_code" qualifiers="const" > - <return type="String"> - </return> - <argument index="0" name="shader" type="RID"> - </argument> - <description> - </description> - </method> - <method name="shader_set_param" > - <argument index="0" name="shader" type="RID"> - </argument> - <argument index="1" name="param" type="String"> - </argument> - <argument index="2" name="value" type="var"> - </argument> - <description> - </description> - </method> - <method name="shader_get_param" qualifiers="const" > - <argument index="0" name="shader" type="RID"> - </argument> - <argument index="1" name="param" type="String"> - </argument> - <description> - </description> - </method> - <method name="shader_get_param_list" qualifiers="const" > - <return type="StringArray"> - </return> - <argument index="0" name="shader" type="RID"> - </argument> - <description> - </description> - </method> - <method name="shader_set_use_world_transform" > - <argument index="0" name="shader" type="RID"> - </argument> - <argument index="1" name="enable" type="bool"> - </argument> - <description> - </description> - </method> - <method name="shader_is_using_world_transform" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="shader" type="RID"> - </argument> - <description> - </description> - </method> - <method name="material_create" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="material_set_shader" > - <argument index="0" name="shader" type="RID"> - </argument> - <argument index="1" name="arg1" type="RID"> - </argument> - <description> - </description> - </method> - <method name="material_get_shader" qualifiers="const" > - <return type="RID"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="material_set_param" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="String"> - </argument> - <argument index="2" name="arg2" type="var"> - </argument> - <description> - </description> - </method> - <method name="material_get_param" qualifiers="const" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="String"> - </argument> - <description> - </description> - </method> - <method name="material_set_flag" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="bool"> - </argument> - <description> - </description> - </method> - <method name="material_get_flag" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="material_set_blend_mode" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="material_get_blend_mode" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="material_set_line_width" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="real"> - </argument> - <description> - </description> - </method> - <method name="material_get_line_width" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="fixed_material_set_parameter" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="var"> - </argument> - <description> - </description> - </method> - <method name="fixed_material_get_parameter" qualifiers="const" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="fixed_material_set_texture" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="RID"> - </argument> - <description> - </description> - </method> - <method name="fixed_material_get_texture" qualifiers="const" > - <return type="RID"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="fixed_material_set_texgen_mode" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="fixed_material_get_texgen_mode" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="fixed_material_set_texcoord_mode" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="int"> - </argument> - <description> - </description> - </method> - <method name="fixed_material_get_texcoord_mode" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="fixed_material_set_uv_transform" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="Transform"> - </argument> - <description> - </description> - </method> - <method name="fixed_material_get_uv_transform" qualifiers="const" > - <return type="Transform"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="mesh_create" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="mesh_surface_set_array" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="int"> - </argument> - <argument index="3" name="arg3" type="var"> - </argument> - <description> - </description> - </method> - <method name="mesh_surface_get_array" qualifiers="const" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="int"> - </argument> - <description> - </description> - </method> - <method name="mesh_surface_set_material" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="RID"> - </argument> - <argument index="3" name="arg3" type="bool" default="false"> - </argument> - <description> - </description> - </method> - <method name="mesh_surface_get_material" qualifiers="const" > - <return type="RID"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="mesh_surface_get_array_len" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="mesh_surface_get_array_index_len" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="mesh_surface_get_format" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="mesh_surface_get_primitive_type" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="mesh_erase_surface" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="mesh_get_surface_count" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="multimesh_create" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="multimesh_set_mesh" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="RID"> - </argument> - <description> - </description> - </method> - <method name="multimesh_set_aabb" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="AABB"> - </argument> - <description> - </description> - </method> - <method name="multimesh_instance_set_transform" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="Transform"> - </argument> - <description> - </description> - </method> - <method name="multimesh_instance_set_color" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="Color"> - </argument> - <description> - </description> - </method> - <method name="multimesh_get_mesh" qualifiers="const" > - <return type="RID"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="multimesh_get_aabb" qualifiers="const" > - <return type="AABB"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="AABB"> - </argument> - <description> - </description> - </method> - <method name="multimesh_instance_get_transform" qualifiers="const" > - <return type="Transform"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="multimesh_instance_get_color" qualifiers="const" > - <return type="Color"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="poly_create" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="poly_set_material" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="RID"> - </argument> - <argument index="2" name="arg2" type="bool" default="false"> - </argument> - <description> - </description> - </method> - <method name="poly_add_primitive" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="Vector3Array"> - </argument> - <argument index="2" name="arg2" type="Vector3Array"> - </argument> - <argument index="3" name="arg3" type="ColorArray"> - </argument> - <argument index="4" name="arg4" type="Vector3Array"> - </argument> - <description> - </description> - </method> - <method name="poly_clear" > - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="particles_create" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="particles_set_amount" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="particles_get_amount" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="particles_set_emitting" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="bool"> - </argument> - <description> - </description> - </method> - <method name="particles_is_emitting" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="particles_set_visibility_aabb" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="AABB"> - </argument> - <description> - </description> - </method> - <method name="particles_get_visibility_aabb" qualifiers="const" > - <return type="AABB"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="particles_set_variable" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="real"> - </argument> - <description> - </description> - </method> - <method name="particles_get_variable" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="particles_set_randomness" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="real"> - </argument> - <description> - </description> - </method> - <method name="particles_get_randomness" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="particles_set_color_phases" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="particles_get_color_phases" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="particles_set_color_phase_pos" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="real"> - </argument> - <description> - </description> - </method> - <method name="particles_get_color_phase_pos" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="particles_set_color_phase_color" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="Color"> - </argument> - <description> - </description> - </method> - <method name="particles_get_color_phase_color" qualifiers="const" > - <return type="Color"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="particles_set_attractors" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="particles_get_attractors" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="particles_set_attractor_pos" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="Vector3"> - </argument> - <description> - </description> - </method> - <method name="particles_get_attractor_pos" qualifiers="const" > - <return type="Vector3"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="particles_set_attractor_strength" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="real"> - </argument> - <description> - </description> - </method> - <method name="particles_get_attractor_strength" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="particles_set_material" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="RID"> - </argument> - <argument index="2" name="arg2" type="bool" default="false"> - </argument> - <description> - </description> - </method> - <method name="particles_set_height_from_velocity" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="bool"> - </argument> - <description> - </description> - </method> - <method name="particles_has_height_from_velocity" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="light_create" > - <return type="RID"> - </return> - <argument index="0" name="arg0" type="int"> - </argument> - <description> - </description> - </method> - <method name="light_get_type" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="light_set_color" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="Color"> - </argument> - <description> - </description> - </method> - <method name="light_get_color" qualifiers="const" > - <return type="Color"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="light_set_shadow" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="bool"> - </argument> - <description> - </description> - </method> - <method name="light_has_shadow" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="light_set_volumetric" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="bool"> - </argument> - <description> - </description> - </method> - <method name="light_is_volumetric" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="light_set_projector" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="RID"> - </argument> - <description> - </description> - </method> - <method name="light_get_projector" qualifiers="const" > - <return type="RID"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="light_set_var" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="real"> - </argument> - <description> - </description> - </method> - <method name="light_get_var" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="skeleton_create" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="skeleton_resize" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="skeleton_get_bone_count" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="skeleton_bone_set_transform" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="Transform"> - </argument> - <description> - </description> - </method> - <method name="skeleton_bone_get_transform" > - <return type="Transform"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="room_create" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="room_set_bounds" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="Dictionary"> - </argument> - <description> - </description> - </method> - <method name="room_get_bounds" qualifiers="const" > - <return type="Dictionary"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="portal_create" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="portal_set_shape" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="Array"> - </argument> - <description> - </description> - </method> - <method name="portal_get_shape" qualifiers="const" > - <return type="Array"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="portal_set_enabled" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="bool"> - </argument> - <description> - </description> - </method> - <method name="portal_is_enabled" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="portal_set_disable_distance" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="real"> - </argument> - <description> - </description> - </method> - <method name="portal_get_disable_distance" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="portal_set_disabled_color" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="Color"> - </argument> - <description> - </description> - </method> - <method name="portal_get_disabled_color" qualifiers="const" > - <return type="Color"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="camera_create" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="camera_set_perspective" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="real"> - </argument> - <argument index="2" name="arg2" type="real"> - </argument> - <argument index="3" name="arg3" type="real"> - </argument> - <description> - </description> - </method> - <method name="camera_set_orthogonal" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="real"> - </argument> - <argument index="2" name="arg2" type="real"> - </argument> - <argument index="3" name="arg3" type="real"> - </argument> - <description> - </description> - </method> - <method name="camera_set_transform" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="Transform"> - </argument> - <description> - </description> - </method> - <method name="viewport_create" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="viewport_set_rect" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="Rect2"> - </argument> - <description> - </description> - </method> - <method name="viewport_get_rect" qualifiers="const" > - <return type="Rect2"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="viewport_attach_camera" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="RID" default="RID()"> - </argument> - <description> - </description> - </method> - <method name="viewport_get_attached_camera" qualifiers="const" > - <return type="RID"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="viewport_get_scenario" qualifiers="const" > - <return type="RID"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="viewport_attach_canvas" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="RID"> - </argument> - <description> - </description> - </method> - <method name="viewport_remove_canvas" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="RID"> - </argument> - <description> - </description> - </method> - <method name="viewport_move_canvas_to_top" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="RID"> - </argument> - <description> - </description> - </method> - <method name="viewport_move_canvas_to_bottom" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="RID"> - </argument> - <description> - </description> - </method> - <method name="scenario_create" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="scenario_set_debug" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="scenario_fx_get_effects" qualifiers="const" > - <return type="StringArray"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="scenario_fx_set_active" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="String"> - </argument> - <argument index="2" name="arg2" type="bool"> - </argument> - <description> - </description> - </method> - <method name="scenario_fx_is_active" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="String"> - </argument> - <description> - </description> - </method> - <method name="scenario_fx_get_effect_params" qualifiers="const" > - <return type="Array"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="String"> - </argument> - <description> - </description> - </method> - <method name="scenario_fx_get_effect_param" qualifiers="const" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="String"> - </argument> - <argument index="2" name="arg2" type="String"> - </argument> - <description> - </description> - </method> - <method name="scenario_fx_set_effect_param" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="String"> - </argument> - <argument index="2" name="arg2" type="String"> - </argument> - <argument index="3" name="arg3" type="var"> - </argument> - <description> - </description> - </method> - <method name="instance_create" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="instance_get_base" qualifiers="const" > - <return type="RID"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="instance_get_base_aabb" qualifiers="const" > - <return type="RID"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="instance_set_transform" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="Transform"> - </argument> - <description> - </description> - </method> - <method name="instance_get_transform" qualifiers="const" > - <return type="Transform"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="instance_attach_object_instance_ID" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="instance_get_object_instance_ID" qualifiers="const" > - <return type="int"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="instance_attach_skeleton" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="RID"> - </argument> - <description> - </description> - </method> - <method name="instance_get_skeleton" qualifiers="const" > - <return type="RID"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="instance_set_room" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="RID"> - </argument> - <description> - </description> - </method> - <method name="instance_get_room" qualifiers="const" > - <return type="RID"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="instance_set_exterior" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="bool"> - </argument> - <description> - </description> - </method> - <method name="instance_is_exterior" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="instances_cull_aabb" qualifiers="const" > - <return type="Array"> - </return> - <argument index="0" name="arg0" type="AABB"> - </argument> - <argument index="1" name="arg1" type="RID"> - </argument> - <description> - </description> - </method> - <method name="instances_cull_ray" qualifiers="const" > - <return type="Array"> - </return> - <argument index="0" name="arg0" type="Vector3"> - </argument> - <argument index="1" name="arg1" type="Vector3"> - </argument> - <argument index="2" name="arg2" type="RID"> - </argument> - <description> - </description> - </method> - <method name="instances_cull_convex" qualifiers="const" > - <return type="Array"> - </return> - <argument index="0" name="arg0" type="Vector3"> - </argument> - <argument index="1" name="arg1" type="Vector3"> - </argument> - <argument index="2" name="arg2" type="RID"> - </argument> - <description> - </description> - </method> - <method name="instance_geometry_set_visible" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="bool"> - </argument> - <description> - </description> - </method> - <method name="instance_geometry_is_visible" qualifiers="const" > - <return type="bool"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="instance_geometry_override_material_param" qualifiers="const" > - <return type="RID"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="instance_geometry_get_material_param" qualifiers="const" > - <return type="RID"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="canvas_create" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="canvas_item_create" > - <return type="RID"> - </return> - <description> - </description> - </method> - <method name="canvas_item_set_parent" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="RID"> - </argument> - <description> - </description> - </method> - <method name="canvas_item_get_parent" qualifiers="const" > - <return type="RID"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="canvas_item_set_custom_rect" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="bool"> - </argument> - <argument index="2" name="arg2" type="Rect2"> - </argument> - <description> - </description> - </method> - <method name="canvas_item_set_clip" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="bool"> - </argument> - <description> - </description> - </method> - <method name="canvas_item_set_opacity" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="real"> - </argument> - <description> - </description> - </method> - <method name="canvas_item_get_opacity" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="real"> - </argument> - <description> - </description> - </method> - <method name="canvas_item_set_self_opacity" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="real"> - </argument> - <description> - </description> - </method> - <method name="canvas_item_get_self_opacity" qualifiers="const" > - <return type="real"> - </return> - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="real"> - </argument> - <description> - </description> - </method> - <method name="canvas_item_add_line" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="Vector2"> - </argument> - <argument index="2" name="arg2" type="Vector2"> - </argument> - <argument index="3" name="arg3" type="Color"> - </argument> - <argument index="4" name="arg4" type="real" default="1"> - </argument> - <description> - </description> - </method> - <method name="canvas_item_add_rect" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="Rect2"> - </argument> - <argument index="2" name="arg2" type="Color"> - </argument> - <description> - </description> - </method> - <method name="canvas_item_add_texture_rect" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="Rect2"> - </argument> - <argument index="2" name="arg2" type="RID"> - </argument> - <argument index="3" name="arg3" type="bool"> - </argument> - <argument index="4" name="arg4" type="Color" default="Color(1,1,1,1)"> - </argument> - <description> - </description> - </method> - <method name="canvas_item_add_texture_rect_region" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="Rect2"> - </argument> - <argument index="2" name="arg2" type="RID"> - </argument> - <argument index="3" name="arg3" type="Rect2"> - </argument> - <argument index="4" name="arg4" type="Color" default="Color(1,1,1,1)"> - </argument> - <description> - </description> - </method> - <method name="canvas_item_add_style_box" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="Rect2"> - </argument> - <argument index="2" name="arg2" type="RID"> - </argument> - <argument index="3" name="arg3" type="RealArray"> - </argument> - <argument index="4" name="arg4" type="Color" default="Color(1,1,1,1)"> - </argument> - <description> - </description> - </method> - <method name="canvas_item_add_primitive" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="Array"> - </argument> - <argument index="2" name="arg2" type="ColorArray"> - </argument> - <argument index="3" name="arg3" type="Array" default="Array()"> - </argument> - <argument index="4" name="arg4" type="RID" default="RID()"> - </argument> - <description> - </description> - </method> - <method name="canvas_item_clear" > - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="canvas_item_raise" > - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - <method name="cursor_set_rotation" > - <argument index="0" name="arg0" type="real"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="cursor_set_texture" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="Vector2"> - </argument> - <argument index="2" name="arg2" type="int"> - </argument> - <description> - </description> - </method> - <method name="cursor_set_visible" > - <argument index="0" name="arg0" type="bool"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="cursor_set_pos" > - <argument index="0" name="arg0" type="Vector2"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <description> - </description> - </method> - <method name="make_sphere_mesh" > - <return type="RID"> - </return> - <argument index="0" name="arg0" type="int"> - </argument> - <argument index="1" name="arg1" type="int"> - </argument> - <argument index="2" name="arg2" type="real"> - </argument> - <description> - </description> - </method> - <method name="mesh_add_surface_from_planes" > - <argument index="0" name="arg0" type="RID"> - </argument> - <argument index="1" name="arg1" type="Array"> - </argument> - <description> - </description> - </method> - <method name="free" > - <argument index="0" name="arg0" type="RID"> - </argument> - <description> - </description> - </method> - </methods> - <constants> - <constant name="INSTANCE_GEOMETRY_MASK" value="30"> - </constant> - <constant name="INSTANCE_PARTICLES" value="4"> - </constant> - <constant name="SCENARIO_DEBUG_WIREFRAME" value="1"> - </constant> - <constant name="LIGHT_VAR_ATTENUATION" value="4"> - </constant> - <constant name="LIGHT_VAR_SPOT_ANGLE" value="1"> - </constant> - <constant name="LIGHT_COLOR_DIFFUSE" value="1"> - </constant> - <constant name="PARTICLE_ANGULAR_VELOCITY" value="4"> - </constant> - <constant name="INSTANCE_LIGHT" value="5"> - </constant> - <constant name="INSTANCE_MULTIMESH" value="2"> - </constant> - <constant name="PARTICLE_HEIGHT" value="11"> - </constant> - <constant name="PARTICLE_LINEAR_VELOCITY" value="3"> - </constant> - <constant name="FIXED_MATERIAL_PARAM_SPECULAR" value="2"> - </constant> - <constant name="ARRAY_VERTEX" value="0"> - </constant> - <constant name="LIGHT_SPOT" value="2"> - </constant> - <constant name="CUBEMAP_BACK" value="5"> - </constant> - <constant name="MATERIAL_FLAG_MAX" value="7"> - </constant> - <constant name="FIXED_MATERIAL_PARAM_DETAIL_MIX" value="6"> - </constant> - <constant name="ARRAY_COLOR" value="3"> - </constant> - <constant name="ARRAY_FORMAT_BONES" value="64"> - </constant> - <constant name="PRIMITIVE_MAX" value="7"> - </constant> - <constant name="FIXED_MATERIAL_TEXGEN_SPHERE" value="1"> - </constant> - <constant name="ARRAY_FORMAT_INDEX" value="256"> - </constant> - <constant name="PRIMITIVE_TRIANGLE_STRIP" value="5"> - </constant> - <constant name="MAX_PARTICLE_ATTRACTORS" value="4"> - </constant> - <constant name="TEXTURE_FLAG_FILTER" value="4"> - </constant> - <constant name="CUBEMAP_TOP" value="3"> - </constant> - <constant name="MATERIAL_BLEND_MODE_ADD" value="1"> - </constant> - <constant name="FIXED_MATERIAL_TEXCOORD_TEXGEN" value="3"> - </constant> - <constant name="FIXED_MATERIAL_TEXCOORD_UV" value="0"> - </constant> - <constant name="ARRAY_TANGENT" value="2"> - </constant> - <constant name="ARRAY_FORMAT_NORMAL" value="2"> - </constant> - <constant name="INFO_VIDEO_MEM_USED" value="3"> - </constant> - <constant name="LIGHT_VAR_SPOT_ATTENUATION" value="0"> - </constant> - <constant name="TEXTURE_FLAG_MIPMAPS" value="1"> - </constant> - <constant name="MATERIAL_FLAG_INVERT_FACES" value="2"> - </constant> - <constant name="MATERIAL_BLEND_MODE_SUB" value="2"> - </constant> - <constant name="FIXED_MATERIAL_PARAM_DETAIL" value="1"> - </constant> - <constant name="INSTANCE_ROOM" value="6"> - </constant> - <constant name="INSTANCE_MESH" value="1"> - </constant> - <constant name="SCENARIO_DEBUG_DISABLED" value="0"> - </constant> - <constant name="PARTICLE_VAR_MAX" value="13"> - </constant> - <constant name="PRIMITIVE_TRIANGLES" value="4"> - </constant> - <constant name="PRIMITIVE_LINE_STRIP" value="2"> - </constant> - <constant name="TEXTURE_FLAGS_DEFAULT" value="7"> - </constant> - <constant name="CUBEMAP_BOTTOM" value="2"> - </constant> - <constant name="FIXED_MATERIAL_TEXGEN_SCREENZ" value="3"> - </constant> - <constant name="FIXED_MATERIAL_TEXCOORD_UV2" value="2"> - </constant> - <constant name="ARRAY_FORMAT_TEX_UV" value="16"> - </constant> - <constant name="ARRAY_FORMAT_WEIGHTS" value="128"> - </constant> - <constant name="INFO_MATERIAL_CHANGES_IN_FRAME" value="1"> - </constant> - <constant name="PARTICLE_SPREAD" value="1"> - </constant> - <constant name="PARTICLE_LIFETIME" value="0"> - </constant> - <constant name="PRIMITIVE_TRIANGLE_FAN" value="6"> - </constant> - <constant name="NO_INDEX_ARRAY" value="-1"> - </constant> - <constant name="MATERIAL_FLAG_BILLBOARD" value="6"> - </constant> - <constant name="FIXED_MATERIAL_TEXGEN_LOCAL_XY" value="0"> - </constant> - <constant name="SCENARIO_DEBUG_OVERDRAW" value="2"> - </constant> - <constant name="PARTICLE_HEIGHT_SPEED_SCALE" value="12"> - </constant> - <constant name="PARTICLE_INITIAL_ANGLE" value="10"> - </constant> - <constant name="PARTICLE_TANGENTIAL_ACCELERATION" value="7"> - </constant> - <constant name="PRIMITIVE_LINES" value="1"> - </constant> - <constant name="CUSTOM_ARRAY_SIZE" value="8"> - </constant> - <constant name="ARRAY_WEIGHTS_SIZE" value="4"> - </constant> - <constant name="MATERIAL_FLAG_UNSHADED" value="3"> - </constant> - <constant name="FIXED_MATERIAL_PARAM_DIFFUSE" value="0"> - </constant> - <constant name="FIXED_MATERIAL_PARAM_MAX" value="9"> - </constant> - <constant name="LIGHT_COLOR_SPECULAR" value="2"> - </constant> - <constant name="MATERIAL_BLEND_MODE_MIX" value="0"> - </constant> - <constant name="MATERIAL_BLEND_MODE_MUL" value="3"> - </constant> - <constant name="FIXED_MATERIAL_PARAM_EMISSION" value="3"> - </constant> - <constant name="ARRAY_MAX" value="9"> - </constant> - <constant name="ARRAY_FORMAT_VERTEX" value="1"> - </constant> - <constant name="INFO_OBJECTS_IN_FRAME" value="0"> - </constant> - <constant name="LIGHT_VAR_MAX" value="6"> - </constant> - <constant name="LIGHT_COLOR_AMBIENT" value="0"> - </constant> - <constant name="LIGHT_DIRECTIONAL" value="0"> - </constant> - <constant name="PRIMITIVE_POINTS" value="0"> - </constant> - <constant name="CUBEMAP_FRONT" value="4"> - </constant> - <constant name="SHADER_MATERIAL" value="0"> - </constant> - <constant name="MATERIAL_FLAG_VISIBLE" value="0"> - </constant> - <constant name="ARRAY_BONES" value="6"> - </constant> - <constant name="ARRAY_FORMAT_COLOR" value="8"> - </constant> - <constant name="INSTANCE_PORTAL" value="7"> - </constant> - <constant name="MAX_CURSORS" value="8"> - </constant> - <constant name="TEXTURE_FLAG_CUBEMAP" value="8"> - </constant> - <constant name="FIXED_MATERIAL_PARAM_GLOW" value="5"> - </constant> - <constant name="FIXED_MATERIAL_PARAM_NORMAL" value="7"> - </constant> - <constant name="ARRAY_INDEX" value="8"> - </constant> - <constant name="INFO_VERTEX_MEM_USED" value="5"> - </constant> - <constant name="INFO_USAGE_VIDEO_MEM_TOTAL" value="2"> - </constant> - <constant name="LIGHT_VAR_RADIUS" value="2"> - </constant> - <constant name="PARTICLE_FINAL_SIZE" value="9"> - </constant> - <constant name="PARTICLE_INITIAL_SIZE" value="8"> - </constant> - <constant name="PARTICLE_LINEAR_ACCELERATION" value="5"> - </constant> - <constant name="CUBEMAP_LEFT" value="0"> - </constant> - <constant name="MATERIAL_FLAG_ONTOP" value="4"> - </constant> - <constant name="FIXED_MATERIAL_TEXGEN_SCREEN" value="2"> - </constant> - <constant name="ARRAY_NORMAL" value="1"> - </constant> - <constant name="ARRAY_FORMAT_TANGENT" value="4"> - </constant> - <constant name="INSTANCE_POLY" value="3"> - </constant> - <constant name="FIXED_MATERIAL_PARAM_SPECULAR_EXP" value="4"> - </constant> - <constant name="LIGHT_VAR_ENERGY" value="3"> - </constant> - <constant name="PARTICLE_RADIAL_ACCELERATION" value="6"> - </constant> - <constant name="PARTICLE_GRAVITY" value="2"> - </constant> - <constant name="PRIMITIVE_LINE_LOOP" value="3"> - </constant> - <constant name="MATERIAL_FLAG_WIREFRAME" value="5"> - </constant> - <constant name="ARRAY_TEX_UV" value="4"> - </constant> - <constant name="ARRAY_WEIGHTS" value="7"> - </constant> - <constant name="INFO_TEXTURE_MEM_USED" value="4"> - </constant> - <constant name="LIGHT_OMNI" value="1"> - </constant> - <constant name="MAX_PARTICLE_COLOR_PHASES" value="4"> - </constant> - <constant name="TEXTURE_FLAG_REPEAT" value="2"> - </constant> - <constant name="CUBEMAP_RIGHT" value="1"> - </constant> - <constant name="SHADER_POST_PROCESS" value="1"> - </constant> - <constant name="MATERIAL_FLAG_DOUBLE_SIDED" value="1"> - </constant> - <constant name="FIXED_MATERIAL_TEXCOORD_UV_TRANSFORM" value="1"> - </constant> - </constants> -</class> -<class name="World" inherits="Resource" category="Resources"> - <brief_description> - </brief_description> - <description> - </description> - <methods> - </methods> - <constants> - </constants> -</class> -</doc> diff --git a/tools/docdump/doc_dump.cpp b/tools/docdump/doc_dump.cpp index 5f108ee9c8..f8e035e3fa 100644 --- a/tools/docdump/doc_dump.cpp +++ b/tools/docdump/doc_dump.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/docdump/doc_dump.h b/tools/docdump/doc_dump.h index cb18289e31..372f5e0969 100644 --- a/tools/docdump/doc_dump.h +++ b/tools/docdump/doc_dump.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/docdump/doc_merge.py b/tools/docdump/doc_merge.py deleted file mode 100644 index 872f38ed87..0000000000 --- a/tools/docdump/doc_merge.py +++ /dev/null @@ -1,208 +0,0 @@ -import sys -import xml.etree.ElementTree as ET - - -tree = ET.parse(sys.argv[1]) -old_doc=tree.getroot() - -tree = ET.parse(sys.argv[2]) -new_doc=tree.getroot() - -f = file(sys.argv[3],"wb") -tab=0 - -old_classes={} - -def write_string(_f, text,newline=True): - for t in range(tab): - _f.write("\t") - _f.write(text) - if (newline): - _f.write("\n") - -def escape(ret): - ret=ret.replace("&","&"); - ret=ret.replace("<",">"); - ret=ret.replace(">","<"); - ret=ret.replace("'","'"); - ret=ret.replace("\"","""); - return ret - - -def inc_tab(): - global tab - tab+=1 - -def dec_tab(): - global tab - tab-=1 - -write_string(f,'<?xml version="1.0" encoding="UTF-8" ?>') -write_string(f,'<doc version="'+new_doc.attrib["version"]+'">') - -def get_tag(node,name): - tag="" - if (name in node.attrib): - tag=' '+name+'="'+escape(node.attrib[name])+'" ' - return tag - -def find_method_descr(old_class,name): - - methods = old_class.find("methods") - if(methods!=None and len(list(methods))>0): - for m in list(methods): - if (m.attrib["name"]==name): - description=m.find("description") - if (description!=None and description.text.strip()!=""): - return description.text - - return None - -def find_signal_descr(old_class,name): - - signals = old_class.find("signals") - if(signals!=None and len(list(signals))>0): - for m in list(signals): - if (m.attrib["name"]==name): - description=m.find("description") - if (description!=None and description.text.strip()!=""): - return description.text - - return None - -def find_constant_descr(old_class,name): - - if (old_class==None): - return None - constants = old_class.find("constants") - if(constants!=None and len(list(constants))>0): - for m in list(constants): - if (m.attrib["name"]==name): - if (m.text.strip()!=""): - return m.text - return None - -def write_class(c): - class_name = c.attrib["name"] - print("Parsing Class: "+class_name) - if (class_name in old_classes): - old_class=old_classes[class_name] - else: - old_class=None - - - category=get_tag(c,"category") - inherits=get_tag(c,"inherits") - write_string(f,'<class name="'+class_name+'" '+category+inherits+'>') - inc_tab() - - write_string(f,"<brief_description>") - - if (old_class!=None): - old_brief_descr=old_class.find("brief_description") - if (old_brief_descr!=None): - write_string(f,escape(old_brief_descr.text.strip())) - - - write_string(f,"</brief_description>") - - write_string(f,"<description>") - if (old_class!=None): - old_descr=old_class.find("description") - if (old_descr!=None): - write_string(f,escape(old_descr.text.strip())) - - write_string(f,"</description>") - - methods = c.find("methods") - if(methods!=None and len(list(methods))>0): - - write_string(f,"<methods>") - inc_tab() - - for m in list(methods): - qualifiers=get_tag(m,"qualifiers") - - write_string(f,'<method name="'+escape(m.attrib["name"])+'" ' +qualifiers+'>') - inc_tab() - - for a in list(m): - if (a.tag=="return"): - typ=get_tag(a,"type") - write_string(f,'<return'+typ+'>'); - write_string(f,'</return>'); - elif (a.tag=="argument"): - - default=get_tag(a,"default") - - write_string(f,'<argument index="'+a.attrib["index"]+'" name="'+escape(a.attrib["name"])+'" type="'+a.attrib["type"]+'"' +default+'>'); - write_string(f,'</argument>'); - - write_string(f,'<description>'); - if (old_class!=None): - old_method_descr=find_method_descr(old_class,m.attrib["name"]) - if (old_method_descr): - write_string(f,escape(escape(old_method_descr.strip()))) - - write_string(f,'</description>'); - dec_tab() - write_string(f,"</method>") - dec_tab() - write_string(f,"</methods>") - - signals = c.find("signals") - if(signals!=None and len(list(signals))>0): - - write_string(f,"<signals>") - inc_tab() - - for m in list(signals): - - write_string(f,'<signal name="'+escape(m.attrib["name"])+'">') - inc_tab() - - for a in list(m): - if (a.tag=="argument"): - - write_string(f,'<argument index="'+a.attrib["index"]+'" name="'+escape(a.attrib["name"])+'" type="'+a.attrib["type"]+'">'); - write_string(f,'</argument>'); - - write_string(f,'<description>'); - if (old_class!=None): - old_signal_descr=find_signal_descr(old_class,m.attrib["name"]) - if (old_signal_descr): - write_string(f,escape(old_signal_descr.strip())) - write_string(f,'</description>'); - dec_tab() - write_string(f,"</signal>") - dec_tab() - write_string(f,"</signals>") - - constants = c.find("constants") - if(constants!=None and len(list(constants))>0): - - write_string(f,"<constants>") - inc_tab() - - for m in list(constants): - - write_string(f,'<constant name="'+escape(m.attrib["name"])+'" value="'+m.attrib["value"]+'">') - old_constant_descr=find_constant_descr(old_class,m.attrib["name"]) - if (old_constant_descr): - write_string(f,escape(old_constant_descr.strip())) - write_string(f,"</constant>") - - dec_tab() - write_string(f,"</constants>") - - dec_tab() - write_string(f,"</class>") - -for c in list(old_doc): - old_classes[c.attrib["name"]]=c - -for c in list(new_doc): - write_class(c) -write_string(f,'</doc>\n') - - diff --git a/tools/docdump/locales/es/LC_MESSAGES/makedocs.mo b/tools/docdump/locales/es/LC_MESSAGES/makedocs.mo Binary files differdeleted file mode 100644 index 8d7ea2689e..0000000000 --- a/tools/docdump/locales/es/LC_MESSAGES/makedocs.mo +++ /dev/null diff --git a/tools/docdump/locales/es/LC_MESSAGES/makedocs.po b/tools/docdump/locales/es/LC_MESSAGES/makedocs.po deleted file mode 100644 index 82115dd897..0000000000 --- a/tools/docdump/locales/es/LC_MESSAGES/makedocs.po +++ /dev/null @@ -1,142 +0,0 @@ -# Translations template for PROJECT. -# Copyright (C) 2015 ORGANIZATION -# This file is distributed under the same license as the PROJECT project. -# FIRST AUTHOR <EMAIL@ADDRESS>, 2015. -# -msgid "" -msgstr "" -"Project-Id-Version: makedocs\n" -"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2015-10-07 11:47-0600\n" -"PO-Revision-Date: 2015-10-07 13:10-0600\n" -"Last-Translator: Jorge Araya Navarro <elcorreo@deshackra.com>\n" -"Language-Team: \n" -"Language: es\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Generated-By: Babel 2.0\n" -"X-Generator: Poedit 1.8.4\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" - -#: makedocs.py:74 -msgid "" -"\"<code>{gclass}</code>(Go to page of class {gclass})\":/class_{lkclass}" -msgstr "" -"\"<code>{gclass}</code>(Ir a la pagina de la clase {gclass})\":/" -"class_{lkclass}" - -#: makedocs.py:76 -msgid "" -"\"<code>{gclass}.{method}</code>(Go to page {gclass}, section {method})\":/" -"class_{lkclass}#{lkmethod}" -msgstr "" -"\"<code>{gclass}.{method}</code>(Ir a la pagina {gclass}, sección " -"{method})\":/class_{lkclass}#{lkmethod}" - -#: makedocs.py:79 -msgid "\"<code>{method}</code>(Jump to method {method})\":#{lkmethod}" -msgstr "\"<code>{method}</code>(Saltar al método {method})\":#{lkmethod}" - -#: makedocs.py:81 -msgid " \"{rtype}(Go to page of class {rtype})\":/class_{link} " -msgstr " \"{rtype}(Ir a la pagina de la clase {rtype})\":/class_{link} " - -#: makedocs.py:82 -msgid "" -"\"*{funcname}*(Jump to description for node {funcname})\":#{link} <b>(</b> " -msgstr "" -"\"*{funcname}*(Saltar a la descripción para el nodo {funcname})\":#{link} " -"<b>(</b> " - -#: makedocs.py:87 -msgid "h4. Inherits: " -msgstr "h4. Hereda de: " - -#: makedocs.py:232 -msgid "<doc>'s version attribute missing" -msgstr "El atributo version de <doc> no existe" - -#: makedocs.py:246 -msgid "|_. Index symbol |_. Class name |_. Index symbol |_. Class name |\n" -msgstr "" -"|_. Índice de símbolo |_. Nombre de la clase |_. Índice de símbolo |_. " -"Nombre de la clase |\n" - -#: makedocs.py:305 -msgid "" -"h4. Category: {}\n" -"\n" -msgstr "" -"h4. Categoría: {}\n" -"\n" - -#: makedocs.py:310 -msgid "" -"h2. Brief Description\n" -"\n" -msgstr "" -"h2. Descripción breve\n" -"\n" - -#: makedocs.py:312 -msgid "" -"\"read more\":#more\n" -"\n" -msgstr "" -"\"Leer más\":#more\n" -"\n" - -#: makedocs.py:317 -msgid "" -"\n" -"h3. Member Functions\n" -"\n" -msgstr "" -"\n" -"h3. Funciones miembro\n" -"\n" - -#: makedocs.py:323 -msgid "" -"\n" -"h3. Signals\n" -"\n" -msgstr "" -"\n" -"h3. Señales\n" -"\n" - -#: makedocs.py:331 -msgid "" -"\n" -"h3. Numeric Constants\n" -"\n" -msgstr "" -"\n" -"h3. Constantes numéricas\n" -"\n" - -#: makedocs.py:347 -msgid "" -"\n" -"h3(#more). Description\n" -"\n" -msgstr "" -"\n" -"h3(#more). Descripción\n" -"\n" - -#: makedocs.py:351 -msgid "_Nothing here, yet..._\n" -msgstr "_Aún nada por aquí..._\n" - -#: makedocs.py:355 -msgid "" -"\n" -"h3. Member Function Description\n" -"\n" -msgstr "" -"\n" -"h3. Descripción de las funciones miembro\n" -"\n" diff --git a/tools/docdump/main.css b/tools/docdump/main.css deleted file mode 100644 index a76e6bbed8..0000000000 --- a/tools/docdump/main.css +++ /dev/null @@ -1,146 +0,0 @@ -BODY,H1,H2,H3,H4,H5,H6,P,CENTER,TD,TH,UL,DL,DIV, SPAN { - font-family: Arial, Geneva, Helvetica, sans-serif; -} - -a { - - text-decoration: none; - -} - -a:hover { - - text-decoration: underline; -} - -td.top_table { - - padding: 5px; -} - -div.method_doc { - - padding-bottom: 30px; -} - -div.method_description { - margin-left: 30px; -} - -list.inh_class_list { - margin-left: 30px; - -} - -div.inh_class_list { - margin-left: 30px; - -} - -div.method_doc div.method { - - font-size: 12pt; - font-weight: bold; -} - -span.funcdecl { - - color: #202060; -} - -span.funcdef { - - color: #202060; -} - - -span.qualifier { - - font-weight: bold; -} - - -span.symbol { - - /*font-weight: bold;*/ - color: #471870; -} - - -span.datatype { - - color: #6a1533; -} - -tr.category_title { - - background-color: #333333; -} -a.category_title { - font-weight: bold; - color: #FFFFFF; -} - -div.method_list { - - margin-left: 30px; -} - -div.constant_list { - - margin-left: 30px; -} - -div.member_list { - - margin-left: 30px; -} - -div.description { - - margin-left: 30px; -} - -div.class_description { - - margin-left: 30px; -} - -div.method_list li div { - - display: inline; -} - -div.member_list li div.member { - - display: inline; -} - -div.constant_list li div.constant { - - display: inline; -} - -span.member_description { - - font-style: italic; - color: grey; -} - -span.constant_description { - - font-style: italic; - color: grey; -} - -span.identifier { - - font-weight: bold; -} - - -table.class_table td { - - vertical-align: top; -} - diff --git a/tools/docdump/makedocs.pot b/tools/docdump/makedocs.pot deleted file mode 100644 index be3220f686..0000000000 --- a/tools/docdump/makedocs.pot +++ /dev/null @@ -1,108 +0,0 @@ -# Translations template for PROJECT. -# Copyright (C) 2015 ORGANIZATION -# This file is distributed under the same license as the PROJECT project. -# FIRST AUTHOR <EMAIL@ADDRESS>, 2015. -# -#, fuzzy -msgid "" -msgstr "" -"Project-Id-Version: makedocs 0.1\n" -"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2015-10-07 11:47-0600\n" -"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" -"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" -"Language-Team: \n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Generated-By: Babel 2.0\n" -"X-Generator: Poedit 1.8.4\n" - -#: makedocs.py:74 -msgid "\"<code>{gclass}</code>(Go to page of class {gclass})\":/class_{lkclass}" -msgstr "" - -#: makedocs.py:76 -msgid "\"<code>{gclass}.{method}</code>(Go to page {gclass}, section {method})\":/class_{lkclass}#{lkmethod}" -msgstr "" - -#: makedocs.py:79 -msgid "\"<code>{method}</code>(Jump to method {method})\":#{lkmethod}" -msgstr "" - -#: makedocs.py:81 -msgid " \"{rtype}(Go to page of class {rtype})\":/class_{link} " -msgstr "" - -#: makedocs.py:82 -msgid "\"*{funcname}*(Jump to description for node {funcname})\":#{link} <b>(</b> " -msgstr "" - -#: makedocs.py:87 -msgid "h4. Inherits: " -msgstr "" - -#: makedocs.py:232 -msgid "<doc>'s version attribute missing" -msgstr "" - -#: makedocs.py:246 -msgid "|_. Index symbol |_. Class name |_. Index symbol |_. Class name |\n" -msgstr "" - -#: makedocs.py:305 -msgid "" -"h4. Category: {}\n" -"\n" -msgstr "" - -#: makedocs.py:310 -msgid "" -"h2. Brief Description\n" -"\n" -msgstr "" - -#: makedocs.py:312 -msgid "" -"\"read more\":#more\n" -"\n" -msgstr "" - -#: makedocs.py:317 -msgid "" -"\n" -"h3. Member Functions\n" -"\n" -msgstr "" - -#: makedocs.py:323 -msgid "" -"\n" -"h3. Signals\n" -"\n" -msgstr "" - -#: makedocs.py:331 -msgid "" -"\n" -"h3. Numeric Constants\n" -"\n" -msgstr "" - -#: makedocs.py:347 -msgid "" -"\n" -"h3(#more). Description\n" -"\n" -msgstr "" - -#: makedocs.py:351 -msgid "_Nothing here, yet..._\n" -msgstr "" - -#: makedocs.py:355 -msgid "" -"\n" -"h3. Member Function Description\n" -"\n" -msgstr "" diff --git a/tools/docdump/makedocs.py b/tools/docdump/makedocs.py deleted file mode 100644 index be57891abc..0000000000 --- a/tools/docdump/makedocs.py +++ /dev/null @@ -1,382 +0,0 @@ -#!/usr/bin/python3 -# -*- coding: utf-8 -*- - -# -# makedocs.py: Generate documentation for Open Project Wiki -# Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. -# Contributor: Jorge Araya Navarro <elcorreo@deshackra.com> -# - -# IMPORTANT NOTICE: -# If you are going to modify anything from this file, please be sure to follow -# the Style Guide for Python Code or often called "PEP8". To do this -# automagically just install autopep8: -# -# $ sudo pip3 install autopep8 -# -# and run: -# -# $ autopep8 makedocs.py -# -# Before committing your changes. Also be sure to delete any trailing -# whitespace you may left. -# -# TODO: -# * Refactor code. -# * Adapt this script for generating content in other markup formats like -# DokuWiki, Markdown, etc. -# -# Also check other TODO entries in this script for more information on what is -# left to do. -import argparse -import gettext -import logging -import re -from itertools import zip_longest -from os import path, listdir -from xml.etree import ElementTree - - -# add an option to change the verbosity -logging.basicConfig(level=logging.INFO) - - -def getxmlfloc(): - """ Returns the supposed location of the XML file - """ - filepath = path.dirname(path.abspath(__file__)) - return path.join(filepath, "class_list.xml") - - -def langavailable(): - """ Return a list of languages available for translation - """ - filepath = path.join( - path.dirname(path.abspath(__file__)), "locales") - files = listdir(filepath) - choices = [x for x in files] - choices.insert(0, "none") - return choices - - -desc = "Generates documentation from a XML file to different markup languages" - -parser = argparse.ArgumentParser(description=desc) -parser.add_argument("--input", dest="xmlfp", default=getxmlfloc(), - help="Input XML file, default: {}".format(getxmlfloc())) -parser.add_argument("--output-dir", dest="outputdir", required=True, - help="Output directory for generated files") -parser.add_argument("--language", choices=langavailable(), default="none", - help=("Choose the language of translation" - " for the output files. Default is English (none). " - "Note: This is NOT for the documentation itself!")) -# TODO: add an option for outputting different markup formats - -args = parser.parse_args() -# Let's check if the file and output directory exists -if not path.isfile(args.xmlfp): - logging.critical("File not found: {}".format(args.xmlfp)) - exit(1) -elif not path.isdir(args.outputdir): - logging.critical("Path does not exist: {}".format(args.outputdir)) - exit(1) - -_ = gettext.gettext -if args.language != "none": - lang = gettext.translation(domain="makedocs", - localedir="locales", - languages=[args.language]) - lang.install() - - _ = lang.gettext - -# Strings -C_LINK = _("\"<code>{gclass}</code>(Go to page of class" - " {gclass})\":/class_{lkclass}") -MC_LINK = _("\"<code>{gclass}.{method}</code>(Go " - "to page {gclass}, section {method})\"" - ":/class_{lkclass}#{lkmethod}") -TM_JUMP = _("\"<code>{method}</code>(Jump to method" - " {method})\":#{lkmethod}") -GTC_LINK = _(" \"{rtype}(Go to page of class {rtype})\":/class_{link} ") -DFN_JUMP = _("\"*{funcname}*(Jump to description for" - " node {funcname})\":#{link} <b>(</b> ") -M_ARG_DEFAULT = C_LINK + " {name}={default}" -M_ARG = C_LINK + " {name}" - -OPENPROJ_INH = _("h4. Inherits: ") + C_LINK + "\n\n" - - -def tb(string): - """ Return a byte representation of a string - """ - return bytes(string, "UTF-8") - - -def sortkey(c): - """ Symbols are first, letters second - """ - if "_" == c.attrib["name"][0]: - return "A" - else: - return c.attrib["name"] - - -def toOP(text): - """ Convert commands in text to Open Project commands - """ - # TODO: Make this capture content between [command] ... [/command] - groups = re.finditer((r'\[html (?P<command>/?\w+/?)(\]| |=)?(\]| |=)?(?P<a' - 'rg>\w+)?(\]| |=)?(?P<value>"[^"]+")?/?\]'), text) - alignstr = "" - for group in groups: - gd = group.groupdict() - if gd["command"] == "br/": - text = text.replace(group.group(0), "\n\n", 1) - elif gd["command"] == "div": - if gd["value"] == '"center"': - alignstr = ("{display:block; margin-left:auto;" - " margin-right:auto;}") - elif gd["value"] == '"left"': - alignstr = "<" - elif gd["value"] == '"right"': - alignstr = ">" - text = text.replace(group.group(0), "\n\n", 1) - elif gd["command"] == "/div": - alignstr = "" - text = text.replace(group.group(0), "\n\n", 1) - elif gd["command"] == "img": - text = text.replace(group.group(0), "!{align}{src}!".format( - align=alignstr, src=gd["value"].strip('"')), 1) - elif gd["command"] == "b" or gd["command"] == "/b": - text = text.replace(group.group(0), "*", 1) - elif gd["command"] == "i" or gd["command"] == "/i": - text = text.replace(group.group(0), "_", 1) - elif gd["command"] == "u" or gd["command"] == "/u": - text = text.replace(group.group(0), "+", 1) - # Process other non-html commands - groups = re.finditer((r'\[method ((?P<class>[aA0-zZ9_]+)(?:\.))' - r'?(?P<method>[aA0-zZ9_]+)\]'), text) - for group in groups: - gd = group.groupdict() - if gd["class"]: - replacewith = (MC_LINK.format(gclass=gd["class"], - method=gd["method"], - lkclass=gd["class"].lower(), - lkmethod=gd["method"].lower())) - else: - # The method is located in the same wiki page - replacewith = (TM_JUMP.format(method=gd["method"], - lkmethod=gd["method"].lower())) - - text = text.replace(group.group(0), replacewith, 1) - # Finally, [Classes] are around brackets, make them direct links - groups = re.finditer(r'\[(?P<class>[az0-AZ0_]+)\]', text) - for group in groups: - gd = group.groupdict() - replacewith = (C_LINK. - format(gclass=gd["class"], - lkclass=gd["class"].lower())) - text = text.replace(group.group(0), replacewith, 1) - - return text + "\n\n" - - -def mkfn(node, is_signal=False): - """ Return a string containing a unsorted item for a function - """ - finalstr = "" - name = node.attrib["name"] - rtype = node.find("return") - if rtype: - rtype = rtype.attrib["type"] - else: - rtype = "void" - # write the return type and the function name first - finalstr += "* " - # return type - if not is_signal: - if rtype != "void": - finalstr += GTC_LINK.format( - rtype=rtype, - link=rtype.lower()) - else: - finalstr += " void " - - # function name - if not is_signal: - finalstr += DFN_JUMP.format( - funcname=name, - link=name.lower()) - else: - # Signals have no description - finalstr += "*{funcname}* <b>(</b>".format(funcname=name) - # loop for the arguments of the function, if any - args = [] - for arg in sorted( - node.iter(tag="argument"), - key=lambda a: int(a.attrib["index"])): - - ntype = arg.attrib["type"] - nname = arg.attrib["name"] - - if "default" in arg.attrib: - args.insert(-1, M_ARG_DEFAULT.format( - gclass=ntype, - lkclass=ntype.lower(), - name=nname, - default=arg.attrib["default"])) - else: - # No default value present - args.insert(-1, M_ARG.format(gclass=ntype, - lkclass=ntype.lower(), name=nname)) - # join the arguments together - finalstr += ", ".join(args) - # and, close the function with a ) - finalstr += " <b>)</b>" - # write the qualifier, if any - if "qualifiers" in node.attrib: - qualifier = node.attrib["qualifiers"] - finalstr += " " + qualifier - - finalstr += "\n" - - return finalstr - -# Let's begin -tree = ElementTree.parse(args.xmlfp) -root = tree.getroot() - -# Check version attribute exists in <doc> -if "version" not in root.attrib: - logging.critical(_("<doc>'s version attribute missing")) - exit(1) - -version = root.attrib["version"] -classes = sorted(root, key=sortkey) -# first column is always longer, second column of classes should be shorter -zclasses = zip_longest(classes[:int(len(classes) / 2 + 1)], - classes[int(len(classes) / 2 + 1):], - fillvalue="") - -# We write the class_list file and also each class file at once -with open(path.join(args.outputdir, "class_list.txt"), "wb") as fcl: - # Write header of table - fcl.write(tb("|^.\n")) - fcl.write(tb(_("|_. Index symbol |_. Class name " - "|_. Index symbol |_. Class name |\n"))) - fcl.write(tb("|-.\n")) - - indexletterl = "" - indexletterr = "" - for gdclassl, gdclassr in zclasses: - # write a row # - # write the index symbol column, left - if indexletterl != gdclassl.attrib["name"][0]: - indexletterl = gdclassl.attrib["name"][0] - fcl.write(tb("| *{}* |".format(indexletterl.upper()))) - else: - # empty cell - fcl.write(tb("| |")) - # write the class name column, left - fcl.write(tb(C_LINK.format( - gclass=gdclassl.attrib["name"], - lkclass=gdclassl.attrib["name"].lower()))) - - # write the index symbol column, right - if isinstance(gdclassr, ElementTree.Element): - if indexletterr != gdclassr.attrib["name"][0]: - indexletterr = gdclassr.attrib["name"][0] - fcl.write(tb("| *{}* |".format(indexletterr.upper()))) - else: - # empty cell - fcl.write(tb("| |")) - # We are dealing with an empty string - else: - # two empty cell - fcl.write(tb("| | |\n")) - # We won't get the name of the class since there is no ElementTree - # object for the right side of the tuple, so we iterate the next - # tuple instead - continue - - # write the class name column (if any), right - fcl.write(tb(C_LINK.format( - gclass=gdclassl.attrib["name"], - lkclass=gdclassl.attrib["name"].lower()) + "|\n")) - - # row written # - # now, let's write each class page for each class - for gdclass in [gdclassl, gdclassr]: - if not isinstance(gdclass, ElementTree.Element): - continue - - classname = gdclass.attrib["name"] - with open(path.join(args.outputdir, "{}.txt".format( - classname.lower())), "wb") as clsf: - # First level header with the name of the class - clsf.write(tb("h1. {}\n\n".format(classname))) - # lay the attributes - if "inherits" in gdclass.attrib: - inh = gdclass.attrib["inherits"].strip() - clsf.write(tb(OPENPROJ_INH.format(gclass=inh, - lkclass=inh.lower()))) - if "category" in gdclass.attrib: - clsf.write(tb(_("h4. Category: {}\n\n"). - format(gdclass.attrib["category"].strip()))) - # lay child nodes - briefd = gdclass.find("brief_description") - if briefd.text.strip(): - clsf.write(tb(_("h2. Brief Description\n\n"))) - clsf.write(tb(toOP(briefd.text.strip()) + - _("\"read more\":#more\n\n"))) - - # Write the list of member functions of this class - methods = gdclass.find("methods") - if methods and len(methods) > 0: - clsf.write(tb(_("\nh3. Member Functions\n\n"))) - for method in methods.iter(tag='method'): - clsf.write(tb(mkfn(method))) - - signals = gdclass.find("signals") - if signals and len(signals) > 0: - clsf.write(tb(_("\nh3. Signals\n\n"))) - for signal in signals.iter(tag='signal'): - clsf.write(tb(mkfn(signal, True))) - # TODO: <members> tag is necessary to process? it does not - # exists in class_list.xml file. - - consts = gdclass.find("constants") - if consts and len(consts) > 0: - clsf.write(tb(_("\nh3. Numeric Constants\n\n"))) - for const in sorted(consts, key=lambda k: - k.attrib["name"]): - if const.text.strip(): - clsf.write(tb("* *{name}* = *{value}* - {desc}\n". - format( - name=const.attrib["name"], - value=const.attrib["value"], - desc=const.text.strip()))) - else: - # Constant have no description - clsf.write(tb("* *{name}* = *{value}*\n". - format( - name=const.attrib["name"], - value=const.attrib["value"]))) - descrip = gdclass.find("description") - clsf.write(tb(_("\nh3(#more). Description\n\n"))) - if descrip.text: - clsf.write(tb(descrip.text.strip() + "\n")) - else: - clsf.write(tb(_("_Nothing here, yet..._\n"))) - - # and finally, the description for each method - if methods and len(methods) > 0: - clsf.write(tb(_("\nh3. Member Function Description\n\n"))) - for method in methods.iter(tag='method'): - clsf.write(tb("h4(#{n}). {name}\n\n".format( - n=method.attrib["name"].lower(), - name=method.attrib["name"]))) - clsf.write(tb(mkfn(method) + "\n")) - clsf.write(tb(toOP(method.find( - "description").text.strip()))) diff --git a/tools/docdump/makedoku.py b/tools/docdump/makedoku.py deleted file mode 100644 index e8207715fe..0000000000 --- a/tools/docdump/makedoku.py +++ /dev/null @@ -1,511 +0,0 @@ -import sys -import xml.etree.ElementTree as ET - -input_list = [] - - -for arg in sys.argv[1:]: - input_list.append(arg) - -if len(input_list) < 1: - print("usage: makedoku.py <class_list.xml>") - sys.exit(0) - - -def validate_tag(elem,tag): - if (elem.tag != tag): - print("Tag mismatch, expected '"+tag+"', got "+elem.tag); - sys.exit(255) - - -class_names=[] -classes={} - - -def make_class_list(class_list,columns): - - f=open("class_list.txt","wb") - prev=0 - col_max = len(class_list) / columns + 1 - print("col max is ", col_max) - col_count = 0 - row_count = 0 - last_initial = "" - fit_columns=[] - - for n in range(0,columns): - fit_columns+=[[]] - - indexers=[] - last_initial="" - - idx=0 - for n in class_list: - col = idx/col_max - if (col>=columns): - col=columns-1 - fit_columns[col]+=[n] - idx+=1 - if (n[:1]!=last_initial): - indexers+=[n] - last_initial=n[:1] - - - row_max=0 - - for n in range(0,columns): - if (len(fit_columns[n])>row_max): - row_max=len(fit_columns[n]) - - - for r in range(0,row_max): - s="|" - for c in range(0,columns): - if (r>=len(fit_columns[c])): - continue - - classname = fit_columns[c][r] - initial=classname[0] - if (classname in indexers): - s+="**"+initial+"**|" - else: - s+=" |" - - s+="[["+classname.lower()+"|"+classname+"]]|" - - s+="\n" - f.write(s) - - -def dokuize_text(txt): - - return txt - - -def dokuize_text(text): - pos=0 - while(True): - pos = text.find("[",pos) - if (pos==-1): - break - - endq_pos=text.find("]",pos+1) - if (endq_pos==-1): - break - - pre_text=text[:pos] - post_text=text[endq_pos+1:] - tag_text=text[pos+1:endq_pos] - - if (tag_text in class_names): - tag_text="[["+tag_text.lower()+"|"+tag_text+"]]" - else: #command - cmd=tag_text - space_pos=tag_text.find(" ") - if (cmd.find("html")==0): - cmd=tag_text[:space_pos] - param=tag_text[space_pos+1:] - tag_text="<"+param+">" - elif(cmd.find("method")==0): - cmd=tag_text[:space_pos] - param=tag_text[space_pos+1:] - - if (param.find(".")!=-1): - class_param,method_param=param.split(".") - tag_text="[["+class_param.lower()+"#"+method_param+"|"+class_param+'.'+method_param+"]]" - else: - tag_text="[[#"+param+"|"+param+"]]" - elif (cmd.find("image=")==0): - tag_text="{{"+cmd[6:]+"}}" - elif (cmd.find("url=")==0): - tag_text="[["+cmd[4:]+"|" - elif (cmd=="/url"): - tag_text="]]>" - elif (cmd=="center"): - tag_text="" - elif (cmd=="/center"): - tag_text="" - elif (cmd=="br"): - tag_text="\\\\\n" - elif (cmd=="i" or cmd=="/i"): - tag_text="//" - elif (cmd=="b" or cmd=="/b"): - tag_text="**" - elif (cmd=="u" or cmd=="/u"): - tag_text="__" - else: - tag_text="["+tag_text+"]" - - - text=pre_text+tag_text+post_text - pos=len(pre_text)+len(tag_text) - - #tnode = ET.SubElement(parent,"div") - #tnode.text=text - return text - - -def make_type(t): - global class_names - if (t in class_names): - return "[["+t.lower()+"|"+t+"]]" - return t - - -def make_method(f,name,m,declare,event=False): - - s=" * " - ret_type="void" - args=list(m) - mdata={} - mdata["argidx"]=[] - for a in args: - if (a.tag=="return"): - idx=-1 - elif (a.tag=="argument"): - idx=int(a.attrib["index"]) - else: - continue - - mdata["argidx"].append(idx) - mdata[idx]=a - - - - if (not event): - if (-1 in mdata["argidx"]): - s+=make_type(mdata[-1].attrib["type"]) - else: - s+="void" - s+=" " - - if (declare): - - #span.attrib["class"]="funcdecl" - #a=ET.SubElement(span,"a") - #a.attrib["name"]=name+"_"+m.attrib["name"] - #a.text=name+"::"+m.attrib["name"] - s+="**"+m.attrib["name"]+"**" - else: - s+="[[#"+m.attrib["name"]+"|"+m.attrib["name"]+"]]" - - s+="**(**" - argfound=False - for a in mdata["argidx"]: - arg=mdata[a] - if (a<0): - continue - if (a>0): - s+=", " - else: - s+=" " - - s+=make_type(arg.attrib["type"]) - if ("name" in arg.attrib): - s+=" "+arg.attrib["name"] - else: - s+=" arg"+str(a) - - if ("default" in arg.attrib): - s+="="+arg.attrib["default"] - - - argfound=True - - if (argfound): - s+=" " - s+="**)**" - - if ("qualifiers" in m.attrib): - s+=" "+m.attrib["qualifiers"] - - f.write(s+"\n") - - -def make_doku_class(node): - - name = node.attrib["name"] - - f=open(name.lower()+".txt","wb") - - f.write("====== "+name+" ======\n") - - if ("inherits" in node.attrib): - inh=node.attrib["inherits"].strip() - f.write("**Inherits:** [["+inh.lower()+"|"+inh+"]]\\\\\n") - if ("category" in node.attrib): - f.write("**Category:** "+node.attrib["category"].strip()+"\\\\\n") - - briefd = node.find("brief_description") - if (briefd!=None): - f.write("===== Brief Description ======\n") - f.write( dokuize_text(briefd.text.strip())+"\n" ) - - methods = node.find("methods") - - if(methods!=None and len(list(methods))>0): - f.write("===== Member Functions ======\n") - for m in list(methods): - make_method(f,node.attrib["name"],m,False) - - events = node.find("signals") - if(events!=None and len(list(events))>0): - f.write("===== Signals ======\n") - for m in list(events): - make_method(f,node.attrib["name"],m,True,True) - - members = node.find("members") - - if(members!=None and len(list(members))>0): - f.write("===== Member Variables ======\n") - - for c in list(members): - s = " * " - s+=make_type(c.attrib["type"])+" " - s+="**"+c.attrib["name"]+"**" - if (c.text.strip()!=""): - s+=" - "+c.text.strip() - f.write(s+"\n") - - - - constants = node.find("constants") - if(constants!=None and len(list(constants))>0): - f.write("===== Numeric Constants ======\n") - for c in list(constants): - s = " * " - s+="**"+c.attrib["name"]+"**" - if ("value" in c.attrib): - s+=" = **"+c.attrib["value"]+"**" - if (c.text.strip()!=""): - s+=" - "+c.text.strip() - f.write(s+"\n") - - - descr=node.find("description") - if (descr!=None and descr.text.strip()!=""): - f.write("===== Description ======\n") - f.write(dokuize_text(descr.text.strip())+"\n") - - methods = node.find("methods") - - if(methods!=None and len(list(methods))>0): - f.write("===== Member Function Description ======\n") - for m in list(methods): - - d=m.find("description") - if (d==None or d.text.strip()==""): - continue - f.write("== "+m.attrib["name"]+" ==\n") - make_method(f,node.attrib["name"],m,False) - f.write("\\\\\n") - f.write(dokuize_text(d.text.strip())) - f.write("\n") - - - - - - """ - div=ET.Element("div") - div.attrib["class"]="class"; - - a=ET.SubElement(div,"a") - a.attrib["name"]=node.attrib["name"] - - h3=ET.SubElement(a,"h3") - h3.attrib["class"]="title class_title" - h3.text=node.attrib["name"] - - briefd = node.find("brief_description") - if (briefd!=None): - div2=ET.SubElement(div,"div") - div2.attrib["class"]="description class_description" - div2.text=briefd.text - - if ("inherits" in node.attrib): - ET.SubElement(div,"br") - - div2=ET.SubElement(div,"div") - div2.attrib["class"]="inheritance"; - - span=ET.SubElement(div2,"span") - span.text="Inherits: " - - make_type(node.attrib["inherits"],div2) - - if ("category" in node.attrib): - ET.SubElement(div,"br") - - div3=ET.SubElement(div,"div") - div3.attrib["class"]="category"; - - span=ET.SubElement(div3,"span") - span.attrib["class"]="category" - span.text="Category: " - - a = ET.SubElement(div3,"a") - a.attrib["class"]="category_ref" - a.text=node.attrib["category"] - catname=a.text - if (catname.rfind("/")!=-1): - catname=catname[catname.rfind("/"):] - catname="CATEGORY_"+catname - - if (single_page): - a.attrib["href"]="#"+catname - else: - a.attrib["href"]="category.html#"+catname - - - methods = node.find("methods") - - if(methods!=None and len(list(methods))>0): - - h4=ET.SubElement(div,"h4") - h4.text="Public Methods:" - - method_table=ET.SubElement(div,"table") - method_table.attrib["class"]="method_list"; - - for m in list(methods): -# li = ET.SubElement(div2, "li") - method_table.append( make_method_def(node.attrib["name"],m,False) ) - - events = node.find("signals") - - if(events!=None and len(list(events))>0): - h4=ET.SubElement(div,"h4") - h4.text="Events:" - - event_table=ET.SubElement(div,"table") - event_table.attrib["class"]="method_list"; - - for m in list(events): -# li = ET.SubElement(div2, "li") - event_table.append( make_method_def(node.attrib["name"],m,False,True) ) - - - members = node.find("members") - if(members!=None and len(list(members))>0): - - h4=ET.SubElement(div,"h4") - h4.text="Public Variables:" - div2=ET.SubElement(div,"div") - div2.attrib["class"]="member_list"; - - for c in list(members): - - li = ET.SubElement(div2, "li") - div3=ET.SubElement(li,"div") - div3.attrib["class"]="member"; - make_type(c.attrib["type"],div3) - span=ET.SubElement(div3,"span") - span.attrib["class"]="identifier member_name" - span.text=" "+c.attrib["name"]+" " - span=ET.SubElement(div3,"span") - span.attrib["class"]="member_description" - span.text=c.text - - - constants = node.find("constants") - if(constants!=None and len(list(constants))>0): - - h4=ET.SubElement(div,"h4") - h4.text="Constants:" - div2=ET.SubElement(div,"div") - div2.attrib["class"]="constant_list"; - - for c in list(constants): - li = ET.SubElement(div2, "li") - div3=ET.SubElement(li,"div") - div3.attrib["class"]="constant"; - - span=ET.SubElement(div3,"span") - span.attrib["class"]="identifier constant_name" - span.text=c.attrib["name"]+" " - if ("value" in c.attrib): - span=ET.SubElement(div3,"span") - span.attrib["class"]="symbol" - span.text="= " - span=ET.SubElement(div3,"span") - span.attrib["class"]="constant_value" - span.text=c.attrib["value"]+" " - span=ET.SubElement(div3,"span") - span.attrib["class"]="constant_description" - span.text=c.text - -# ET.SubElement(div,"br") - - - descr=node.find("description") - if (descr!=None and descr.text.strip()!=""): - - h4=ET.SubElement(div,"h4") - h4.text="Description:" - - make_text_def(node.attrib["name"],div,descr.text) -# div2=ET.SubElement(div,"div") -# div2.attrib["class"]="description"; -# div2.text=descr.text - - - - if(methods!=None or events!=None): - - h4=ET.SubElement(div,"h4") - h4.text="Method Documentation:" - iter_list = [] - if (methods!=None): - iter_list+=list(methods) - if (events!=None): - iter_list+=list(events) - - for m in iter_list: - - descr=m.find("description") - - if (descr==None or descr.text.strip()==""): - continue; - - div2=ET.SubElement(div,"div") - div2.attrib["class"]="method_doc"; - - - div2.append( make_method_def(node.attrib["name"],m,True) ) - #anchor = ET.SubElement(div2, "a") - #anchor.attrib["name"] = - make_text_def(node.attrib["name"],div2,descr.text) - #div3=ET.SubElement(div2,"div") - #div3.attrib["class"]="description"; - #div3.text=descr.text - - - return div -""" -for file in input_list: - tree = ET.parse(file) - doc=tree.getroot() - - if ("version" not in doc.attrib): - print("Version missing from 'doc'") - sys.exit(255) - - version=doc.attrib["version"] - - for c in list(doc): - if (c.attrib["name"] in class_names): - continue - class_names.append(c.attrib["name"]) - classes[c.attrib["name"]]=c - - -class_names.sort() - -make_class_list(class_names,4) - -for cn in class_names: - c=classes[cn] - make_doku_class(c) - - diff --git a/tools/docdump/makehtml.py b/tools/docdump/makehtml.py deleted file mode 100644 index d533ca1b8b..0000000000 --- a/tools/docdump/makehtml.py +++ /dev/null @@ -1,704 +0,0 @@ -import sys -import xml.etree.ElementTree as ET - -input_list = [] - -single_page=True - -for arg in sys.argv[1:]: - if arg[:1] == "-": - if arg[1:] == "multipage": - single_page = False - if arg[1:] == "singlepage": - single_page = True - else: - input_list.append(arg) - -if len(input_list) < 1: - print("usage: makehtml.py <class_list.xml>") - sys.exit(0) - - -def validate_tag(elem,tag): - if (elem.tag != tag): - print("Tag mismatch, expected '"+tag+"', got "+elem.tag); - sys.exit(255) - -def make_html_bottom(body): - #make_html_top(body,True) - ET.SubElement(body,"hr") - copyright = ET.SubElement(body,"span") - copyright.text = "Copyright 2008-2010 Codenix SRL" - -def make_html_top(body,bottom=False): - - if (bottom): - ET.SubElement(body,"hr") - - table = ET.SubElement(body,"table") - table.attrib["class"]="top_table" - tr = ET.SubElement(table,"tr") - td = ET.SubElement(tr,"td") - td.attrib["class"]="top_table" - - img = ET.SubElement(td,"image") - img.attrib["src"]="images/logo.png" - td = ET.SubElement(tr,"td") - td.attrib["class"]="top_table" - a = ET.SubElement(td,"a") - a.attrib["href"]="index.html" - a.text="Index" - td = ET.SubElement(tr,"td") - td.attrib["class"]="top_table" - a = ET.SubElement(td,"a") - a.attrib["href"]="alphabetical.html" - a.text="Classes" - td = ET.SubElement(tr,"td") - td.attrib["class"]="top_table" - a = ET.SubElement(td,"a") - a.attrib["href"]="category.html" - a.text="Categories" - td = ET.SubElement(tr,"td") - a = ET.SubElement(td,"a") - a.attrib["href"]="inheritance.html" - a.text="Inheritance" - if (not bottom): - ET.SubElement(body,"hr") - - - - -def make_html_class_list(class_list,columns): - - div=ET.Element("div") - div.attrib["class"]="ClassList"; - - h1=ET.SubElement(div,"h2") - h1.text="Alphabetical Class List" - - table=ET.SubElement(div,"table") - table.attrib["class"]="class_table" - table.attrib["width"]="100%" - prev=0 - - col_max = len(class_list) / columns + 1 - print("col max is ", col_max) - col_count = 0 - row_count = 0 - last_initial = "" - fit_columns=[] - - for n in range(0,columns): - fit_columns+=[[]] - - indexers=[] - last_initial="" - - idx=0 - for n in class_list: - col = idx/col_max - if (col>=columns): - col=columns-1 - fit_columns[col]+=[n] - idx+=1 - if (n[:1]!=last_initial): - indexers+=[n] - last_initial=n[:1] - - row_max=0 - - for n in range(0,columns): - if (len(fit_columns[n])>row_max): - row_max=len(fit_columns[n]) - - - for r in range(0,row_max): - tr = ET.SubElement(table,"tr") - for c in range(0,columns): - tdi = ET.SubElement(tr,"td") - tdi.attrib["align"]="right" - td = ET.SubElement(tr,"td") - if (r>=len(fit_columns[c])): - continue - - classname = fit_columns[c][r] - print(classname) - if (classname in indexers): - - span = ET.SubElement(tdi, "span") - span.attrib["class"] = "class_index_letter" - span.text = classname[:1].upper() - - if (single_page): - link="#"+classname - else: - link=classname+".html" - - a=ET.SubElement(td,"a") - a.attrib["href"]=link - a.text=classname - - - if (not single_page): - cat_class_list=ET.Element("html") - csscc = ET.SubElement(cat_class_list, "link") - csscc.attrib["href"] = "main.css" - csscc.attrib["rel"] = "stylesheet" - csscc.attrib["type"] = "text/css" - bodycc = ET.SubElement(cat_class_list, "body") - make_html_top(bodycc) - - cat_class_parent=bodycc - else: - cat_class_parent=div - - - - - h1=ET.SubElement(cat_class_parent,"h2") - h1.text="Class List By Category" - - class_cat_table={} - class_cat_list=[] - - for c in class_list: - clss = classes[c] - if ("category" in clss.attrib): - class_cat=clss.attrib["category"] - else: - class_cat="Core" - if (class_cat.find("/")!=-1): - class_cat=class_cat[class_cat.rfind("/")+1:] - if (not class_cat in class_cat_list): - class_cat_list.append(class_cat) - class_cat_table[class_cat]=[] - class_cat_table[class_cat].append(c) - - class_cat_list.sort() - - ct = ET.SubElement(cat_class_parent,"table") - for cl in class_cat_list: - l = class_cat_table[cl] - l.sort() - tr = ET.SubElement(ct,"tr") - tr.attrib["class"]="category_title" - td = ET.SubElement(ct,"td") - td.attrib["class"]="category_title" - - a = ET.SubElement(td,"a") - a.attrib["class"]="category_title" - a.text=cl - a.attrib["name"]="CATEGORY_"+cl - - td = ET.SubElement(ct,"td") - td.attrib["class"]="category_title" - - for clt in l: - tr = ET.SubElement(ct,"tr") - td = ET.SubElement(ct,"td") - make_type(clt,td) - clss=classes[clt] - bd = clss.find("brief_description") - bdtext="" - if (bd!=None): - bdtext=bd.text - td = ET.SubElement(ct,"td") - td.text=bdtext - - if (not single_page): - make_html_bottom(bodycc) - catet_out = ET.ElementTree(cat_class_list) - catet_out.write("category.html") - - - if (not single_page): - inh_class_list=ET.Element("html") - cssic = ET.SubElement(inh_class_list, "link") - cssic.attrib["href"] = "main.css" - cssic.attrib["rel"] = "stylesheet" - cssic.attrib["type"] = "text/css" - bodyic = ET.SubElement(inh_class_list, "body") - make_html_top(bodyic) - inh_class_parent=bodyic - else: - inh_class_parent=div - - - - - h1=ET.SubElement(inh_class_parent,"h2") - h1.text="Class List By Inheritance" - - itemlist = ET.SubElement(inh_class_parent,"list") - - class_inh_table={} - - def add_class(clss): - if (clss.attrib["name"] in class_inh_table): - return #already added - parent_list=None - - if ("inherits" in clss.attrib): - inhc = clss.attrib["inherits"] - if (not (inhc in class_inh_table)): - add_class(classes[inhc]) - - parent_list = class_inh_table[inhc].find("div") - if (parent_list == None): - parent_div = ET.SubElement(class_inh_table[inhc],"div") - parent_list = ET.SubElement(parent_div,"list") - parent_div.attrib["class"]="inh_class_list" - else: - parent_list = parent_list.find("list") - - - else: - parent_list=itemlist - - item = ET.SubElement(parent_list,"li") -# item.attrib["class"]="inh_class_list" - class_inh_table[clss.attrib["name"]]=item - make_type(clss.attrib["name"],item) - - - for c in class_list: - add_class(classes[c]) - - if (not single_page): - make_html_bottom(bodyic) - catet_out = ET.ElementTree(inh_class_list) - catet_out.write("inheritance.html") - - - - - - #h1=ET.SubElement(div,"h2") - #h1.text="Class List By Inheritance" - - return div - - -def make_type(p_type,p_parent): - if (p_type=="RefPtr"): - p_type="Resource" - - if (p_type in class_names): - a=ET.SubElement(p_parent,"a") - a.attrib["class"]="datatype_existing" - a.text=p_type+" " - if (single_page): - a.attrib["href"]="#"+p_type - else: - a.attrib["href"]=p_type+".html" - else: - span=ET.SubElement(p_parent,"span") - span.attrib["class"]="datatype" - span.text=p_type+" " - - - -def make_text_def(class_name,parent,text): - pos=0 - while(True): - pos = text.find("[",pos) - if (pos==-1): - break - - endq_pos=text.find("]",pos+1) - if (endq_pos==-1): - break - - pre_text=text[:pos] - post_text=text[endq_pos+1:] - tag_text=text[pos+1:endq_pos] - - if (tag_text in class_names): - if (single_page): - tag_text='<a href="#'+tag_text+'">'+tag_text+'</a>' - else: - tag_text='<a href="'+tag_text+'.html">'+tag_text+'</a>' - else: #command - cmd=tag_text - space_pos=tag_text.find(" ") - if (cmd.find("html")==0): - cmd=tag_text[:space_pos] - param=tag_text[space_pos+1:] - tag_text="<"+param+">" - elif(cmd.find("method")==0): - cmd=tag_text[:space_pos] - param=tag_text[space_pos+1:] - - if (not single_page and param.find(".")!=-1): - class_param,method_param=param.split(".") - tag_text=tag_text='<a href="'+class_param+'.html#'+class_param+"_"+method_param+'">'+class_param+'.'+method_param+'()</a>' - else: - tag_text=tag_text='<a href="#'+class_name+"_"+param+'">'+class_name+'.'+param+'()</a>' - elif (cmd.find("image=")==0): - print("found image: "+cmd) - tag_text="<img src="+cmd[6:]+"/>" - elif (cmd.find("url=")==0): - tag_text="<a href="+cmd[4:]+">" - elif (cmd=="/url"): - tag_text="</a>" - elif (cmd=="center"): - tag_text="<div align=\"center\">" - elif (cmd=="/center"): - tag_text="</div>" - elif (cmd=="br"): - tag_text="<br/>" - elif (cmd=="i" or cmd=="/i" or cmd=="b" or cmd=="/b" or cmd=="u" or cmd=="/u"): - tag_text="<"+tag_text+">" #html direct mapping - else: - tag_text="["+tag_text+"]" - - - text=pre_text+tag_text+post_text - pos=len(pre_text)+len(tag_text) - - #tnode = ET.SubElement(parent,"div") - #tnode.text=text - text="<div class=\"description\">"+text+"</div>" - try: - tnode=ET.XML(text) - parent.append(tnode) - except: - print("Error parsing description text: '"+text+"'") - sys.exit(255) - - - return tnode - - - - -def make_method_def(name,m,declare,event=False): - - mdata={} - - - if (not declare): - div=ET.Element("tr") - div.attrib["class"]="method" - ret_parent=ET.SubElement(div,"td") - ret_parent.attrib["align"]="right" - func_parent=ET.SubElement(div,"td") - else: - div=ET.Element("div") - div.attrib["class"]="method" - ret_parent=div - func_parent=div - - mdata["argidx"]=[] - mdata["name"]=m.attrib["name"] - qualifiers="" - if ("qualifiers" in m.attrib): - qualifiers=m.attrib["qualifiers"] - - args=list(m) - for a in args: - if (a.tag=="return"): - idx=-1 - elif (a.tag=="argument"): - idx=int(a.attrib["index"]) - else: - continue - - mdata["argidx"].append(idx) - mdata[idx]=a - - if (not event): - if (-1 in mdata["argidx"]): - make_type(mdata[-1].attrib["type"],ret_parent) - mdata["argidx"].remove(-1) - else: - make_type("void",ret_parent) - - span=ET.SubElement(func_parent,"span") - if (declare): - span.attrib["class"]="funcdecl" - a=ET.SubElement(span,"a") - a.attrib["name"]=name+"_"+m.attrib["name"] - a.text=name+"::"+m.attrib["name"] - else: - span.attrib["class"]="identifier funcdef" - a=ET.SubElement(span,"a") - a.attrib["href"]="#"+name+"_"+m.attrib["name"] - a.text=m.attrib["name"] - - span=ET.SubElement(func_parent,"span") - span.attrib["class"]="symbol" - span.text=" (" - - for a in mdata["argidx"]: - arg=mdata[a] - if (a>0): - span=ET.SubElement(func_parent,"span") - span.text=", " - else: - span=ET.SubElement(func_parent,"span") - span.text=" " - - - make_type(arg.attrib["type"],func_parent) - - span=ET.SubElement(func_parent,"span") - span.text=arg.attrib["name"] - if ("default" in arg.attrib): - span.text=span.text+"="+arg.attrib["default"] - - - span=ET.SubElement(func_parent,"span") - span.attrib["class"]="symbol" - if (len(mdata["argidx"])): - span.text=" )" - else: - span.text=")" - - if (qualifiers): - span=ET.SubElement(func_parent,"span") - span.attrib["class"]="qualifier" - span.text=" "+qualifiers - - return div - - -def make_html_class(node): - - div=ET.Element("div") - div.attrib["class"]="class"; - - a=ET.SubElement(div,"a") - a.attrib["name"]=node.attrib["name"] - - h3=ET.SubElement(a,"h3") - h3.attrib["class"]="title class_title" - h3.text=node.attrib["name"] - - briefd = node.find("brief_description") - if (briefd!=None): - div2=ET.SubElement(div,"div") - div2.attrib["class"]="description class_description" - div2.text=briefd.text - - if ("inherits" in node.attrib): - ET.SubElement(div,"br") - - div2=ET.SubElement(div,"div") - div2.attrib["class"]="inheritance"; - - span=ET.SubElement(div2,"span") - span.text="Inherits: " - - make_type(node.attrib["inherits"],div2) - - if ("category" in node.attrib): - ET.SubElement(div,"br") - - div3=ET.SubElement(div,"div") - div3.attrib["class"]="category"; - - span=ET.SubElement(div3,"span") - span.attrib["class"]="category" - span.text="Category: " - - a = ET.SubElement(div3,"a") - a.attrib["class"]="category_ref" - a.text=node.attrib["category"] - catname=a.text - if (catname.rfind("/")!=-1): - catname=catname[catname.rfind("/"):] - catname="CATEGORY_"+catname - - if (single_page): - a.attrib["href"]="#"+catname - else: - a.attrib["href"]="category.html#"+catname - - - methods = node.find("methods") - - if(methods!=None and len(list(methods))>0): - - h4=ET.SubElement(div,"h4") - h4.text="Public Methods:" - - method_table=ET.SubElement(div,"table") - method_table.attrib["class"]="method_list"; - - for m in list(methods): -# li = ET.SubElement(div2, "li") - method_table.append( make_method_def(node.attrib["name"],m,False) ) - - events = node.find("signals") - - if(events!=None and len(list(events))>0): - h4=ET.SubElement(div,"h4") - h4.text="Events:" - - event_table=ET.SubElement(div,"table") - event_table.attrib["class"]="method_list"; - - for m in list(events): -# li = ET.SubElement(div2, "li") - event_table.append( make_method_def(node.attrib["name"],m,False,True) ) - - - members = node.find("members") - if(members!=None and len(list(members))>0): - - h4=ET.SubElement(div,"h4") - h4.text="Public Variables:" - div2=ET.SubElement(div,"div") - div2.attrib["class"]="member_list"; - - for c in list(members): - - li = ET.SubElement(div2, "li") - div3=ET.SubElement(li,"div") - div3.attrib["class"]="member"; - make_type(c.attrib["type"],div3) - span=ET.SubElement(div3,"span") - span.attrib["class"]="identifier member_name" - span.text=" "+c.attrib["name"]+" " - span=ET.SubElement(div3,"span") - span.attrib["class"]="member_description" - span.text=c.text - - - constants = node.find("constants") - if(constants!=None and len(list(constants))>0): - - h4=ET.SubElement(div,"h4") - h4.text="Constants:" - div2=ET.SubElement(div,"div") - div2.attrib["class"]="constant_list"; - - for c in list(constants): - li = ET.SubElement(div2, "li") - div3=ET.SubElement(li,"div") - div3.attrib["class"]="constant"; - - span=ET.SubElement(div3,"span") - span.attrib["class"]="identifier constant_name" - span.text=c.attrib["name"]+" " - if ("value" in c.attrib): - span=ET.SubElement(div3,"span") - span.attrib["class"]="symbol" - span.text="= " - span=ET.SubElement(div3,"span") - span.attrib["class"]="constant_value" - span.text=c.attrib["value"]+" " - span=ET.SubElement(div3,"span") - span.attrib["class"]="constant_description" - span.text=c.text - -# ET.SubElement(div,"br") - - - descr=node.find("description") - if (descr!=None and descr.text.strip()!=""): - - h4=ET.SubElement(div,"h4") - h4.text="Description:" - - make_text_def(node.attrib["name"],div,descr.text) -# div2=ET.SubElement(div,"div") -# div2.attrib["class"]="description"; -# div2.text=descr.text - - - - if(methods!=None or events!=None): - - h4=ET.SubElement(div,"h4") - h4.text="Method Documentation:" - iter_list = [] - if (methods!=None): - iter_list+=list(methods) - if (events!=None): - iter_list+=list(events) - - for m in iter_list: - - descr=m.find("description") - - if (descr==None or descr.text.strip()==""): - continue; - - div2=ET.SubElement(div,"div") - div2.attrib["class"]="method_doc"; - - - div2.append( make_method_def(node.attrib["name"],m,True) ) - #anchor = ET.SubElement(div2, "a") - #anchor.attrib["name"] = - make_text_def(node.attrib["name"],div2,descr.text) - #div3=ET.SubElement(div2,"div") - #div3.attrib["class"]="description"; - #div3.text=descr.text - - - return div - -class_names=[] -classes={} - - -for file in input_list: - tree = ET.parse(file) - doc=tree.getroot() - - if ("version" not in doc.attrib): - print("Version missing from 'doc'") - sys.exit(255) - - version=doc.attrib["version"] - - for c in list(doc): - if (c.attrib["name"] in class_names): - continue - class_names.append(c.attrib["name"]) - classes[c.attrib["name"]]=c - -html = ET.Element("html") -css = ET.SubElement(html, "link") -css.attrib["href"] = "main.css" -css.attrib["rel"] = "stylesheet" -css.attrib["type"] = "text/css" - -body = ET.SubElement(html, "body") -if (not single_page): - make_html_top(body) - - - -class_names.sort() - -body.append( make_html_class_list(class_names,5) ) - -for cn in class_names: - c=classes[cn] - if (single_page): - body.append( make_html_class(c)) - else: - html2 = ET.Element("html") - css = ET.SubElement(html2, "link") - css.attrib["href"] = "main.css" - css.attrib["rel"] = "stylesheet" - css.attrib["type"] = "text/css" - body2 = ET.SubElement(html2, "body" ) - make_html_top(body2) - body2.append( make_html_class(c) ); - make_html_bottom(body2) - et_out = ET.ElementTree(html2) - et_out.write(c.attrib["name"]+".html") - - -et_out = ET.ElementTree(html) -if (single_page): - et_out.write("singlepage.html") -else: - make_html_bottom(body) - et_out.write("alphabetical.html") - diff --git a/tools/docdump/makemd.py b/tools/docdump/makemd.py deleted file mode 100644 index f85d145d5e..0000000000 --- a/tools/docdump/makemd.py +++ /dev/null @@ -1,345 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -import sys -import xml.etree.ElementTree as ET - -input_list = [] - -for arg in sys.argv[1:]: - input_list.append(arg) - -if len(input_list) < 1: - print 'usage: makedoku.py <class_list.xml>' - sys.exit(0) - - -def validate_tag(elem, tag): - if elem.tag != tag: - print "Tag mismatch, expected '" + tag + "', got " + elem.tag - sys.exit(255) - - -class_names = [] -classes = {} - - -def make_class_list(class_list, columns): - - f = open('class_list.md', 'wb') - prev = 0 - col_max = len(class_list) / columns + 1 - print ('col max is ', col_max) - col_count = 0 - row_count = 0 - last_initial = '' - fit_columns = [] - - for n in range(0, columns): - fit_columns += [[]] - - indexers = [] - last_initial = '' - - idx = 0 - for n in class_list: - col = idx / col_max - if col >= columns: - col = columns - 1 - fit_columns[col] += [n] - idx += 1 - if n[:1] != last_initial: - indexers += [n] - last_initial = n[:1] - - row_max = 0 - f.write("\n") - - for n in range(0, columns): - if len(fit_columns[n]) > row_max: - row_max = len(fit_columns[n]) - - f.write("| ") - for n in range(0, columns): - f.write(" | |") - - f.write("\n") - f.write("| ") - for n in range(0, columns): - f.write(" --- | ------- |") - f.write("\n") - - for r in range(0, row_max): - s = '| ' - for c in range(0, columns): - if r >= len(fit_columns[c]): - continue - - classname = fit_columns[c][r] - initial = classname[0] - if classname in indexers: - s += '**' + initial + '** | ' - else: - s += ' | ' - - s += '[' + classname + '](class_'+ classname.lower()+') | ' - - s += '\n' - f.write(s) - - -def dokuize_text(txt): - - return txt - - -def dokuize_text(text): - pos = 0 - while True: - pos = text.find('[', pos) - if pos == -1: - break - - endq_pos = text.find(']', pos + 1) - if endq_pos == -1: - break - - pre_text = text[:pos] - post_text = text[endq_pos + 1:] - tag_text = text[pos + 1:endq_pos] - - if tag_text in class_names: - tag_text = make_type(tag_text) - else: - - # command - - cmd = tag_text - space_pos = tag_text.find(' ') - if cmd.find('html') == 0: - cmd = tag_text[:space_pos] - param = tag_text[space_pos + 1:] - tag_text = '<' + param + '>' - elif cmd.find('method') == 0: - cmd = tag_text[:space_pos] - param = tag_text[space_pos + 1:] - - if param.find('.') != -1: - (class_param, method_param) = param.split('.') - tag_text = '['+class_param+'.'+method_param.replace("_","_")+'](' + class_param.lower() + '#' \ - + method_param + ')' - else: - tag_text = '[' + param.replace("_","_") + '](#' + param + ')' - elif cmd.find('image=') == 0: - tag_text = '' - elif cmd.find('url=') == 0: - tag_text = '[' + cmd[4:] + ']('+cmd[4:] - elif cmd == '/url': - tag_text = ')' - elif cmd == 'center': - tag_text = '' - elif cmd == '/center': - tag_text = '' - elif cmd == 'br': - tag_text = '\n' - elif cmd == 'i' or cmd == '/i': - tag_text = '_' - elif cmd == 'b' or cmd == '/b': - tag_text = '**' - elif cmd == 'u' or cmd == '/u': - tag_text = '__' - else: - tag_text = '[' + tag_text + ']' - - text = pre_text + tag_text + post_text - pos = len(pre_text) + len(tag_text) - - # tnode = ET.SubElement(parent,"div") - # tnode.text=text - - return text - - -def make_type(t): - global class_names - if t in class_names: - return '[' + t + '](class_' + t.lower() + ')' - return t - - -def make_method( - f, - name, - m, - declare, - event=False, - ): - - s = ' * ' - ret_type = 'void' - args = list(m) - mdata = {} - mdata['argidx'] = [] - for a in args: - if a.tag == 'return': - idx = -1 - elif a.tag == 'argument': - idx = int(a.attrib['index']) - else: - continue - - mdata['argidx'].append(idx) - mdata[idx] = a - - if not event: - if -1 in mdata['argidx']: - s += make_type(mdata[-1].attrib['type']) - else: - s += 'void' - s += ' ' - - if declare: - - # span.attrib["class"]="funcdecl" - # a=ET.SubElement(span,"a") - # a.attrib["name"]=name+"_"+m.attrib["name"] - # a.text=name+"::"+m.attrib["name"] - - s += ' **'+m.attrib['name'].replace("_","_")+'** ' - else: - s += ' **['+ m.attrib['name'].replace("_","_")+'](#' + m.attrib['name'] + ')** ' - - s += ' **(**' - argfound = False - for a in mdata['argidx']: - arg = mdata[a] - if a < 0: - continue - if a > 0: - s += ', ' - else: - s += ' ' - - s += make_type(arg.attrib['type']) - if 'name' in arg.attrib: - s += ' ' + arg.attrib['name'] - else: - s += ' arg' + str(a) - - if 'default' in arg.attrib: - s += '=' + arg.attrib['default'] - - argfound = True - - if argfound: - s += ' ' - s += ' **)**' - - if 'qualifiers' in m.attrib: - s += ' ' + m.attrib['qualifiers'] - - f.write(s + '\n') - - -def make_doku_class(node): - - name = node.attrib['name'] - - f = open("class_"+name.lower() + '.md', 'wb') - - f.write('# ' + name + ' \n') - - if 'inherits' in node.attrib: - inh = node.attrib['inherits'].strip() - f.write('####**Inherits:** '+make_type(inh)+'\n') - if 'category' in node.attrib: - f.write('####**Category:** ' + node.attrib['category'].strip() - + '\n') - - briefd = node.find('brief_description') - if briefd != None: - f.write('\n### Brief Description \n') - f.write(dokuize_text(briefd.text.strip()) + '\n') - - methods = node.find('methods') - - if methods != None and len(list(methods)) > 0: - f.write('\n### Member Functions \n') - for m in list(methods): - make_method(f, node.attrib['name'], m, False) - - events = node.find('signals') - if events != None and len(list(events)) > 0: - f.write('\n### Signals \n') - for m in list(events): - make_method(f, node.attrib['name'], m, True, True) - - members = node.find('members') - - if members != None and len(list(members)) > 0: - f.write('\n### Member Variables \n') - - for c in list(members): - s = ' * ' - s += make_type(c.attrib['type']) + ' ' - s += '**' + c.attrib['name'] + '**' - if c.text.strip() != '': - s += ' - ' + c.text.strip() - f.write(s + '\n') - - constants = node.find('constants') - if constants != None and len(list(constants)) > 0: - f.write('\n### Numeric Constants \n') - for c in list(constants): - s = ' * ' - s += '**' + c.attrib['name'] + '**' - if 'value' in c.attrib: - s += ' = **' + c.attrib['value'] + '**' - if c.text.strip() != '': - s += ' - ' + c.text.strip() - f.write(s + '\n') - - descr = node.find('description') - if descr != None and descr.text.strip() != '': - f.write('\n### Description \n') - f.write(dokuize_text(descr.text.strip()) + '\n') - - methods = node.find('methods') - - if methods != None and len(list(methods)) > 0: - f.write('\n### Member Function Description \n') - for m in list(methods): - - d = m.find('description') - if d == None or d.text.strip() == '': - continue - f.write('\n#### <a name="'+m.attrib['name']+'">' + m.attrib['name'] + '</a>\n') - make_method(f, node.attrib['name'], m, True) - f.write('\n') - f.write(dokuize_text(d.text.strip())) - f.write('\n') - - -for file in input_list: - tree = ET.parse(file) - doc = tree.getroot() - - if 'version' not in doc.attrib: - print "Version missing from 'doc'" - sys.exit(255) - - version = doc.attrib['version'] - - for c in list(doc): - if c.attrib['name'] in class_names: - continue - class_names.append(c.attrib['name']) - classes[c.attrib['name']] = c - -class_names.sort() - -make_class_list(class_names, 2) - -for cn in class_names: - c = classes[cn] - make_doku_class(c) - diff --git a/tools/editor/SCsub b/tools/editor/SCsub index 73ec530177..cd46ff8353 100644 --- a/tools/editor/SCsub +++ b/tools/editor/SCsub @@ -28,7 +28,7 @@ def make_doc_header(target,source,env): - + if (env["tools"]=="yes"): @@ -43,17 +43,16 @@ if (env["tools"]=="yes"): f.write(reg_exporters_inc) f.write(reg_exporters) f.close() - + env.Depends("#tools/editor/doc_data_compressed.h","#doc/base/classes.xml") env.Command("#tools/editor/doc_data_compressed.h","#doc/base/classes.xml",make_doc_header) #make_doc_header(env.File("#tools/editor/doc_data_raw.h").srcnode().abspath,env.File("#doc/base/classes.xml").srcnode().abspath,env) - + env.add_source_files(env.tool_sources,"*.cpp") - + Export('env') - SConscript('icons/SCsub'); + SConscript('icons/SCsub'); SConscript('plugins/SCsub'); SConscript('fileserver/SCsub'); SConscript('io_plugins/SCsub'); - diff --git a/tools/editor/animation_editor.cpp b/tools/editor/animation_editor.cpp index 5df49bd327..2d274dc91b 100644 --- a/tools/editor/animation_editor.cpp +++ b/tools/editor/animation_editor.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -34,6 +34,7 @@ #include "pair.h" #include "scene/gui/separator.h" #include "editor_node.h" +#include "tools/editor/plugins/animation_player_editor_plugin.h" /* Missing to fix: *Set @@ -627,31 +628,41 @@ public: }; -void AnimationKeyEditor::_menu_track(int p_type) { +void AnimationKeyEditor::_menu_add_track(int p_type) { ERR_FAIL_COND(!animation.is_valid()); - last_menu_track_opt=p_type; switch(p_type) { - case TRACK_MENU_ADD_CALL_TRACK: { + case ADD_TRACK_MENU_ADD_CALL_TRACK: { if (root) { call_select->popup_centered_ratio(); break; } } break; - case TRACK_MENU_ADD_VALUE_TRACK: - case TRACK_MENU_ADD_TRANSFORM_TRACK: { + case ADD_TRACK_MENU_ADD_VALUE_TRACK: + case ADD_TRACK_MENU_ADD_TRANSFORM_TRACK: { undo_redo->create_action("Anim Add Track"); - undo_redo->add_do_method(animation.ptr(),"add_track",p_type); + undo_redo->add_do_method(animation.ptr(),"add_track",p_type); undo_redo->add_do_method(animation.ptr(),"track_set_path",animation->get_track_count(),"."); undo_redo->add_undo_method(animation.ptr(),"remove_track",animation->get_track_count()); undo_redo->commit_action(); } break; + } +} + +void AnimationKeyEditor::_menu_track(int p_type) { + + ERR_FAIL_COND(!animation.is_valid()); + + + last_menu_track_opt=p_type; + switch(p_type) { + case TRACK_MENU_SCALE: case TRACK_MENU_SCALE_PIVOT: { @@ -893,6 +904,23 @@ void AnimationKeyEditor::_menu_track(int p_type) { optimize_dialog->popup_centered(Size2(250,180)); } break; + case TRACK_MENU_CLEAN_UP: { + + cleanup_dialog->popup_centered_minsize(Size2(300,0)); + } break; + case TRACK_MENU_CLEAN_UP_CONFIRM: { + + if (cleanup_all->is_pressed()) { + List<StringName> names; + AnimationPlayerEditor::singleton->get_player()->get_animation_list(&names); + for (List<StringName>::Element *E=names.front();E;E=E->next()) { + _cleanup_animation(AnimationPlayerEditor::singleton->get_player()->get_animation(E->get())); + } + } else { + _cleanup_animation(animation); + + } + } break; case CURVE_SET_LINEAR: { curve_edit->force_transition(1.0); @@ -923,6 +951,57 @@ void AnimationKeyEditor::_menu_track(int p_type) { } +void AnimationKeyEditor::_cleanup_animation(Ref<Animation> p_animation) { + + + for(int i=0;i<p_animation->get_track_count();i++) { + + bool prop_exists=false; + Variant::Type valid_type=Variant::NIL; + Object *obj=NULL; + + RES res; + Node *node = root->get_node_and_resource(p_animation->track_get_path(i),res); + + if (res.is_valid()) { + obj=res.ptr(); + } else if (node) { + obj=node; + } + + if (obj && p_animation->track_get_type(i)==Animation::TYPE_VALUE) { + valid_type=obj->get_static_property_type(p_animation->track_get_path(i).get_property(),&prop_exists); + } + + if (!obj && cleanup_tracks->is_pressed()) { + + p_animation->remove_track(i); + i--; + continue; + } + + if (!prop_exists || p_animation->track_get_type(i)!=Animation::TYPE_VALUE || cleanup_keys->is_pressed()==false) + continue; + + for(int j=0;j<p_animation->track_get_key_count(i);j++) { + + Variant v = p_animation->track_get_key_value(i,j); + + if (!Variant::can_convert(v.get_type(),valid_type)) { + p_animation->track_remove_key(i,j); + j--; + } + } + + if (p_animation->track_get_key_count(i)==0 && cleanup_tracks->is_pressed()) { + p_animation->remove_track(i); + i--; + } + } + + undo_redo->clear_history(); + _update_paths(); +} void AnimationKeyEditor::_animation_optimize() { @@ -999,6 +1078,7 @@ void AnimationKeyEditor::_track_editor_draw() { if (!animation.is_valid()) { v_scroll->hide(); h_scroll->hide(); + menu_add_track->set_disabled(true); menu_track->set_disabled(true); edit_button->set_disabled(true); key_editor_tab->hide(); @@ -1008,6 +1088,7 @@ void AnimationKeyEditor::_track_editor_draw() { return; } + menu_add_track->set_disabled(false); menu_track->set_disabled(false); edit_button->set_disabled(false); move_up_button->set_disabled(false); @@ -1030,6 +1111,7 @@ void AnimationKeyEditor::_track_editor_draw() { timecolor = Color::html("ff4a414f"); Color hover_color = Color(1,1,1,0.05); Color select_color = Color(1,1,1,0.1); + Color invalid_path_color = Color(1,0.6,0.4,0.5); Color track_select_color =Color::html("ffbd8e8e"); Ref<Texture> remove_icon = get_icon("Remove","EditorIcons"); @@ -1056,6 +1138,9 @@ void AnimationKeyEditor::_track_editor_draw() { get_icon("KeyCall","EditorIcons") }; + Ref<Texture> invalid_icon = get_icon("KeyInvalid","EditorIcons"); + Ref<Texture> invalid_icon_hover = get_icon("KeyInvalidHover","EditorIcons"); + Ref<Texture> hsize_icon = get_icon("Hsize","EditorIcons"); Ref<Texture> type_hover=get_icon("KeyHover","EditorIcons"); @@ -1242,6 +1327,23 @@ void AnimationKeyEditor::_track_editor_draw() { break; int y = h+i*h+sep; + bool prop_exists=false; + Variant::Type valid_type=Variant::NIL; + Object *obj=NULL; + + RES res; + Node *node = root->get_node_and_resource(animation->track_get_path(idx),res); + + if (res.is_valid()) { + obj=res.ptr(); + } else if (node) { + obj=node; + } + + if (obj && animation->track_get_type(idx)==Animation::TYPE_VALUE) { + valid_type=obj->get_static_property_type(animation->track_get_path(idx).get_property(),&prop_exists); + } + if (/*mouse_over.over!=MouseOver::OVER_NONE &&*/ idx==mouse_over.track) { Color sepc=hover_color; @@ -1262,6 +1364,8 @@ void AnimationKeyEditor::_track_editor_draw() { ncol=track_select_color; te->draw_string(font,Point2(ofs+Point2(type_icon[0]->get_width()+sep,y+font->get_ascent()+(sep/2))).floor(),np,ncol,name_limit-(type_icon[0]->get_width()+sep)-5); + if (!obj) + te->draw_line(ofs+Point2(0,y+h/2),ofs+Point2(name_limit,y+h/2),invalid_path_color); te->draw_line(ofs+Point2(0,y+h),ofs+Point2(size.width,y+h),sepcolor); @@ -1327,6 +1431,8 @@ void AnimationKeyEditor::_track_editor_draw() { int kc=animation->track_get_key_count(idx); bool first=true; + + for(int i=0;i<kc;i++) { @@ -1374,7 +1480,21 @@ void AnimationKeyEditor::_track_editor_draw() { } - te->draw_texture(tex,ofs+Point2(x,y+key_vofs).floor()); + if (prop_exists && !Variant::can_convert(value.get_type(),valid_type)) { + te->draw_texture(invalid_icon,ofs+Point2(x,y+key_vofs).floor()); + } + + if (prop_exists && !Variant::can_convert(value.get_type(),valid_type)) { + if (tex==type_hover) + te->draw_texture(invalid_icon_hover,ofs+Point2(x,y+key_vofs).floor()); + else + te->draw_texture(invalid_icon,ofs+Point2(x,y+key_vofs).floor()); + } else { + + te->draw_texture(tex,ofs+Point2(x,y+key_vofs).floor()); + } + + first=false; } @@ -2543,6 +2663,8 @@ void AnimationKeyEditor::_track_editor_input_event(const InputEvent& p_input) { String text; text="time: "+rtos(animation->track_get_key_time(idx,mouse_over.over_key))+"\n"; + + switch(animation->track_get_type(idx)) { case Animation::TYPE_TRANSFORM: { @@ -2557,8 +2679,33 @@ void AnimationKeyEditor::_track_editor_input_event(const InputEvent& p_input) { } break; case Animation::TYPE_VALUE: { - Variant v = animation->track_get_key_value(idx,mouse_over.over_key); - text+="value: "+String(v)+"\n"; + Variant v = animation->track_get_key_value(idx,mouse_over.over_key);; + //text+="value: "+String(v)+"\n"; + + bool prop_exists=false; + Variant::Type valid_type=Variant::NIL; + Object *obj=NULL; + + RES res; + Node *node = root->get_node_and_resource(animation->track_get_path(idx),res); + + if (res.is_valid()) { + obj=res.ptr(); + } else if (node) { + obj=node; + } + + if (obj) { + valid_type=obj->get_static_property_type(animation->track_get_path(idx).get_property(),&prop_exists); + } + + text+="type: "+Variant::get_type_name(v.get_type())+"\n"; + if (prop_exists && !Variant::can_convert(v.get_type(),valid_type)) { + text+="value: "+String(v)+" (Invalid, expected type: "+Variant::get_type_name(valid_type)+")\n"; + } else { + text+="value: "+String(v)+"\n"; + } + } break; case Animation::TYPE_METHOD: { @@ -2581,6 +2728,9 @@ void AnimationKeyEditor::_track_editor_input_event(const InputEvent& p_input) { } break; } text+="easing: "+rtos(animation->track_get_key_transition(idx,mouse_over.over_key)); + + + track_editor->set_tooltip(text); return; @@ -2659,12 +2809,14 @@ void AnimationKeyEditor::_notification(int p_what) { case NOTIFICATION_ENTER_TREE: { - zoomicon->set_texture( get_icon("Zoom","EditorIcons") ); - //menu_track->set_icon(get_icon("AddTrack","EditorIcons")); - menu_track->get_popup()->add_icon_item(get_icon("KeyValue","EditorIcons"),"Add Normal Track",TRACK_MENU_ADD_VALUE_TRACK); - menu_track->get_popup()->add_icon_item(get_icon("KeyXform","EditorIcons"),"Add Transform Track",TRACK_MENU_ADD_TRANSFORM_TRACK); - menu_track->get_popup()->add_icon_item(get_icon("KeyCall","EditorIcons"),"Add Call Func Track",TRACK_MENU_ADD_CALL_TRACK); - menu_track->get_popup()->add_separator(); + zoomicon->set_texture( get_icon("Zoom","EditorIcons") ); + + menu_add_track->set_icon(get_icon("AddTrack","EditorIcons")); + menu_add_track->get_popup()->add_icon_item(get_icon("KeyValue","EditorIcons"),"Add Normal Track",ADD_TRACK_MENU_ADD_VALUE_TRACK); + menu_add_track->get_popup()->add_icon_item(get_icon("KeyXform","EditorIcons"),"Add Transform Track",ADD_TRACK_MENU_ADD_TRANSFORM_TRACK); + menu_add_track->get_popup()->add_icon_item(get_icon("KeyCall","EditorIcons"),"Add Call Func Track",ADD_TRACK_MENU_ADD_CALL_TRACK); + + menu_track->set_icon(get_icon("Tools","EditorIcons")); menu_track->get_popup()->add_item("Scale Selection",TRACK_MENU_SCALE); menu_track->get_popup()->add_item("Scale From Cursor",TRACK_MENU_SCALE_PIVOT); menu_track->get_popup()->add_separator(); @@ -2689,6 +2841,7 @@ void AnimationKeyEditor::_notification(int p_what) { //menu_track->get_popup()->add_submenu_item("Set Transitions..","Transitions"); //menu_track->get_popup()->add_separator(); menu_track->get_popup()->add_item("Optimize Animation",TRACK_MENU_OPTIMIZE); + menu_track->get_popup()->add_item("Clean-Up Animation",TRACK_MENU_CLEAN_UP); curve_linear->set_icon(get_icon("CurveLinear","EditorIcons")); curve_in->set_icon(get_icon("CurveIn","EditorIcons")); @@ -3511,6 +3664,7 @@ void AnimationKeyEditor::_bind_methods() { ObjectTypeDB::bind_method(_MD("_track_editor_input_event"),&AnimationKeyEditor::_track_editor_input_event); ObjectTypeDB::bind_method(_MD("_track_name_changed"),&AnimationKeyEditor::_track_name_changed); ObjectTypeDB::bind_method(_MD("_track_menu_selected"),&AnimationKeyEditor::_track_menu_selected); + ObjectTypeDB::bind_method(_MD("_menu_add_track"),&AnimationKeyEditor::_menu_add_track); ObjectTypeDB::bind_method(_MD("_menu_track"),&AnimationKeyEditor::_menu_track); ObjectTypeDB::bind_method(_MD("_clear_selection_for_anim"),&AnimationKeyEditor::_clear_selection_for_anim); ObjectTypeDB::bind_method(_MD("_select_at_anim"),&AnimationKeyEditor::_select_at_anim); @@ -3563,15 +3717,6 @@ AnimationKeyEditor::AnimationKeyEditor(UndoRedo *p_undo_redo, EditorHistory *p_h //menu->set_pos(Point2()); //add_child(menu); - menu_track = memnew( MenuButton ); - menu_track->set_text("Tracks"); - hb->add_child(menu_track); - menu_track->get_popup()->connect("item_pressed",this,"_menu_track"); - - - - hb->add_child( memnew( VSeparator ) ); - zoomicon = memnew( TextureFrame ); hb->add_child(zoomicon); zoomicon->set_tooltip("Animation zoom."); @@ -3629,6 +3774,10 @@ AnimationKeyEditor::AnimationKeyEditor(UndoRedo *p_undo_redo, EditorHistory *p_h hb->add_child( memnew( VSeparator ) ); + menu_add_track = memnew( MenuButton ); + hb->add_child(menu_add_track); + menu_add_track->get_popup()->connect("item_pressed",this,"_menu_add_track"); + menu_add_track->set_tooltip("Add new tracks."); move_up_button = memnew( ToolButton ); hb->add_child(move_up_button); @@ -3653,6 +3802,11 @@ AnimationKeyEditor::AnimationKeyEditor(UndoRedo *p_undo_redo, EditorHistory *p_h hb->add_child(memnew( VSeparator )); + menu_track = memnew( MenuButton ); + hb->add_child(menu_track); + menu_track->get_popup()->connect("item_pressed",this,"_menu_track"); + menu_track->set_tooltip("Track tools"); + edit_button = memnew( ToolButton ); edit_button->set_toggle_mode(true); edit_button->set_focus_mode(FOCUS_NONE); @@ -3847,6 +4001,32 @@ AnimationKeyEditor::AnimationKeyEditor(UndoRedo *p_undo_redo, EditorHistory *p_h add_child(call_select); call_select->set_title("Call Functions in Which Node?"); + cleanup_dialog = memnew( ConfirmationDialog ); + add_child(cleanup_dialog); + VBoxContainer *cleanup_vb = memnew( VBoxContainer ); + cleanup_dialog->add_child(cleanup_vb); + cleanup_dialog->set_child_rect(cleanup_vb); + cleanup_keys = memnew( CheckButton ); + cleanup_keys->set_text("Remove invalid keys"); + cleanup_keys->set_pressed(true); + cleanup_vb->add_child(cleanup_keys); + + cleanup_tracks = memnew( CheckButton ); + cleanup_tracks->set_text("Remove unresolved and empty tracks"); + cleanup_tracks->set_pressed(true); + cleanup_vb->add_child(cleanup_tracks); + + cleanup_all = memnew( CheckButton ); + cleanup_all->set_text("Clean-Up all animations"); + cleanup_vb->add_child(cleanup_all); + + cleanup_dialog->set_title("Clean up Animation(s) (NO UNDO!)"); + cleanup_dialog->get_ok()->set_text("Clean-Up"); + + cleanup_dialog->connect("confirmed",this,"_menu_track",varray(TRACK_MENU_CLEAN_UP_CONFIRM)); + + + } AnimationKeyEditor::~AnimationKeyEditor() { diff --git a/tools/editor/animation_editor.h b/tools/editor/animation_editor.h index 4a1cc21154..65d0fb70f8 100644 --- a/tools/editor/animation_editor.h +++ b/tools/editor/animation_editor.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -70,9 +70,9 @@ class AnimationKeyEditor : public VBoxContainer { enum { - TRACK_MENU_ADD_VALUE_TRACK, - TRACK_MENU_ADD_TRANSFORM_TRACK, - TRACK_MENU_ADD_CALL_TRACK, + ADD_TRACK_MENU_ADD_VALUE_TRACK, + ADD_TRACK_MENU_ADD_TRANSFORM_TRACK, + ADD_TRACK_MENU_ADD_CALL_TRACK, TRACK_MENU_SCALE, TRACK_MENU_SCALE_PIVOT, TRACK_MENU_MOVE_UP, @@ -89,6 +89,8 @@ class AnimationKeyEditor : public VBoxContainer { TRACK_MENU_NEXT_STEP, TRACK_MENU_PREV_STEP, TRACK_MENU_OPTIMIZE, + TRACK_MENU_CLEAN_UP, + TRACK_MENU_CLEAN_UP_CONFIRM, CURVE_SET_LINEAR, CURVE_SET_IN, CURVE_SET_OUT, @@ -190,8 +192,14 @@ class AnimationKeyEditor : public VBoxContainer { SpinBox *optimize_angular_error; SpinBox *optimize_max_angle; + ConfirmationDialog *cleanup_dialog; + CheckButton *cleanup_keys; + CheckButton *cleanup_tracks; + CheckButton *cleanup_all; + SpinBox *step; + MenuButton *menu_add_track; MenuButton *menu_track; HScrollBar *h_scroll; @@ -283,9 +291,11 @@ class AnimationKeyEditor : public VBoxContainer { void _animation_changed(); void _animation_optimize(); + void _cleanup_animation(Ref<Animation> p_animation); void _scroll_changed(double); + void _menu_add_track(int p_type); void _menu_track(int p_type); void _clear_selection_for_anim(const Ref<Animation>& p_anim); diff --git a/tools/editor/array_property_edit.cpp b/tools/editor/array_property_edit.cpp index 9cd443270b..66c2782da5 100644 --- a/tools/editor/array_property_edit.cpp +++ b/tools/editor/array_property_edit.cpp @@ -72,6 +72,15 @@ bool ArrayPropertyEdit::_set(const StringName& p_name, const Variant& p_value){ ur->add_undo_method(this,"_set_value",i,arr.get(i)); } + } else if (newsize>size && size) { + + Variant init; + Variant::CallError ce; + init = Variant::construct(arr.get(size-1).get_type(),NULL,0,ce); + for(int i=size;i<newsize;i++) { + ur->add_do_method(this,"_set_value",i,init); + } + } ur->add_do_method(this,"_notif_change"); ur->add_undo_method(this,"_notif_change"); @@ -83,6 +92,7 @@ bool ArrayPropertyEdit::_set(const StringName& p_name, const Variant& p_value){ _change_notify(); return true; } + } else if (pn.begins_with("indices")) { if (pn.find("_")!=-1) { @@ -209,6 +219,15 @@ void ArrayPropertyEdit::edit(Object* p_obj,const StringName& p_prop,Variant::Typ } +Node *ArrayPropertyEdit::get_node() { + + Object *o = ObjectDB::get_instance(obj); + if (!o) + return NULL; + + return o->cast_to<Node>(); +} + void ArrayPropertyEdit::_bind_methods() { ObjectTypeDB::bind_method(_MD("_set_size"),&ArrayPropertyEdit::_set_size); diff --git a/tools/editor/array_property_edit.h b/tools/editor/array_property_edit.h index acfb8e68ed..948b2a71a3 100644 --- a/tools/editor/array_property_edit.h +++ b/tools/editor/array_property_edit.h @@ -30,6 +30,8 @@ public: void edit(Object* p_obj, const StringName& p_prop, Variant::Type p_deftype); + Node *get_node(); + ArrayPropertyEdit(); }; diff --git a/tools/editor/call_dialog.cpp b/tools/editor/call_dialog.cpp index 0e3abcf4ef..edcd7371f2 100644 --- a/tools/editor/call_dialog.cpp +++ b/tools/editor/call_dialog.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/call_dialog.h b/tools/editor/call_dialog.h index fe69847796..2d04e7b6cd 100644 --- a/tools/editor/call_dialog.h +++ b/tools/editor/call_dialog.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/code_editor.cpp b/tools/editor/code_editor.cpp index 2ed03a1858..fe863bfebc 100644 --- a/tools/editor/code_editor.cpp +++ b/tools/editor/code_editor.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -612,13 +612,15 @@ CodeTextEditor::CodeTextEditor() { if (!font_overrode) text_editor->add_font_override("font",get_font("source","Fonts")); + text_editor->set_show_line_numbers(true); text_editor->set_brace_matching(true); + text_editor->set_auto_indent(true); line_col = memnew( Label ); add_child(line_col); line_col->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_END,135); - line_col->set_anchor_and_margin(MARGIN_TOP,ANCHOR_END,20); + line_col->set_anchor_and_margin(MARGIN_TOP,ANCHOR_END,15); line_col->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_END,1); line_col->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,5); //line_col->set_align(Label::ALIGN_RIGHT); @@ -637,7 +639,7 @@ CodeTextEditor::CodeTextEditor() { error = memnew( Label ); add_child(error); error->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_BEGIN,5); - error->set_anchor_and_margin(MARGIN_TOP,ANCHOR_END,20); + error->set_anchor_and_margin(MARGIN_TOP,ANCHOR_END,15); error->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_END,1); error->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,130); error->hide(); diff --git a/tools/editor/code_editor.h b/tools/editor/code_editor.h index 0c32aeb68f..5ed7ce9052 100644 --- a/tools/editor/code_editor.h +++ b/tools/editor/code_editor.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/connections_dialog.cpp b/tools/editor/connections_dialog.cpp index b0bacdae61..e94bc78f5d 100644 --- a/tools/editor/connections_dialog.cpp +++ b/tools/editor/connections_dialog.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -163,6 +163,7 @@ void ConnectDialog::edit(Node *p_node) { dst_path->set_text(""); dst_method->set_text(""); deferred->set_pressed(false); + oneshot->set_pressed(false); cdbinds->params.clear(); cdbinds->notify_changed(); } @@ -196,6 +197,11 @@ bool ConnectDialog::get_deferred() const { return deferred->is_pressed(); } +bool ConnectDialog::get_oneshot() const { + + return oneshot->is_pressed(); +} + StringName ConnectDialog::get_dst_method() const { String txt=dst_method->get_text(); @@ -423,12 +429,13 @@ ConnectDialog::ConnectDialog() { dstm_hb->add_child(make_callback); deferred = memnew( CheckButton ); - deferred->set_toggle_mode(true); - deferred->set_pressed(true); deferred->set_text("Deferred"); dstm_hb->add_child(deferred); - + oneshot = memnew( CheckButton ); + oneshot->set_text("Oneshot"); + dstm_hb->add_child(oneshot); + /* realtime = memnew( CheckButton ); realtime->set_anchor( MARGIN_TOP, ANCHOR_END ); @@ -496,11 +503,13 @@ void ConnectionsDialog::_connect() { StringName dst_method=connect_dialog->get_dst_method(); bool defer=connect_dialog->get_deferred(); + bool oshot=connect_dialog->get_oneshot(); Vector<Variant> binds = connect_dialog->get_binds(); StringArray args = it->get_metadata(0).operator Dictionary()["args"]; + int flags = CONNECT_PERSIST | (defer?CONNECT_DEFERRED:0) | (oshot?CONNECT_ONESHOT:0); undo_redo->create_action("Connect '"+signal+"' to '"+String(dst_method)+"'"); - undo_redo->add_do_method(node,"connect",signal,target,dst_method,binds,CONNECT_PERSIST | (defer?CONNECT_DEFERRED:0)); + undo_redo->add_do_method(node,"connect",signal,target,dst_method,binds,flags); undo_redo->add_undo_method(node,"disconnect",signal,target,dst_method); undo_redo->add_do_method(this,"update_tree"); undo_redo->add_undo_method(this,"update_tree"); @@ -731,6 +740,8 @@ void ConnectionsDialog::update_tree() { String path = String(node->get_path_to(target))+" :: "+c.method+"()"; if (c.flags&CONNECT_DEFERRED) path+=" (deferred)"; + if (c.flags&CONNECT_ONESHOT) + path+=" (oneshot)"; if (c.binds.size()) { path+=" binds( "; diff --git a/tools/editor/connections_dialog.h b/tools/editor/connections_dialog.h index 68b13bf07a..d5e228e799 100644 --- a/tools/editor/connections_dialog.h +++ b/tools/editor/connections_dialog.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -58,6 +58,7 @@ class ConnectDialog : public ConfirmationDialog { //MenuButton *dst_method_list; OptionButton *type_list; CheckButton *deferred; + CheckButton *oneshot; CheckButton *make_callback; PropertyEditor *bind_editor; Node *node; @@ -80,6 +81,7 @@ public: NodePath get_dst_path() const; StringName get_dst_method() const; bool get_deferred() const; + bool get_oneshot() const; Vector<Variant> get_binds() const; void set_dst_method(const StringName& p_method); void set_dst_node(Node* p_node); diff --git a/tools/editor/console.cpp b/tools/editor/console.cpp deleted file mode 100644 index 0c98f05706..0000000000 --- a/tools/editor/console.cpp +++ /dev/null @@ -1,386 +0,0 @@ -/*************************************************************************/ -/* console.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* http://www.godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ -#include "console.h" -#include "os/os.h" -#include "os/keyboard.h" - -#include "editor_icons.h" -#include "scene/gui/label.h" -#include "globals.h" - - -void Console::_stats_update_timer_callback() { - - if (!status->is_visible()) - return; - - VisualServer *vs = VisualServer::get_singleton(); - - stats.render_objects_in_frame->set_text(1,String::num(vs->get_render_info( VisualServer::INFO_OBJECTS_IN_FRAME ) ) ); - stats.material_changes_in_frame->set_text(1,String::num(vs->get_render_info( VisualServer::INFO_MATERIAL_CHANGES_IN_FRAME ) ) ); - - int64_t total_vmem = vs->get_render_info( VisualServer::INFO_USAGE_VIDEO_MEM_TOTAL ); - if (total_vmem<0) - stats.usage_video_mem_total->set_text(1, "Unknown"); - else - stats.usage_video_mem_total->set_text(1,String::humanize_size( total_vmem ) ); - - stats.usage_video_mem_used->set_text(1,String::humanize_size( vs->get_render_info( VisualServer::INFO_VIDEO_MEM_USED ) ) ); - stats.usage_texture_mem_used->set_text(1,String::humanize_size( vs->get_render_info( VisualServer::INFO_TEXTURE_MEM_USED ) ) ); - stats.usage_vertex_mem_used->set_text(1,String::humanize_size( vs->get_render_info( VisualServer::INFO_VERTEX_MEM_USED ) ) ); - - - stats.usage_static_memory_total->set_text(1,String::humanize_size( Memory::get_static_mem_available() ) ); - stats.usage_static_memory->set_text(1,String::humanize_size( Memory::get_static_mem_usage() ) ); - stats.usage_dynamic_memory_total->set_text(1,String::humanize_size( Memory::get_dynamic_mem_available() ) ); - stats.usage_dynamic_memory->set_text(1,String::humanize_size( Memory::get_dynamic_mem_usage() ) ); - stats.usage_objects_instanced->set_text(1,String::num( ObjectDB::get_object_count()) ); - - -} - -void Console::_print_handle(void *p_this,const String& p_string) { - - - return; - Console *self = (Console*)p_this; - - OutputQueue oq; - oq.text=p_string; - oq.type=OutputStrings::LINE_NORMAL; - - - if (self->output_queue_mutex) - self->output_queue_mutex->lock(); - - self->output_queue.push_back(oq); - - if (self->output_queue_mutex) - self->output_queue_mutex->unlock(); - -} -void Console::_error_handle(void *p_this,const char*p_function,const char* p_file,int p_line,const char *p_error, const char *p_explanation,ErrorHandlerType p_type) { - - - Console *self = (Console*)p_this; - - OutputQueue oq; - oq.text="ERROR: "+String(p_file)+":"+itos(p_line)+", in function: "+String(p_function); - oq.text+="\n "+String(p_error)+"."; - if (p_explanation && p_explanation[0]) - oq.text+="\n Reason: "+String(p_explanation); - oq.text+="\n"; - oq.type=OutputStrings::LINE_ERROR; - - - if (self->output_queue_mutex) - self->output_queue_mutex->lock(); - - self->output_queue.push_back(oq); - - if (self->output_queue_mutex) - self->output_queue_mutex->unlock(); - - -} - -void Console::_window_input_event(InputEvent p_event) { - - Control::_window_input_event(p_event); - - if (p_event.type==InputEvent::KEY && p_event.key.pressed) { - - if (p_event.key.scancode==KEY_QUOTELEFT && p_event.key.mod.control) { - - if (is_visible()) - hide(); - else { - globals_property_editor->edit( NULL ); - globals_property_editor->edit( Globals::get_singleton() ); - show(); - }; - } - - if (p_event.key.scancode==KEY_ESCAPE && !window_has_modal_stack() && is_visible()) { - hide(); - get_tree()->call_group(0,"windows","_cancel_input_ID",p_event.ID); - } - - - } -} - -void Console::_window_resize_event() { - -// Control::_window_resize_event(); - _resized(); -} - - -void Console::_resized() { - - set_pos( Point2( 0, OS::get_singleton()->get_video_mode().height-height) ); - set_size( Size2( OS::get_singleton()->get_video_mode().width, height) ); -} - -void Console::_notification(int p_what) { - - switch(p_what) { - - case NOTIFICATION_ENTER_TREE: { - - _resized(); - show(); - globals_property_editor->edit( Globals::get_singleton() ); - - } break; - - case NOTIFICATION_PROCESS: { - //pop messies - - if (output_queue_mutex) - output_queue_mutex->lock(); - - while(output_queue.size()) { - - OutputQueue q = output_queue.front()->get(); - if (q.type==OutputStrings::LINE_ERROR || q.type==OutputStrings::LINE_WARNING) - errors->add_line(q.text,q.meta,q.type); - output->add_line(q.text,q.meta,q.type); - output_queue.pop_front(); - } - - if (output_queue_mutex) - output_queue_mutex->unlock(); - - } break; - case NOTIFICATION_DRAW: { - - RID ci = get_canvas_item(); - get_stylebox("panel","Panel")->draw(ci,Rect2(Point2(),get_size())); - - } break; - } -} - - -void Console::_close_pressed() { - - hide(); -} - -void Console::_inspector_node_selected() { - - - Node *node = inspect_tree_editor->get_selected(); - - if (!node) - inspect_property_editor->edit(NULL); - else { - - inspect_history.add_object(node->get_instance_ID()); - - inspect_property_editor->edit(node); - } - -} - -void Console::_bind_methods() { - - ObjectTypeDB::bind_method("_stats_update_timer_callback",&Console::_stats_update_timer_callback); - ObjectTypeDB::bind_method("_close_pressed",&Console::_close_pressed); - ObjectTypeDB::bind_method("_inspector_node_selected",&Console::_inspector_node_selected); -} - - -Console::Console() { - - Ref<Theme> theme( memnew( Theme ) ); - set_theme( theme ); - editor_register_icons(theme); - - height=300; - tabs = memnew( TabContainer ); - tabs->set_tab_align(TabContainer::ALIGN_LEFT); - add_child(tabs); - tabs->set_area_as_parent_rect(); - - output = memnew( OutputStrings ); - output->set_name("Output"); - tabs->add_child(output); - errors = memnew( OutputStrings ); - errors->set_name("Errors"); - tabs->add_child(errors); - status = memnew( Control ); - status->set_name("Stats"); - tabs->add_child(status); - inspect = memnew( Control ); - inspect->set_name("Inspect"); - tabs->add_child(inspect); - globals = memnew( Control ); - globals->set_name("Globals"); - tabs->add_child(globals); - - // stats - - stats_tree = memnew( Tree ); - stats_tree->set_hide_root(true); - stats_tree->set_columns(2); - status->add_child(stats_tree); - stats_tree->set_anchor( MARGIN_BOTTOM, ANCHOR_END ); - stats_tree->set_anchor( MARGIN_RIGHT, ANCHOR_RATIO ); - stats_tree->set_margin( MARGIN_RIGHT, 0.5 ); - stats_tree->set_begin( Point2( 20,25 ) ); - stats_tree->set_end( Point2( 0.5,5 ) ); - - Label *stats_label = memnew( Label ); - stats_label->set_text("Engine Statistics:"); - stats_label->set_pos( Point2( 5,5 ) ); - status->add_child(stats_label); - - TreeItem *stats_tree_root = stats_tree->create_item(NULL); - - { - //system items - TreeItem *system_item = stats_tree->create_item(stats_tree_root); - system_item->set_text(0,"System"); - - stats.usage_static_memory_total = stats_tree->create_item(system_item); - stats.usage_static_memory_total->set_text(0,"Total Static Mem");; - stats.usage_static_memory = stats_tree->create_item(system_item); - stats.usage_static_memory->set_text(0,"Static Mem Usage");; - stats.usage_dynamic_memory_total = stats_tree->create_item(system_item); - stats.usage_dynamic_memory_total->set_text(0,"Total Dynamic Mem");; - stats.usage_dynamic_memory = stats_tree->create_item(system_item); - stats.usage_dynamic_memory->set_text(0,"Dynamic Mem Usage"); - stats.usage_objects_instanced = stats_tree->create_item(system_item); - stats.usage_objects_instanced->set_text(0,"Instanced Objects"); - - //render items - TreeItem *render_item = stats_tree->create_item(stats_tree_root); - render_item->set_text(0,"Render"); - stats.render_objects_in_frame = stats_tree->create_item(render_item); - stats.render_objects_in_frame->set_text(0,"Visible Objects"); - stats.material_changes_in_frame = stats_tree->create_item(render_item); - stats.material_changes_in_frame->set_text(0,"Material Changes"); - stats.usage_video_mem_total = stats_tree->create_item(render_item); - stats.usage_video_mem_total->set_text(0,"Total Video Mem"); - stats.usage_texture_mem_used = stats_tree->create_item(render_item); - stats.usage_texture_mem_used->set_text(0,"Texture Mem Usage"); - stats.usage_vertex_mem_used = stats_tree->create_item(render_item); - stats.usage_vertex_mem_used->set_text(0,"Vertex Mem Usage"); - stats.usage_video_mem_used = stats_tree->create_item(render_item); - stats.usage_video_mem_used->set_text(0,"Combined Mem Usage"); - } - - { - - inspect_tree_editor = memnew( SceneTreeEditor ); - inspect_tree_editor->set_anchor( MARGIN_RIGHT, ANCHOR_RATIO ); - inspect_tree_editor->set_anchor( MARGIN_BOTTOM, ANCHOR_END ); - inspect_tree_editor->set_begin( Point2( 20, 5 ) ); - inspect_tree_editor->set_end( Point2( 0.49, 5 ) ); - inspect->add_child(inspect_tree_editor); - - inspect_property_editor = memnew( PropertyEditor ); - inspect_property_editor->set_anchor( MARGIN_LEFT, ANCHOR_RATIO ); - inspect_property_editor->set_anchor( MARGIN_RIGHT, ANCHOR_END ); - inspect_property_editor->set_anchor( MARGIN_BOTTOM, ANCHOR_END ); - inspect_property_editor->set_begin( Point2( 0.51, 5 ) ); - inspect_property_editor->set_end( Point2( 5, 5 ) ); - inspect->add_child(inspect_property_editor); - } - - - { //globals - - globals_property_editor = memnew( PropertyEditor ); - globals_property_editor->set_anchor( MARGIN_RIGHT, ANCHOR_END ); - globals_property_editor->set_anchor( MARGIN_BOTTOM, ANCHOR_END ); - globals_property_editor->set_begin( Point2( 15, 5 ) ); - globals_property_editor->set_end( Point2( 5, 5 ) ); - globals_property_editor->get_top_label()->set_text("Globals Editor:"); - globals->add_child(globals_property_editor); - - } - - -#ifndef NO_THREADS - output_queue_mutex = Mutex::create(); -#else - output_queue_mutex = NULL; -#endif - - - hide(); - set_process(true); - - close = memnew( Button ); - add_child(close); - close->set_anchor( MARGIN_LEFT, ANCHOR_END); - close->set_anchor( MARGIN_RIGHT, ANCHOR_END); - close->set_begin( Point2( 25, 3 ) ); - close->set_end( Point2( 5, 3 ) ); - close->set_flat(true); - close->connect("pressed", this,"_close_pressed"); - - - close->set_icon( get_icon("close","Icons") ); -// force_top_viewport(true); - - - err_handler.userdata=this; - err_handler.errfunc=_error_handle; - add_error_handler(&err_handler); - - print_handler.userdata=this; - print_handler.printfunc=_print_handle; - add_print_handler(&print_handler); - - Timer *timer = memnew( Timer ); - add_child(timer); - timer->set_wait_time(1); - timer->start(); - timer->connect("timeout", this,"_stats_update_timer_callback"); - inspect_tree_editor->connect("node_selected", this,"_inspector_node_selected"); - - - -} - - -Console::~Console() { - - if (output_queue_mutex) - memdelete(output_queue_mutex); - - remove_error_handler(&err_handler); - remove_print_handler(&print_handler); - -} diff --git a/tools/editor/create_dialog.cpp b/tools/editor/create_dialog.cpp index a9119349c8..0f39d72308 100644 --- a/tools/editor/create_dialog.cpp +++ b/tools/editor/create_dialog.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/create_dialog.h b/tools/editor/create_dialog.h index f200e1caf5..6f959fd467 100644 --- a/tools/editor/create_dialog.h +++ b/tools/editor/create_dialog.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/default_saver.cpp b/tools/editor/default_saver.cpp index c865adb1eb..611232e04b 100644 --- a/tools/editor/default_saver.cpp +++ b/tools/editor/default_saver.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/default_saver.h b/tools/editor/default_saver.h index 4e11ff5592..2b1a1edb23 100644 --- a/tools/editor/default_saver.h +++ b/tools/editor/default_saver.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/dependency_editor.cpp b/tools/editor/dependency_editor.cpp index c04e82a08a..7e63cfb1b4 100644 --- a/tools/editor/dependency_editor.cpp +++ b/tools/editor/dependency_editor.cpp @@ -510,3 +510,184 @@ DependencyErrorDialog::DependencyErrorDialog() { set_title("Errors loading!"); } + +////////////////////////////////////////////////////////////////////// + + + +void OrphanResourcesDialog::ok_pressed() { + + paths.clear(); + + _find_to_delete(files->get_root(),paths); + if (paths.empty()) + return; + + delete_confirm->set_text("Permanently Delete "+itos(paths.size())+" Item(s) ? (No Undo!!)"); + delete_confirm->popup_centered_minsize(); +} + +bool OrphanResourcesDialog::_fill_owners(EditorFileSystemDirectory *efsd,HashMap<String,int>& refs,TreeItem* p_parent){ + + + if (!efsd) + return false; + + bool has_childs=false; + + for(int i=0;i<efsd->get_subdir_count();i++) { + + TreeItem *dir_item=NULL; + if (p_parent) { + dir_item = files->create_item(p_parent); + dir_item->set_text(0,efsd->get_subdir(i)->get_name()); + dir_item->set_icon(0,get_icon("folder","FileDialog")); + + } + bool children = _fill_owners(efsd->get_subdir(i),refs,dir_item); + + if (p_parent) { + if (!children) { + memdelete(dir_item); + } else { + has_childs=true; + } + } + + } + + + for(int i=0;i<efsd->get_file_count();i++) { + + if (!p_parent) { + Vector<String> deps = efsd->get_file_deps(i); + //print_line(":::"+efsd->get_file_path(i)); + for(int j=0;j<deps.size();j++) { + + if (!refs.has(deps[j])) { + refs[deps[j]]=1; + } + } + } else { + + String path = efsd->get_file_path(i); + if (!refs.has(path)) { + TreeItem *ti=files->create_item(p_parent); + ti->set_cell_mode(0,TreeItem::CELL_MODE_CHECK); + ti->set_text(0,efsd->get_file(i)); + ti->set_editable(0,true); + + String type=efsd->get_file_type(i); + + Ref<Texture> icon; + if (has_icon(type,"EditorIcons")) { + icon=get_icon(type,"EditorIcons"); + } else { + icon=get_icon("Object","EditorIcons"); + } + ti->set_icon(0,icon); + int ds = efsd->get_file_deps(i).size(); + ti->set_text(1,itos(ds)); + if (ds) { + ti->add_button(1,get_icon("Visible","EditorIcons")); + } + ti->set_metadata(0,path); + has_childs=true; + } + } + + } + + return has_childs; +} + + +void OrphanResourcesDialog::refresh() { + HashMap<String,int> refs; + _fill_owners(EditorFileSystem::get_singleton()->get_filesystem(),refs,NULL); + files->clear(); + TreeItem *root=files->create_item(); + _fill_owners(EditorFileSystem::get_singleton()->get_filesystem(),refs,root); +} + + +void OrphanResourcesDialog::show(){ + + refresh(); + popup_centered_ratio(); +} + + +void OrphanResourcesDialog::_find_to_delete(TreeItem* p_item,List<String>& paths) { + + while(p_item) { + + if (p_item->get_cell_mode(0)==TreeItem::CELL_MODE_CHECK && p_item->is_checked(0)) { + paths.push_back(p_item->get_metadata(0)); + } + + if (p_item->get_children()) { + _find_to_delete(p_item->get_children(),paths); + } + + p_item=p_item->get_next(); + } + + +} + +void OrphanResourcesDialog::_delete_confirm() { + + DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + for (List<String>::Element *E=paths.front();E;E=E->next()) { + + da->remove(E->get()); + EditorFileSystem::get_singleton()->update_file(E->get()); + } + memdelete(da); + refresh(); +} + +void OrphanResourcesDialog::_button_pressed(Object *p_item,int p_column, int p_id) { + + TreeItem *ti=p_item->cast_to<TreeItem>(); + + String path = ti->get_metadata(0); + dep_edit->edit(path); + +} + +void OrphanResourcesDialog::_bind_methods() { + + ObjectTypeDB::bind_method(_MD("_delete_confirm"),&OrphanResourcesDialog::_delete_confirm); + ObjectTypeDB::bind_method(_MD("_button_pressed"),&OrphanResourcesDialog::_button_pressed); + +} + +OrphanResourcesDialog::OrphanResourcesDialog(){ + + VBoxContainer *vbc = memnew( VBoxContainer ); + add_child(vbc); + set_child_rect(vbc); + files = memnew( Tree ); + files->set_columns(2); + files->set_column_titles_visible(true); + files->set_column_min_width(1,100); + files->set_column_expand(0,true); + files->set_column_expand(1,false); + files->set_column_title(0,"Resource"); + files->set_column_title(1,"Owns"); + files->set_hide_root(true); + vbc->add_margin_child("Resources Without Explicit Ownership:",files,true); + set_title("Orphan Resource Explorer"); + delete_confirm = memnew( ConfirmationDialog ); + delete_confirm->set_text("Delete selected files?"); + get_ok()->set_text("Delete"); + add_child(delete_confirm); + dep_edit = memnew( DependencyEditor ); + add_child(dep_edit); + files->connect("button_pressed",this,"_button_pressed"); + delete_confirm->connect("confirmed",this,"_delete_confirm"); + set_hide_on_ok(false); + +} diff --git a/tools/editor/dependency_editor.h b/tools/editor/dependency_editor.h index 1c328e7a93..c372025ca0 100644 --- a/tools/editor/dependency_editor.h +++ b/tools/editor/dependency_editor.h @@ -91,4 +91,29 @@ public: DependencyErrorDialog(); }; + + +class OrphanResourcesDialog : public ConfirmationDialog { + OBJ_TYPE(OrphanResourcesDialog,ConfirmationDialog); + + DependencyEditor *dep_edit; + Tree *files; + ConfirmationDialog *delete_confirm; + void ok_pressed(); + + bool _fill_owners(EditorFileSystemDirectory *efsd, HashMap<String,int>& refs, TreeItem *p_parent); + + List<String> paths; + void _find_to_delete(TreeItem* p_item,List<String>& paths); + void _delete_confirm(); + void _button_pressed(Object *p_item,int p_column, int p_id); + + void refresh(); + static void _bind_methods(); +public: + + void show(); + OrphanResourcesDialog(); +}; + #endif // DEPENDENCY_EDITOR_H diff --git a/tools/editor/doc_code_font.h b/tools/editor/doc_code_font.h index 91f67c4a41..879c873ea1 100644 --- a/tools/editor/doc_code_font.h +++ b/tools/editor/doc_code_font.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/doc_font.h b/tools/editor/doc_font.h index f2e5e7950b..a3c3b58b21 100644 --- a/tools/editor/doc_font.h +++ b/tools/editor/doc_font.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/doc_title_font.h b/tools/editor/doc_title_font.h index fb6b4eaf5b..75a3f049f0 100644 --- a/tools/editor/doc_title_font.h +++ b/tools/editor/doc_title_font.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/editor_data.cpp b/tools/editor/editor_data.cpp index 673ee30adb..d79c1ff466 100644 --- a/tools/editor/editor_data.cpp +++ b/tools/editor/editor_data.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -31,6 +31,9 @@ #include "editor_settings.h" #include "os/dir_access.h" #include "io/resource_loader.h" +#include "scene/resources/packed_scene.h" +#include "os/file_access.h" +#include "editor_node.h" void EditorHistory::_cleanup_history() { @@ -338,6 +341,14 @@ void EditorData::set_editor_states(const Dictionary& p_states) { } +void EditorData::notify_edited_scene_changed() { + + for(int i=0;i<editor_plugins.size();i++) { + + editor_plugins[i]->edited_scene_changed(); + } +} + void EditorData::clear_editor_states() { for(int i=0;i<editor_plugins.size();i++) { @@ -485,6 +496,93 @@ void EditorData::remove_scene(int p_idx){ edited_scene.remove(p_idx); } + +bool EditorData::_find_updated_instances(Node* p_root,Node *p_node,Set<String> &checked_paths) { + + if (p_root!=p_node && p_node->get_owner()!=p_root && !p_root->is_editable_instance(p_node->get_owner())) + return false; + + Ref<SceneState> ss; + + if (p_node==p_root) { + ss=p_node->get_scene_inherited_state(); + } else if (p_node->get_filename()!=String()){ + ss=p_node->get_scene_instance_state(); + } + + if (ss.is_valid()) { + String path = ss->get_path(); + + if (!checked_paths.has(path)) { + + uint64_t modified_time = FileAccess::get_modified_time(path); + if (modified_time!=ss->get_last_modified_time()) { + return true; //external scene changed + } + + checked_paths.insert(path); + } + + } + + for(int i=0;i<p_node->get_child_count();i++) { + + bool found = _find_updated_instances(p_root,p_node->get_child(i),checked_paths); + if (found) + return true; + } + + return false; +} + + +bool EditorData::check_and_update_scene(int p_idx) { + + ERR_FAIL_INDEX_V(p_idx,edited_scene.size(),false); + if (!edited_scene[p_idx].root) + return false; + + Set<String> checked_scenes; + + + bool must_reload = _find_updated_instances(edited_scene[p_idx].root,edited_scene[p_idx].root,checked_scenes); + + if (must_reload) { + Ref<PackedScene> pscene; + pscene.instance(); + + EditorProgress ep("update_scene","Updating Scene",2); + ep.step("Storing local changes..",0); + //pack first, so it stores diffs to previous version of saved scene + Error err = pscene->pack(edited_scene[p_idx].root); + ERR_FAIL_COND_V(err!=OK,false); + ep.step("Updating scene..",1); + Node *new_scene = pscene->instance(true); + ERR_FAIL_COND_V(!new_scene,false); + + //transfer selection + List<Node*> new_selection; + for (List<Node*>::Element *E=edited_scene[p_idx].selection.front();E;E=E->next()) { + NodePath p = edited_scene[p_idx].root->get_path_to(E->get()); + Node *new_node = new_scene->get_node(p); + if (new_node) + new_selection.push_back(new_node); + } + + new_scene->set_filename( edited_scene[p_idx].root->get_filename() ); + + memdelete(edited_scene[p_idx].root); + edited_scene[p_idx].root=new_scene; + edited_scene[p_idx].selection=new_selection; + + return true; + + } + + return false; + +} + int EditorData::get_edited_scene() const { return current_edited_scene; diff --git a/tools/editor/editor_data.h b/tools/editor/editor_data.h index c5ee83ae63..7dafeeea04 100644 --- a/tools/editor/editor_data.h +++ b/tools/editor/editor_data.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -144,6 +144,8 @@ private: Vector<EditedScene> edited_scene; int current_edited_scene; + bool _find_updated_instances(Node* p_root,Node *p_node,Set<String> &checked_paths); + public: EditorPlugin* get_editor(Object *p_object); @@ -193,6 +195,7 @@ public: void clear_edited_scenes(); void set_edited_scene_live_edit_root(const NodePath& p_root); NodePath get_edited_scene_live_edit_root(); + bool check_and_update_scene(int p_idx); void set_plugin_window_layout(Ref<ConfigFile> p_layout); @@ -200,6 +203,7 @@ public: void save_edited_scene_state(EditorSelection *p_selection,EditorHistory *p_history,const Dictionary& p_custom); Dictionary restore_edited_scene_state(EditorSelection *p_selection, EditorHistory *p_history); + void notify_edited_scene_changed(); EditorData(); diff --git a/tools/editor/editor_dir_dialog.cpp b/tools/editor/editor_dir_dialog.cpp index a8421acff8..8512154485 100644 --- a/tools/editor/editor_dir_dialog.cpp +++ b/tools/editor/editor_dir_dialog.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -205,31 +205,36 @@ void EditorDirDialog::_bind_methods() { EditorDirDialog::EditorDirDialog() { + updating=false; + set_title("Choose a Directory"); + set_hide_on_ok(false); + tree = memnew( Tree ); add_child(tree); set_child_rect(tree); - updating=false; - get_ok()->set_text("Choose"); - set_hide_on_ok(false); - - + tree->connect("item_activated",this,"_ok"); makedir = add_button("Create Folder",OS::get_singleton()->get_swap_ok_cancel()?true:false,"makedir"); makedir->connect("pressed",this,"_make_dir"); makedialog = memnew( ConfirmationDialog ); makedialog->set_title("Create Folder"); + add_child(makedialog); + VBoxContainer *makevb= memnew( VBoxContainer ); makedialog->add_child(makevb); makedialog->set_child_rect(makevb); + makedirname = memnew( LineEdit ); makevb->add_margin_child("Name:",makedirname); - add_child(makedialog); makedialog->register_text_enter(makedirname); makedialog->connect("confirmed",this,"_make_dir_confirm"); + mkdirerr = memnew( AcceptDialog ); mkdirerr->set_text("Could not create folder."); add_child(mkdirerr); + get_ok()->set_text("Choose"); + } diff --git a/tools/editor/editor_dir_dialog.h b/tools/editor/editor_dir_dialog.h index 8ac83b86e8..1c2593219c 100644 --- a/tools/editor/editor_dir_dialog.h +++ b/tools/editor/editor_dir_dialog.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/editor_file_dialog.cpp b/tools/editor/editor_file_dialog.cpp index c62347d129..28a9b63412 100644 --- a/tools/editor/editor_file_dialog.cpp +++ b/tools/editor/editor_file_dialog.cpp @@ -6,6 +6,8 @@ #include "editor_resource_preview.h" #include "editor_settings.h" #include "scene/gui/margin_container.h" +#include "os/file_access.h" + EditorFileDialog::GetIconFunc EditorFileDialog::get_icon_func=NULL; EditorFileDialog::GetIconFunc EditorFileDialog::get_large_icon_func=NULL; @@ -27,14 +29,14 @@ void EditorFileDialog::_notification(int p_what) { dir_prev->set_icon(get_icon("ArrowLeft","EditorIcons")); dir_next->set_icon(get_icon("ArrowRight","EditorIcons")); dir_up->set_icon(get_icon("ArrowUp","EditorIcons")); + refresh->set_icon(get_icon("Reload","EditorIcons")); favorite->set_icon(get_icon("Favorites","EditorIcons")); fav_up->set_icon(get_icon("MoveUp","EditorIcons")); fav_down->set_icon(get_icon("MoveDown","EditorIcons")); fav_rm->set_icon(get_icon("RemoveSmall","EditorIcons")); - } - if (p_what==NOTIFICATION_PROCESS) { + } else if (p_what==NOTIFICATION_PROCESS) { if (preview_waiting) { preview_wheel_timeout-=get_process_delta_time(); @@ -47,12 +49,14 @@ void EditorFileDialog::_notification(int p_what) { preview_wheel_timeout=0.1; } } - } - - if (p_what==NOTIFICATION_DRAW) { + } else if (p_what==NOTIFICATION_DRAW) { //RID ci = get_canvas_item(); //get_stylebox("panel","PopupMenu")->draw(ci,Rect2(Point2(),get_size())); + } else if (p_what==EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) { + + set_show_hidden_files(EditorSettings::get_singleton()->get("file_dialog/show_hidden_files")); + set_display_mode((DisplayMode)EditorSettings::get_singleton()->get("file_dialog/display_mode").operator int()); } } @@ -189,6 +193,9 @@ void EditorFileDialog::_thumbnail_done(const String& p_path,const Ref<Texture>& void EditorFileDialog::_request_single_thumbnail(const String& p_path) { + if (!FileAccess::exists(p_path)) + return; + EditorResourcePreview::get_singleton()->queue_resource_preview(p_path,this,"_thumbnail_done",p_path); //print_line("want file "+p_path); set_process(true); @@ -430,6 +437,8 @@ void EditorFileDialog::update_file_list() { } + String cdir = dir_access->get_current_dir(); + bool skip_pp = access==ACCESS_RESOURCES && cdir=="res://"; dir_access->list_dir_begin(); @@ -450,7 +459,7 @@ void EditorFileDialog::update_file_list() { if (show_hidden || !ishidden) { if (!isdir) files.push_back(item); - else + else if (item!=".." || !skip_pp) dirs.push_back(item); } } @@ -1012,7 +1021,9 @@ void EditorFileDialog::_go_forward(){ } -bool EditorFileDialog::default_show_hidden_files=true; +bool EditorFileDialog::default_show_hidden_files=false; + +EditorFileDialog::DisplayMode EditorFileDialog::default_display_mode=DISPLAY_THUMBNAILS; void EditorFileDialog::set_display_mode(DisplayMode p_mode) { @@ -1060,7 +1071,7 @@ void EditorFileDialog::_bind_methods() { ObjectTypeDB::bind_method(_MD("get_vbox:VBoxContainer"),&EditorFileDialog::get_vbox); ObjectTypeDB::bind_method(_MD("set_access","access"),&EditorFileDialog::set_access); ObjectTypeDB::bind_method(_MD("get_access"),&EditorFileDialog::get_access); - ObjectTypeDB::bind_method(_MD("set_show_hidden_files"),&EditorFileDialog::set_show_hidden_files); + ObjectTypeDB::bind_method(_MD("set_show_hidden_files","show"),&EditorFileDialog::set_show_hidden_files); ObjectTypeDB::bind_method(_MD("is_showing_hidden_files"),&EditorFileDialog::is_showing_hidden_files); ObjectTypeDB::bind_method(_MD("_select_drive"),&EditorFileDialog::_select_drive); ObjectTypeDB::bind_method(_MD("_make_dir"),&EditorFileDialog::_make_dir); @@ -1113,6 +1124,10 @@ void EditorFileDialog::set_default_show_hidden_files(bool p_show) { default_show_hidden_files=p_show; } +void EditorFileDialog::set_default_display_mode(DisplayMode p_mode) { + default_display_mode=p_mode; +} + void EditorFileDialog::_save_to_recent() { String dir = get_current_dir(); @@ -1141,8 +1156,8 @@ void EditorFileDialog::_save_to_recent() { EditorFileDialog::EditorFileDialog() { - show_hidden_files=true; - display_mode=DISPLAY_THUMBNAILS; + show_hidden_files=default_show_hidden_files; + display_mode=default_display_mode; local_history_pos=0; VBoxContainer *vbc = memnew( VBoxContainer ); @@ -1170,6 +1185,10 @@ EditorFileDialog::EditorFileDialog() { pathhb->add_child(dir); dir->set_h_size_flags(SIZE_EXPAND_FILL); + refresh = memnew( ToolButton ); + refresh->connect("pressed",this,"_update_file_list"); + pathhb->add_child(refresh); + favorite = memnew( ToolButton ); favorite->set_toggle_mode(true); favorite->connect("toggled",this,"_favorite_toggled"); @@ -1178,11 +1197,13 @@ EditorFileDialog::EditorFileDialog() { mode_thumbnails = memnew( ToolButton ); mode_thumbnails->connect("pressed",this,"set_display_mode",varray(DISPLAY_THUMBNAILS)); mode_thumbnails->set_toggle_mode(true); - mode_thumbnails->set_pressed(true); + mode_thumbnails->set_pressed(display_mode==DISPLAY_THUMBNAILS); pathhb->add_child(mode_thumbnails); + mode_list = memnew( ToolButton ); mode_list->connect("pressed",this,"set_display_mode",varray(DISPLAY_LIST)); mode_list->set_toggle_mode(true); + mode_list->set_pressed(display_mode==DISPLAY_LIST); pathhb->add_child(mode_list); drives = memnew( OptionButton ); diff --git a/tools/editor/editor_file_dialog.h b/tools/editor/editor_file_dialog.h index 6cfd970516..db3201e5c4 100644 --- a/tools/editor/editor_file_dialog.h +++ b/tools/editor/editor_file_dialog.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -108,6 +108,7 @@ private: ToolButton *mode_list; + ToolButton *refresh; ToolButton *favorite; ToolButton *fav_up; @@ -127,6 +128,7 @@ private: int preview_wheel_index; float preview_wheel_timeout; static bool default_show_hidden_files; + static DisplayMode default_display_mode; bool show_hidden_files; DisplayMode display_mode; @@ -210,6 +212,7 @@ public: bool is_showing_hidden_files() const; static void set_default_show_hidden_files(bool p_show); + static void set_default_display_mode(DisplayMode p_mode); void invalidate(); diff --git a/tools/editor/editor_file_system.cpp b/tools/editor/editor_file_system.cpp index 33e4a15c85..c7c1a48e34 100644 --- a/tools/editor/editor_file_system.cpp +++ b/tools/editor/editor_file_system.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -37,6 +37,31 @@ EditorFileSystem *EditorFileSystem::singleton=NULL; +void EditorFileSystemDirectory::sort_files() { + + files.sort_custom<FileInfoSort>(); +} + +int EditorFileSystemDirectory::find_file_index(const String& p_file) const { + + for(int i=0;i<files.size();i++) { + if (files[i]->file==p_file) + return i; + } + return -1; + +} +int EditorFileSystemDirectory::find_dir_index(const String& p_dir) const{ + + + for(int i=0;i<subdirs.size();i++) { + if (subdirs[i]->name==p_dir) + return i; + } + + return -1; +} + int EditorFileSystemDirectory::get_subdir_count() const { @@ -59,7 +84,7 @@ String EditorFileSystemDirectory::get_file(int p_idx) const{ ERR_FAIL_INDEX_V(p_idx,files.size(),""); - return files[p_idx].file; + return files[p_idx]->file; } String EditorFileSystemDirectory::get_path() const { @@ -91,22 +116,22 @@ String EditorFileSystemDirectory::get_file_path(int p_idx) const { bool EditorFileSystemDirectory::get_file_meta(int p_idx) const { ERR_FAIL_INDEX_V(p_idx,files.size(),""); - return files[p_idx].meta.enabled; + return files[p_idx]->meta.enabled; } Vector<String> EditorFileSystemDirectory::get_file_deps(int p_idx) const { ERR_FAIL_INDEX_V(p_idx,files.size(),Vector<String>()); - return files[p_idx].meta.deps; + return files[p_idx]->meta.deps; } Vector<String> EditorFileSystemDirectory::get_missing_sources(int p_idx) const { ERR_FAIL_INDEX_V(p_idx,files.size(),Vector<String>()); Vector<String> missing; - for(int i=0;i<files[p_idx].meta.sources.size();i++) { - if (files[p_idx].meta.sources[i].missing) - missing.push_back(files[p_idx].meta.sources[i].path); + for(int i=0;i<files[p_idx]->meta.sources.size();i++) { + if (files[p_idx]->meta.sources[i].missing) + missing.push_back(files[p_idx]->meta.sources[i].path); } return missing; @@ -116,8 +141,8 @@ Vector<String> EditorFileSystemDirectory::get_missing_sources(int p_idx) const { bool EditorFileSystemDirectory::is_missing_sources(int p_idx) const { ERR_FAIL_INDEX_V(p_idx,files.size(),false); - for(int i=0;i<files[p_idx].meta.sources.size();i++) { - if (files[p_idx].meta.sources[i].missing) + for(int i=0;i<files[p_idx]->meta.sources.size();i++) { + if (files[p_idx]->meta.sources[i].missing) return true; } @@ -127,7 +152,7 @@ bool EditorFileSystemDirectory::is_missing_sources(int p_idx) const { StringName EditorFileSystemDirectory::get_file_type(int p_idx) const { ERR_FAIL_INDEX_V(p_idx,files.size(),""); - return files[p_idx].type; + return files[p_idx]->type; } String EditorFileSystemDirectory::get_name() { @@ -157,11 +182,17 @@ void EditorFileSystemDirectory::_bind_methods() { EditorFileSystemDirectory::EditorFileSystemDirectory() { + modified_time=0; parent=NULL; } EditorFileSystemDirectory::~EditorFileSystemDirectory() { + for(int i=0;i<files.size();i++) { + + memdelete(files[i]); + } + for(int i=0;i<subdirs.size();i++) { memdelete(subdirs[i]); @@ -173,19 +204,6 @@ EditorFileSystemDirectory::~EditorFileSystemDirectory() { - - -EditorFileSystem::DirItem::~DirItem() { - - for(int i=0;i<dirs.size();i++) { - memdelete(dirs[i]); - } - - for(int i=0;i<files.size();i++) { - memdelete(files[i]); - } -} - EditorFileSystemDirectory::ImportMeta EditorFileSystem::_get_meta(const String& p_path) { Ref<ResourceImportMetadata> imd = ResourceLoader::load_import_metadata(p_path); @@ -214,160 +232,16 @@ EditorFileSystemDirectory::ImportMeta EditorFileSystem::_get_meta(const String& return m; } -EditorFileSystem::DirItem* EditorFileSystem::_scan_dir(DirAccess *da,Set<String> &extensions,String p_name,float p_from,float p_range,const String& p_path,HashMap<String,FileCache> &file_cache,HashMap<String,DirCache> &dir_cache,EditorProgressBG& p_prog) { - if (abort_scan) - return NULL; - - if (p_path!=String()) { - if (FileAccess::exists(("res://"+p_path).plus_file("engine.cfg"))) { - return NULL; - } - } - - List<String> dirs; - List<String> files; - Set<String> pngs; - - String path=p_path; - if (path.ends_with("/")) - path=path.substr(0,path.length()-1); - String global_path = Globals::get_singleton()->get_resource_path().plus_file(path); - - path="res://"+path; - uint64_t mtime = FileAccess::get_modified_time(global_path); - - DirCache *dc = dir_cache.getptr(path); - - - if (false && dc && dc->modification_time==mtime) { - //use the cached files, since directory did not change - for (Set<String>::Element *E=dc->subdirs.front();E;E=E->next()) { - dirs.push_back(E->get()); - } - for (Set<String>::Element *E=dc->files.front();E;E=E->next()) { - files.push_back(E->get()); - } - - } else { - //use the filesystem, some files may have changed - Error err = da->change_dir(global_path); - if (err!=OK) { - print_line("Can't change to: "+path); - ERR_FAIL_COND_V(err!=OK,NULL); - } +void EditorFileSystem::_scan_filesystem() { - - da->list_dir_begin(); - while (true) { - - bool isdir; - String f = da->get_next(&isdir); - if (f=="") - break; - if (isdir) { - dirs.push_back(f); - } else { - String ext = f.extension().to_lower(); - if (extensions.has(ext)) - files.push_back(f); - - } - - } - - da->list_dir_end(); - files.sort(); - dirs.sort(); - - } - - - - //print_line(da->get_current_dir()+": dirs: "+itos(dirs.size())+" files:"+itos(files.size()) ); - - //find subdirs - Vector<DirItem*> subdirs; - - //String current = da->get_current_dir(); - float idx=0; - for (List<String>::Element *E=dirs.front();E;E=E->next(),idx+=1.0) { - - String d = E->get(); - if (d.begins_with(".")) //ignore hidden and . / .. - continue; - - //ERR_CONTINUE( da->change_dir(d)!= OK ); - DirItem *sdi = _scan_dir(da,extensions,d,p_from+(idx/dirs.size())*p_range,p_range/dirs.size(),p_path+d+"/",file_cache,dir_cache,p_prog); - if (sdi) { - subdirs.push_back(sdi); - } - //da->change_dir(current); - } - - - if (subdirs.empty() && files.empty()) { - total=p_from+p_range; - p_prog.step(total*100); - return NULL; //give up, nothing to do here - } - - DirItem *di = memnew( DirItem ); - di->path=path; - di->name=p_name; - di->dirs=subdirs; - di->modified_time=mtime; - - //add files - for (List<String>::Element *E=files.front();E;E=E->next()) { - - SceneItem * si = memnew( SceneItem ); - si->file=E->get(); - si->path="res://"+p_path+si->file; - FileCache *fc = file_cache.getptr(si->path); - uint64_t mt = FileAccess::get_modified_time(si->path); - - if (fc && fc->modification_time == mt) { - - si->meta=fc->meta; - si->type=fc->type; - si->modified_time=fc->modification_time; - } else { - si->meta=_get_meta(si->path); - si->type=ResourceLoader::get_resource_type(si->path); - si->modified_time=mt; - - } - - if (si->meta.enabled) { - md_count++; - if (_check_meta_sources(si->meta)) { - sources_changed.push_back(si->path); - } - } - di->files.push_back(si); - } - - total=p_from+p_range; - p_prog.step(total*100); - - return di; -} - - -void EditorFileSystem::_scan_scenes() { - - ERR_FAIL_COND(!scanning || scandir); + ERR_FAIL_COND(!scanning || new_filesystem); //read .fscache - HashMap<String,FileCache> file_cache; - HashMap<String,DirCache> dir_cache; - DirCache *dc=NULL; String cpath; sources_changed.clear(); - - + file_cache.clear(); String project=Globals::get_singleton()->get_resource_path(); @@ -387,26 +261,7 @@ void EditorFileSystem::_scan_scenes() { ERR_CONTINUE( split.size() != 3); String name = split[1]; - dir_cache[name]=DirCache(); - dc=&dir_cache[name]; - dc->modification_time=split[2].to_int64(); - - if (name!="res://") { - - cpath=name+"/"; - - int sp=name.find_last("/"); - if (sp==5) - sp=6; - String pd = name.substr(0,sp); - DirCache *dcp = dir_cache.getptr(pd); - ERR_CONTINUE(!dcp); - dcp->subdirs.insert(name.get_file()); - } else { - - cpath=name; - } - + cpath=name; } else { Vector<String> split = l.split("::"); @@ -414,12 +269,8 @@ void EditorFileSystem::_scan_scenes() { String name = split[0]; String file; - if (!name.begins_with("res://")) { - file=name; - name=cpath+name; - } else { - file=name.get_file(); - } + file=name; + name=cpath.plus_file(name); FileCache fc; fc.type=split[1]; @@ -453,8 +304,6 @@ void EditorFileSystem::_scan_scenes() { file_cache[name]=fc; - ERR_CONTINUE(!dc); - dc->files.insert(file); } } @@ -465,39 +314,31 @@ void EditorFileSystem::_scan_scenes() { + EditorProgressBG scan_progress("efs","ScanFS",1000); + ScanProgress sp; + sp.low=0; + sp.hi=1; + sp.progress=&scan_progress; - total=0; - DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - //da->change_dir( Globals::get_singleton()->get_resource_path() ); + new_filesystem = memnew( EditorFileSystemDirectory ); + new_filesystem->parent=NULL; + DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES); + d->change_dir("res://"); + _scan_new_dir(new_filesystem,d,sp); - List<String> extensionsl; - ResourceLoader::get_recognized_extensions_for_type("",&extensionsl); - Set<String> extensions; - for(List<String>::Element *E = extensionsl.front();E;E=E->next()) { + file_cache.clear(); //clear caches, no longer needed - extensions.insert(E->get()); - } - - EditorProgressBG scan_progress("efs","ScanFS",100); - - md_count=0; - scandir=_scan_dir(da,extensions,"",0,1,"",file_cache,dir_cache,scan_progress); - memdelete(da); - if (abort_scan && scandir) { - memdelete(scandir); - scandir=NULL; - - } + memdelete(d); //save back the findings // String fscache = EditorSettings::get_singleton()->get_project_settings_path().plus_file("file_cache"); f=FileAccess::open(fscache,FileAccess::WRITE); - _save_type_cache_fs(scandir,f); + _save_filesystem_cache(new_filesystem,f); f->close(); memdelete(f); @@ -510,7 +351,95 @@ void EditorFileSystem::_scan_scenes() { void EditorFileSystem::_thread_func(void *_userdata) { EditorFileSystem *sd = (EditorFileSystem*)_userdata; - sd->_scan_scenes(); + sd->_scan_filesystem(); + +} + +bool EditorFileSystem::_update_scan_actions() { + + sources_changed.clear(); + + bool fs_changed=false; + + for (List<ItemAction>::Element *E=scan_actions.front();E;E=E->next()) { + + ItemAction&ia = E->get(); + + switch(ia.action) { + case ItemAction::ACTION_NONE: { + + } break; + case ItemAction::ACTION_DIR_ADD: { + + //print_line("*ACTION ADD DIR: "+ia.new_dir->get_name()); + int idx=0; + for(int i=0;i<ia.dir->subdirs.size();i++) { + + if (ia.new_dir->name<ia.dir->subdirs[i]->name) + break; + idx++; + } + if (idx==ia.dir->subdirs.size()) { + ia.dir->subdirs.push_back(ia.new_dir); + } else { + ia.dir->subdirs.insert(idx,ia.new_dir); + } + + fs_changed=true; + } break; + case ItemAction::ACTION_DIR_REMOVE: { + + ERR_CONTINUE(!ia.dir->parent); + //print_line("*ACTION REMOVE DIR: "+ia.dir->get_name()); + ia.dir->parent->subdirs.erase(ia.dir); + memdelete( ia.dir ); + fs_changed=true; + } break; + case ItemAction::ACTION_FILE_ADD: { + + int idx=0; + for(int i=0;i<ia.dir->files.size();i++) { + + if (ia.new_file->file<ia.dir->files[i]->file) + break; + idx++; + } + if (idx==ia.dir->files.size()) { + ia.dir->files.push_back(ia.new_file); + } else { + ia.dir->files.insert(idx,ia.new_file); + } + + fs_changed=true; + //print_line("*ACTION ADD FILE: "+ia.new_file->file); + + } break; + case ItemAction::ACTION_FILE_REMOVE: { + + int idx = ia.dir->find_file_index(ia.file); + ERR_CONTINUE(idx==-1); + memdelete( ia.dir->files[idx] ); + ia.dir->files.remove(idx); + + fs_changed=true; + //print_line("*ACTION REMOVE FILE: "+ia.file); + + } break; + case ItemAction::ACTION_FILE_SOURCES_CHANGED: { + + int idx = ia.dir->find_file_index(ia.file); + ERR_CONTINUE(idx==-1); + String full_path = ia.dir->get_file_path(idx); + sources_changed.push_back(full_path); + + } break; + + } + } + + scan_actions.clear(); + + return fs_changed; } @@ -526,19 +455,15 @@ void EditorFileSystem::scan() { abort_scan=false; if (!use_threads) { scanning=true; - _scan_scenes(); - if (rootdir) - memdelete(rootdir); - rootdir=scandir; + scan_total=0; + _scan_filesystem(); if (filesystem) memdelete(filesystem); // file_type_cache.clear(); - filesystem=_update_tree(rootdir); - - if (rootdir) - memdelete(rootdir); - rootdir=NULL; - scanning=false; + filesystem=new_filesystem; + new_filesystem=NULL; + _update_scan_actions(); + scanning=false; emit_signal("filesystem_changed"); emit_signal("sources_changed",sources_changed.size()>0); @@ -548,6 +473,7 @@ void EditorFileSystem::scan() { set_process(true); Thread::Settings s; scanning=true; + scan_total=0; s.priority=Thread::PRIORITY_LOW; thread = Thread::create(_thread_func,this,s); //tree->hide(); @@ -559,14 +485,10 @@ void EditorFileSystem::scan() { } -bool EditorFileSystem::_check_meta_sources(EditorFileSystemDirectory::ImportMeta & p_meta,EditorProgressBG *ep) { +bool EditorFileSystem::_check_meta_sources(EditorFileSystemDirectory::ImportMeta & p_meta) { if (p_meta.enabled) { - if (ep) { - ep->step(ss_amount++); - } - for(int j=0;j<p_meta.sources.size();j++) { @@ -584,9 +506,9 @@ bool EditorFileSystem::_check_meta_sources(EditorFileSystemDirectory::ImportMeta if (mt!=p_meta.sources[j].modified_time) { //scan String md5 = FileAccess::get_md5(src); - print_line("checking: "+src); - print_line("md5: "+md5); - print_line("vs: "+p_meta.sources[j].md5); + //print_line("checking: "+src); + //print_line("md5: "+md5); + //print_line("vs: "+p_meta.sources[j].md5); if (md5!=p_meta.sources[j].md5) { //really changed return true; @@ -599,18 +521,300 @@ bool EditorFileSystem::_check_meta_sources(EditorFileSystemDirectory::ImportMeta return false; } -void EditorFileSystem::_scan_sources(EditorFileSystemDirectory *p_dir,EditorProgressBG *ep) { +void EditorFileSystem::ScanProgress::update(int p_current,int p_total) const { + + float ratio = low + ((hi-low)/p_total)*p_current; + progress->step(ratio*1000); + EditorFileSystem::singleton->scan_total=ratio; +} + +EditorFileSystem::ScanProgress EditorFileSystem::ScanProgress::get_sub(int p_current,int p_total) const{ + + ScanProgress sp=*this; + float slice = (sp.hi-sp.low)/p_total; + sp.low+=slice*p_current; + sp.hi=slice; + return sp; + + +} + + +void EditorFileSystem::_scan_new_dir(EditorFileSystemDirectory *p_dir,DirAccess *da,const ScanProgress& p_progress) { + + List<String> dirs; + List<String> files; + + String cd = da->get_current_dir(); + + p_dir->modified_time = FileAccess::get_modified_time(cd); + + + da->list_dir_begin(); + while (true) { + + bool isdir; + String f = da->get_next(&isdir); + if (f=="") + break; + + if (isdir) { + + if (f.begins_with(".")) //ignore hidden and . / .. + continue; + + if (FileAccess::exists(cd.plus_file(f).plus_file("engine.cfg"))) // skip if another project inside this + continue; + + dirs.push_back(f); + + } else { + + files.push_back(f); + } + + } + + da->list_dir_end(); + + dirs.sort(); + files.sort(); + + int total = dirs.size()+files.size(); + int idx=0; + + for (List<String>::Element *E=dirs.front();E;E=E->next(),idx++) { + + if (da->change_dir(E->get())==OK) { + + EditorFileSystemDirectory *efd = memnew( EditorFileSystemDirectory ); + + efd->parent=p_dir; + efd->name=E->get(); + + _scan_new_dir(efd,da,p_progress.get_sub(idx,total)); + + int idx=0; + for(int i=0;i<p_dir->subdirs.size();i++) { + + if (efd->name<p_dir->subdirs[i]->name) + break; + idx++; + } + if (idx==p_dir->subdirs.size()) { + p_dir->subdirs.push_back(efd); + } else { + p_dir->subdirs.insert(idx,efd); + } + + da->change_dir(".."); + } else { + ERR_PRINTS("Can't go into subdir: "+E->get()); + } + + p_progress.update(idx,total); + + } + + for (List<String>::Element*E=files.front();E;E=E->next(),idx++) { + + String ext = E->get().extension().to_lower(); + if (!valid_extensions.has(ext)) + continue; //invalid + + EditorFileSystemDirectory::FileInfo *fi = memnew( EditorFileSystemDirectory::FileInfo ); + fi->file=E->get(); + + String path = cd.plus_file(fi->file); + + FileCache *fc = file_cache.getptr(path); + uint64_t mt = FileAccess::get_modified_time(path); + + if (fc && fc->modification_time == mt) { + + fi->meta=fc->meta; + fi->type=fc->type; + fi->modified_time=fc->modification_time; + } else { + fi->meta=_get_meta(path); + fi->type=ResourceLoader::get_resource_type(path); + fi->modified_time=mt; + + } + + if (fi->meta.enabled) { + if (_check_meta_sources(fi->meta)) { + ItemAction ia; + ia.action=ItemAction::ACTION_FILE_SOURCES_CHANGED; + ia.dir=p_dir; + ia.file=E->get(); + scan_actions.push_back(ia); + } + } + + p_dir->files.push_back(fi); + p_progress.update(idx,total); + } + +} + + +void EditorFileSystem::_scan_fs_changes(EditorFileSystemDirectory *p_dir,const ScanProgress& p_progress) { + + uint64_t current_mtime = FileAccess::get_modified_time(p_dir->get_path()); + + bool updated_dir=false; + + //print_line("dir: "+p_dir->get_path()+" MODTIME: "+itos(p_dir->modified_time)+" CTIME: "+itos(current_mtime)); + + if (current_mtime!=p_dir->modified_time) { + + updated_dir=true; + p_dir->modified_time=current_mtime; + //ooooops, dir changed, see what's going on + + //first mark everything as veryfied + + for(int i=0;i<p_dir->files.size();i++) { + + p_dir->files[i]->verified=false; + } + + for(int i=0;i<p_dir->subdirs.size();i++) { + + p_dir->get_subdir(i)->verified=false; + } + + //then scan files and directories and check what's different + + DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + String cd = p_dir->get_path(); + da->change_dir(cd); + da->list_dir_begin(); + while (true) { + + bool isdir; + String f = da->get_next(&isdir); + if (f=="") + break; + + if (isdir) { + + if (f.begins_with(".")) //ignore hidden and . / .. + continue; + + int idx = p_dir->find_dir_index(f); + if (idx==-1) { + + if (FileAccess::exists(cd.plus_file(f).plus_file("engine.cfg"))) // skip if another project inside this + continue; + + EditorFileSystemDirectory *efd = memnew( EditorFileSystemDirectory ); + + efd->parent=p_dir; + efd->name=f; + DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES); + d->change_dir(cd.plus_file(f)); + _scan_new_dir(efd,d,p_progress.get_sub(1,1)); + memdelete(d); + + + ItemAction ia; + ia.action=ItemAction::ACTION_DIR_ADD; + ia.dir=p_dir; + ia.file=f; + ia.new_dir=efd; + scan_actions.push_back(ia); + } else { + p_dir->subdirs[idx]->verified=true; + } + + + } else { + String ext = f.extension().to_lower(); + if (!valid_extensions.has(ext)) + continue; //invalid + + int idx = p_dir->find_file_index(f); + + if (idx==-1) { + //never seen this file, add actition to add it + EditorFileSystemDirectory::FileInfo *fi = memnew( EditorFileSystemDirectory::FileInfo ); + fi->file=f; + + String path = cd.plus_file(fi->file); + fi->modified_time=FileAccess::get_modified_time(path); + fi->meta=_get_meta(path); + fi->type=ResourceLoader::get_resource_type(path); + + { + ItemAction ia; + ia.action=ItemAction::ACTION_FILE_ADD; + ia.dir=p_dir; + ia.file=f; + ia.new_file=fi; + scan_actions.push_back(ia); + } + + //take the chance and scan sources + if (_check_meta_sources(fi->meta)) { + + ItemAction ia; + ia.action=ItemAction::ACTION_FILE_SOURCES_CHANGED; + ia.dir=p_dir; + ia.file=f; + scan_actions.push_back(ia); + } + + } else { + p_dir->files[idx]->verified=true; + } + + + } + + } + da->list_dir_end(); + memdelete(da); + + + + + } for(int i=0;i<p_dir->files.size();i++) { - if (_check_meta_sources(p_dir->files[i].meta,ep)) { - sources_changed.push_back(p_dir->get_file_path(i)); + if (updated_dir && !p_dir->files[i]->verified) { + //this file was removed, add action to remove it + ItemAction ia; + ia.action=ItemAction::ACTION_FILE_REMOVE; + ia.dir=p_dir; + ia.file=p_dir->files[i]->file; + scan_actions.push_back(ia); + continue; + + } + if (_check_meta_sources(p_dir->files[i]->meta)) { + ItemAction ia; + ia.action=ItemAction::ACTION_FILE_SOURCES_CHANGED; + ia.dir=p_dir; + ia.file=p_dir->files[i]->file; + scan_actions.push_back(ia); } } for(int i=0;i<p_dir->subdirs.size();i++) { - _scan_sources(p_dir->get_subdir(i),ep); + if (updated_dir && !p_dir->subdirs[i]->verified) { + //this directory was removed, add action to remove it + ItemAction ia; + ia.action=ItemAction::ACTION_DIR_REMOVE; + ia.dir=p_dir->subdirs[i]; + scan_actions.push_back(ia); + continue; + + } + _scan_fs_changes(p_dir->get_subdir(i),p_progress); } } @@ -619,9 +823,12 @@ void EditorFileSystem::_thread_func_sources(void *_userdata) { EditorFileSystem *efs = (EditorFileSystem*)_userdata; if (efs->filesystem) { - EditorProgressBG pr("sources","ScanSources",efs->md_count); - efs->ss_amount=0; - efs->_scan_sources(efs->filesystem,&pr); + EditorProgressBG pr("sources","ScanSources",1000); + ScanProgress sp; + sp.progress=≺ + sp.hi=1; + sp.low=0; + efs->_scan_fs_changes(efs->filesystem,sp); } efs->scanning_sources_done=true; } @@ -643,8 +850,17 @@ void EditorFileSystem::scan_sources() { abort_scan=false; if (!use_threads) { - if (filesystem) - _scan_sources(filesystem,NULL); + if (filesystem) { + EditorProgressBG pr("sources","ScanSources",1000); + ScanProgress sp; + sp.progress=≺ + sp.hi=1; + sp.low=0; + scan_total=0; + _scan_fs_changes(filesystem,sp); + if (_update_scan_actions()) + emit_signal("filesystem_changed"); + } scanning_sources=false; scanning_sources_done=true; emit_signal("sources_changed",sources_changed.size()>0); @@ -652,8 +868,8 @@ void EditorFileSystem::scan_sources() { ERR_FAIL_COND(thread_sources); set_process(true); + scan_total=0; Thread::Settings s; - ss_amount=0; s.priority=Thread::PRIORITY_LOW; thread_sources = Thread::create(_thread_func_sources,this,s); //tree->hide(); @@ -665,53 +881,14 @@ void EditorFileSystem::scan_sources() { } -EditorFileSystemDirectory* EditorFileSystem::_update_tree(DirItem *p_item) { - - EditorFileSystemDirectory *efd = memnew( EditorFileSystemDirectory ); - - if (!p_item) - return efd; //empty likely - efd->name=p_item->name; - - for(int i=0;i<p_item->files.size();i++) { - - String s = p_item->files[i]->type; - //if (p_item->files[i]->meta) - // s="*"+s; - -// file_type_cache[p_item->files[i]->path]=s; - if (p_item->files[i]->type=="") - continue; //ignore because it's invalid - EditorFileSystemDirectory::FileInfo fi; - fi.file=p_item->files[i]->file; - fi.type=p_item->files[i]->type; - fi.meta=p_item->files[i]->meta; - fi.modified_time=p_item->files[i]->modified_time; - - efd->files.push_back(fi); - - } - - for(int i=0;i<p_item->dirs.size();i++) { - - EditorFileSystemDirectory *efsd =_update_tree(p_item->dirs[i]); - efsd->parent=efd; - efd->subdirs.push_back( efsd ); - - } - - - return efd; -} - void EditorFileSystem::_notification(int p_what) { switch(p_what) { case NOTIFICATION_ENTER_TREE: { - _load_type_cache(); - scan(); + + scan(); } break; case NOTIFICATION_EXIT_TREE: { if (use_threads && thread) { @@ -727,13 +904,13 @@ void EditorFileSystem::_notification(int p_what) { set_process(false); } - if (rootdir) - memdelete(rootdir); - rootdir=NULL; if (filesystem) memdelete(filesystem); + if (new_filesystem) + memdelete(new_filesystem); filesystem=NULL; + new_filesystem=NULL; } break; case NOTIFICATION_PROCESS: { @@ -751,6 +928,8 @@ void EditorFileSystem::_notification(int p_what) { Thread::wait_to_finish(thread_sources); memdelete(thread_sources); thread_sources=NULL; + if (_update_scan_actions()) + emit_signal("filesystem_changed"); //print_line("sources changed: "+itos(sources_changed.size())); emit_signal("sources_changed",sources_changed.size()>0); } @@ -758,21 +937,14 @@ void EditorFileSystem::_notification(int p_what) { set_process(false); - if (rootdir) - memdelete(rootdir); if (filesystem) memdelete(filesystem); - rootdir=scandir; - scandir=NULL; -// file_type_cache.clear(); - filesystem=_update_tree(rootdir); - - if (rootdir) - memdelete(rootdir); - rootdir=NULL; + filesystem=new_filesystem; + new_filesystem=NULL; Thread::wait_to_finish(thread); memdelete(thread); thread=NULL; + _update_scan_actions(); emit_signal("filesystem_changed"); emit_signal("sources_changed",sources_changed.size()>0); //print_line("initial sources changed: "+itos(sources_changed.size())); @@ -794,7 +966,7 @@ bool EditorFileSystem::is_scanning() const { } float EditorFileSystem::get_scanning_progress() const { - return total; + return scan_total; } EditorFileSystemDirectory *EditorFileSystem::get_filesystem() { @@ -802,12 +974,12 @@ EditorFileSystemDirectory *EditorFileSystem::get_filesystem() { return filesystem; } -void EditorFileSystem::_save_type_cache_fs(DirItem *p_dir,FileAccess *p_file) { +void EditorFileSystem::_save_filesystem_cache(EditorFileSystemDirectory*p_dir,FileAccess *p_file) { if (!p_dir) return; //none - p_file->store_line("::"+p_dir->path+"::"+String::num(p_dir->modified_time)); + p_file->store_line("::"+p_dir->get_path()+"::"+String::num(p_dir->modified_time)); for(int i=0;i<p_dir->files.size();i++) { @@ -832,126 +1004,96 @@ void EditorFileSystem::_save_type_cache_fs(DirItem *p_dir,FileAccess *p_file) { p_file->store_line(s); } - for(int i=0;i<p_dir->dirs.size();i++) { + for(int i=0;i<p_dir->subdirs.size();i++) { - _save_type_cache_fs(p_dir->dirs[i],p_file); + _save_filesystem_cache(p_dir->subdirs[i],p_file); } } -void EditorFileSystem::_load_type_cache(){ - - GLOBAL_LOCK_FUNCTION - - -#if 0 - //this is not good, removed for now as it interferes with metadata stored in files - - String project=Globals::get_singleton()->get_resource_path(); - FileAccess *f =FileAccess::open(project+"/types.cache",FileAccess::READ); - - if (!f) { - - WARN_PRINT("Can't open types.cache."); - return; - } - - file_type_cache.clear(); - while(!f->eof_reached()) { - - String path=f->get_line(); - if (f->eof_reached()) - break; - String type=f->get_line(); - file_type_cache[path]=type; - } - - memdelete(f); -#endif -} bool EditorFileSystem::_find_file(const String& p_file,EditorFileSystemDirectory ** r_d, int &r_file_pos) const { //todo make faster - if (!filesystem || scanning) - return false; + if (!filesystem || scanning) + return false; - String f = Globals::get_singleton()->localize_path(p_file); + String f = Globals::get_singleton()->localize_path(p_file); - if (!f.begins_with("res://")) - return false; - f=f.substr(6,f.length()); - f=f.replace("\\","/"); + if (!f.begins_with("res://")) + return false; + f=f.substr(6,f.length()); + f=f.replace("\\","/"); - Vector<String> path = f.split("/"); + Vector<String> path = f.split("/"); - if (path.size()==0) - return false; - String file=path[path.size()-1]; - path.resize(path.size()-1); + if (path.size()==0) + return false; + String file=path[path.size()-1]; + path.resize(path.size()-1); - EditorFileSystemDirectory *fs=filesystem; + EditorFileSystemDirectory *fs=filesystem; - for(int i=0;i<path.size();i++) { + for(int i=0;i<path.size();i++) { - int idx=-1; - for(int j=0;j<fs->get_subdir_count();j++) { + int idx=-1; + for(int j=0;j<fs->get_subdir_count();j++) { - if (fs->get_subdir(j)->get_name()==path[i]) { - idx=j; - break; - } - } + if (fs->get_subdir(j)->get_name()==path[i]) { + idx=j; + break; + } + } - if (idx==-1) { - //does not exist, create i guess? - EditorFileSystemDirectory *efsd = memnew( EditorFileSystemDirectory ); - efsd->name=path[i]; - int idx2=0; - for(int j=0;j<fs->get_subdir_count();j++) { + if (idx==-1) { + //does not exist, create i guess? + EditorFileSystemDirectory *efsd = memnew( EditorFileSystemDirectory ); + efsd->name=path[i]; + int idx2=0; + for(int j=0;j<fs->get_subdir_count();j++) { - if (efsd->name<fs->get_subdir(j)->get_name()) - break; - idx2++; - } + if (efsd->name<fs->get_subdir(j)->get_name()) + break; + idx2++; + } - if (idx2==fs->get_subdir_count()) - fs->subdirs.push_back(efsd); - else - fs->subdirs.insert(idx2,efsd); - fs=efsd; - } else { + if (idx2==fs->get_subdir_count()) + fs->subdirs.push_back(efsd); + else + fs->subdirs.insert(idx2,efsd); + fs=efsd; + } else { - fs=fs->get_subdir(idx); + fs=fs->get_subdir(idx); + } } - } - int cpos=-1; - for(int i=0;i<fs->files.size();i++) { + int cpos=-1; + for(int i=0;i<fs->files.size();i++) { - if (fs->files[i].file==file) { - cpos=i; - break; + if (fs->files[i]->file==file) { + cpos=i; + break; + } } - } r_file_pos=cpos; *r_d=fs; - if (cpos!=-1) { + if (cpos!=-1) { - return true; - } else { + return true; + } else { - return false; - } + return false; + } } @@ -967,7 +1109,7 @@ String EditorFileSystem::get_file_type(const String& p_file) const { } - return fs->files[cpos].type; + return fs->files[cpos]->type; } @@ -1024,16 +1166,16 @@ EditorFileSystemDirectory *EditorFileSystem::get_path(const String& p_path) { void EditorFileSystem::_resource_saved(const String& p_path){ - print_line("resource saved: "+p_path); + //print_line("resource saved: "+p_path); EditorFileSystem::get_singleton()->update_file(p_path); } String EditorFileSystem::_find_first_from_source(EditorFileSystemDirectory* p_dir,const String &p_src) const { for(int i=0;i<p_dir->files.size();i++) { - for(int j=0;j<p_dir->files[i].meta.sources.size();j++) { + for(int j=0;j<p_dir->files[i]->meta.sources.size();j++) { - if (p_dir->files[i].meta.sources[j].path==p_src) + if (p_dir->files[i]->meta.sources[j].path==p_src) return p_dir->get_file_path(i); } } @@ -1070,6 +1212,7 @@ void EditorFileSystem::update_file(const String& p_file) { if (!FileAccess::exists(p_file)) { //was removed + memdelete( fs->files[cpos] ); fs->files.remove(cpos); call_deferred("emit_signal","filesystem_changed"); //update later return; @@ -1083,13 +1226,13 @@ void EditorFileSystem::update_file(const String& p_file) { int idx=0; for(int i=0;i<fs->files.size();i++) { - if (p_file<fs->files[i].file) + if (p_file<fs->files[i]->file) break; idx++; } - EditorFileSystemDirectory::FileInfo fi; - fi.file=p_file.get_file(); + EditorFileSystemDirectory::FileInfo *fi = memnew( EditorFileSystemDirectory::FileInfo ); + fi->file=p_file.get_file(); if (idx==fs->files.size()) { fs->files.push_back(fi); @@ -1102,10 +1245,10 @@ void EditorFileSystem::update_file(const String& p_file) { } - print_line("UPDATING: "+p_file); - fs->files[cpos].type=type; - fs->files[cpos].modified_time=FileAccess::get_modified_time(p_file); - fs->files[cpos].meta=_get_meta(p_file); + //print_line("UPDATING: "+p_file); + fs->files[cpos]->type=type; + fs->files[cpos]->modified_time=FileAccess::get_modified_time(p_file); + fs->files[cpos]->meta=_get_meta(p_file); call_deferred("emit_signal","filesystem_changed"); //update later @@ -1128,15 +1271,22 @@ EditorFileSystem::EditorFileSystem() { thread = NULL; scanning=false; - scandir=NULL; - rootdir=NULL; use_threads=true; thread_sources=NULL; + new_filesystem=NULL; scanning_sources=false; ResourceSaver::set_save_callback(_resource_saved); + List<String> extensionsl; + ResourceLoader::get_recognized_extensions_for_type("",&extensionsl); + for(List<String>::Element *E = extensionsl.front();E;E=E->next()) { + + valid_extensions.insert(E->get()); + } + + scan_total=0; } EditorFileSystem::~EditorFileSystem() { diff --git a/tools/editor/editor_file_system.h b/tools/editor/editor_file_system.h index f79dd209ef..d11fa0cfb1 100644 --- a/tools/editor/editor_file_system.h +++ b/tools/editor/editor_file_system.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -42,6 +42,8 @@ class EditorFileSystemDirectory : public Object { OBJ_TYPE( EditorFileSystemDirectory,Object ); String name; + uint64_t modified_time; + bool verified; //used for checking changes EditorFileSystemDirectory *parent; Vector<EditorFileSystemDirectory*> subdirs; @@ -68,11 +70,20 @@ class EditorFileSystemDirectory : public Object { String file; StringName type; uint64_t modified_time; - ImportMeta meta; + bool verified; //used for checking changes + + }; + + struct FileInfoSort { + bool operator()(const FileInfo *p_a,const FileInfo *p_b) const { + return p_a->file<p_b->file; + } }; - Vector<FileInfo> files; + void sort_files(); + + Vector<FileInfo*> files; static void _bind_methods(); @@ -96,6 +107,9 @@ public: EditorFileSystemDirectory *get_parent(); + int find_file_index(const String& p_file) const; + int find_dir_index(const String& p_dir) const; + EditorFileSystemDirectory(); ~EditorFileSystemDirectory(); @@ -107,45 +121,47 @@ class EditorFileSystem : public Node { _THREAD_SAFE_CLASS_ - struct SceneItem { + + struct ItemAction { + + enum Action { + ACTION_NONE, + ACTION_DIR_ADD, + ACTION_DIR_REMOVE, + ACTION_FILE_ADD, + ACTION_FILE_REMOVE, + ACTION_FILE_SOURCES_CHANGED + }; + + Action action; + EditorFileSystemDirectory *dir; String file; - String path; - String type; - uint64_t modified_time; - EditorFileSystemDirectory::ImportMeta meta; - }; + EditorFileSystemDirectory *new_dir; + EditorFileSystemDirectory::FileInfo *new_file; - struct DirItem { + ItemAction() { action=ACTION_NONE; dir=NULL; new_dir=NULL; new_file=NULL; } - uint64_t modified_time; - String path; - String name; - Vector<DirItem*> dirs; - Vector<SceneItem*> files; - ~DirItem(); }; - float total; bool use_threads; Thread *thread; static void _thread_func(void *_userdata); - DirItem *scandir; - DirItem *rootdir; + EditorFileSystemDirectory *new_filesystem; bool abort_scan; bool scanning; + float scan_total; - EditorFileSystemDirectory* _update_tree(DirItem *p_item); - void _scan_scenes(); - void _load_type_cache(); + void _scan_filesystem(); EditorFileSystemDirectory *filesystem; static EditorFileSystem *singleton; + /* Used for reading the filesystem cache file */ struct FileCache { String type; @@ -154,34 +170,43 @@ class EditorFileSystem : public Node { Vector<String> deps; }; - struct DirCache { + HashMap<String,FileCache> file_cache; - uint64_t modification_time; - Set<String> files; - Set<String> subdirs; - }; + struct ScanProgress { + float low; + float hi; + mutable EditorProgressBG *progress; + void update(int p_current,int p_total) const; + ScanProgress get_sub(int p_current,int p_total) const; + }; static EditorFileSystemDirectory::ImportMeta _get_meta(const String& p_path); - bool _check_meta_sources(EditorFileSystemDirectory::ImportMeta & p_meta,EditorProgressBG *ep=NULL); + bool _check_meta_sources(EditorFileSystemDirectory::ImportMeta & p_meta); - DirItem* _scan_dir(DirAccess *da,Set<String> &extensions,String p_name,float p_from,float p_range,const String& p_path,HashMap<String,FileCache> &file_cache,HashMap<String,DirCache> &dir_cache,EditorProgressBG& p_prog); - void _save_type_cache_fs(DirItem *p_dir,FileAccess *p_file); + void _save_filesystem_cache(EditorFileSystemDirectory *p_dir,FileAccess *p_file); bool _find_file(const String& p_file,EditorFileSystemDirectory ** r_d, int &r_file_pos) const; - void _scan_sources(EditorFileSystemDirectory *p_dir,EditorProgressBG *ep); + void _scan_fs_changes(EditorFileSystemDirectory *p_dir, const ScanProgress &p_progress); int md_count; + Set<String> valid_extensions; + + void _scan_new_dir(EditorFileSystemDirectory *p_dir,DirAccess *da,const ScanProgress& p_progress); Thread *thread_sources; bool scanning_sources; bool scanning_sources_done; - int ss_amount; + static void _thread_func_sources(void *_userdata); + List<String> sources_changed; + List<ItemAction> scan_actions; + + bool _update_scan_actions(); static void _resource_saved(const String& p_path); String _find_first_from_source(EditorFileSystemDirectory* p_dir,const String &p_src) const; diff --git a/tools/editor/editor_fonts.cpp b/tools/editor/editor_fonts.cpp index f145f1ddef..b12b041f16 100644 --- a/tools/editor/editor_fonts.cpp +++ b/tools/editor/editor_fonts.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/editor_fonts.h b/tools/editor/editor_fonts.h index cc990a560c..3b2422c3e3 100644 --- a/tools/editor/editor_fonts.h +++ b/tools/editor/editor_fonts.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/editor_help.cpp b/tools/editor/editor_help.cpp index 46ed2194a8..2ece518f8d 100644 --- a/tools/editor/editor_help.cpp +++ b/tools/editor/editor_help.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -36,6 +36,14 @@ #include "os/keyboard.h" +void EditorHelpSearch::popup() { + popup_centered_ratio(0.6); + if (search_box->get_text()!="") { + search_box->select_all(); + _update_search(); + } + search_box->grab_focus(); +} void EditorHelpSearch::popup(const String& p_term) { @@ -263,7 +271,7 @@ void EditorHelpSearch::_confirmed() { String mdata=ti->get_metadata(0); emit_signal("go_to_help",mdata); - editor->call("_editor_select",3); // in case EditorHelpSearch beeen invoked on top of other editor window + editor->call("_editor_select",EditorNode::EDITOR_SCRIPT); // in case EditorHelpSearch beeen invoked on top of other editor window // go to that hide(); } @@ -300,9 +308,9 @@ void EditorHelpSearch::_bind_methods() { } -EditorHelpSearch::EditorHelpSearch(EditorNode *p_editor) { +EditorHelpSearch::EditorHelpSearch() { - editor=p_editor; + editor=EditorNode::get_singleton(); VBoxContainer *vbc = memnew( VBoxContainer ); add_child(vbc); set_child_rect(vbc); @@ -318,17 +326,138 @@ EditorHelpSearch::EditorHelpSearch(EditorNode *p_editor) { search_box->connect("input_event",this,"_sbox_input"); search_options = memnew( Tree ); vbc->add_margin_child("Matches:",search_options,true); - get_ok()->set_text("View"); + get_ok()->set_text("Open"); get_ok()->set_disabled(true); register_text_enter(search_box); set_hide_on_ok(false); search_options->connect("item_activated",this,"_confirmed"); set_title("Search Classes"); + // search_options->set_hide_root(true); } +///////////////////////////////// + +//////////////////////////////////// +/// ///////////////////////////////// + + + +void EditorHelpIndex::add_type(const String& p_type,HashMap<String,TreeItem*>& p_types,TreeItem *p_root) { + + if (p_types.has(p_type)) + return; +// if (!ObjectTypeDB::is_type(p_type,base) || p_type==base) +// return; + + String inherits=EditorHelp::get_doc_data()->class_list[p_type].inherits; + + TreeItem *parent=p_root; + + + if (inherits.length()) { + + if (!p_types.has(inherits)) { + + add_type(inherits,p_types,p_root); + } + + if (p_types.has(inherits) ) + parent=p_types[inherits]; + } + + TreeItem *item = class_list->create_item(parent); + item->set_metadata(0,p_type); + item->set_tooltip(0,EditorHelp::get_doc_data()->class_list[p_type].brief_description); + item->set_text(0,p_type); + + + if (has_icon(p_type,"EditorIcons")) { + + item->set_icon(0, get_icon(p_type,"EditorIcons")); + } + + p_types[p_type]=item; +} + + +void EditorHelpIndex::_tree_item_selected() { + + + TreeItem *s=class_list->get_selected(); + if (!s) + return; + + emit_signal("open_class",s->get_text(0)); + + hide(); + + //_goto_desc(s->get_text(0)); + +} + +void EditorHelpIndex::select_class(const String& p_class) { + + if (!tree_item_map.has(p_class)) + return; + tree_item_map[p_class]->select(0); + class_list->ensure_cursor_is_visible(); +} + +void EditorHelpIndex::_notification(int p_what) { + + if (p_what==NOTIFICATION_ENTER_TREE) { + + class_list->clear(); + tree_item_map.clear(); + TreeItem *root = class_list->create_item(); + class_list->set_hide_root(true); + connect("confirmed",this,"_tree_item_selected"); + + + for(Map<String,DocData::ClassDoc>::Element *E=EditorHelp::get_doc_data()->class_list.front();E;E=E->next()) { + + + add_type(E->key(),tree_item_map,root); + } + + } +} + +void EditorHelpIndex::_bind_methods() { + + ObjectTypeDB::bind_method("_tree_item_selected",&EditorHelpIndex::_tree_item_selected); + ObjectTypeDB::bind_method("select_class",&EditorHelpIndex::select_class); + ADD_SIGNAL( MethodInfo("open_class")); +} + + + +EditorHelpIndex::EditorHelpIndex() { + + + VBoxContainer *vbc = memnew( VBoxContainer ); + add_child(vbc); + set_child_rect(vbc); + + class_list = memnew( Tree ); + vbc->add_margin_child("Class List: ",class_list,true); + class_list->set_v_size_flags(SIZE_EXPAND_FILL); + + + class_list->connect("item_activated",this,"_tree_item_selected"); + + + get_ok()->set_text("Open"); +} + + +///////////////////////////////// + +//////////////////////////////////// +/// ///////////////////////////////// DocData *EditorHelp::doc=NULL; void EditorHelp::_unhandled_key_input(const InputEvent& p_ev) { @@ -339,8 +468,6 @@ void EditorHelp::_unhandled_key_input(const InputEvent& p_ev) { search->grab_focus(); search->select_all(); - } else if (p_ev.key.mod.shift && p_ev.key.scancode==KEY_F1) { - class_search->popup(); } } @@ -351,17 +478,19 @@ void EditorHelp::_search(const String&) { String stext=search->get_text(); - bool keep = prev_search==stext && class_list->get_selected() && prev_search_page==class_list->get_selected()->get_text(0); + bool keep = prev_search==stext; - class_desc->search(stext, keep); + bool ret = class_desc->search(stext, keep); + if (!ret) { + class_desc->search(stext, false); + } prev_search=stext; - if (class_list->get_selected()) - prev_search_page=class_list->get_selected()->get_text(0); } +#if 0 void EditorHelp::_button_pressed(int p_idx) { if (p_idx==PAGE_CLASS_LIST) { @@ -399,16 +528,11 @@ void EditorHelp::_button_pressed(int p_idx) { } else if (p_idx==PAGE_SEARCH) { _search(""); - } else if (p_idx==CLASS_SEARCH) { - - class_search->popup(); } - - } - +#endif void EditorHelp::_class_list_select(const String& p_select) { @@ -417,16 +541,28 @@ void EditorHelp::_class_list_select(const String& p_select) { void EditorHelp::_class_desc_select(const String& p_select) { + + +// print_line("LINK: "+p_select); if (p_select.begins_with("#")) { - _goto_desc(p_select.substr(1,p_select.length())); + //_goto_desc(p_select.substr(1,p_select.length())); + emit_signal("go_to_help","class_name:"+p_select.substr(1,p_select.length())); return; } else if (p_select.begins_with("@")) { String m = p_select.substr(1,p_select.length()); - if (!method_line.has(m)) - return; - class_desc->scroll_to_line(method_line[m]); - return; + + if (m.find(".")!=-1) { + //must go somewhere else + + emit_signal("go_to_help","class_method:"+m.get_slice(".",0)+":"+m.get_slice(".",0)); + } else { + + if (!method_line.has(m)) + return; + class_desc->scroll_to_line(method_line[m]); + } + } @@ -449,68 +585,40 @@ void EditorHelp::_add_type(const String& p_type) { } -void EditorHelp::_update_history_buttons() { - - back->set_disabled(history_pos<2); - forward->set_disabled(history_pos>=history.size()); - -} - - void EditorHelp::_scroll_changed(double p_scroll) { if (scroll_locked) return; - int p = history_pos -1; - if (p<0 || p>=history.size()) - return; - if (class_desc->get_v_scroll()->is_hidden()) p_scroll=0; - history[p].scroll=p_scroll; + //history[p].scroll=p_scroll; } -Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_vscr) { +Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) { //ERR_FAIL_COND(!doc->class_list.has(p_class)); if (!doc->class_list.has(p_class)) return ERR_DOES_NOT_EXIST; - if (tree_item_map.has(p_class)) { + //if (tree_item_map.has(p_class)) { select_locked = true; - tree_item_map[p_class]->select(0); - class_list->ensure_cursor_is_visible(); - } + //} class_desc->show(); //tabs->set_current_tab(PAGE_CLASS_DESC); - edited_class->set_pressed(true); - class_list_button->set_pressed(false); description_line=0; - if (p_class==edited_class->get_text()) + if (p_class==edited_class) return OK; //already there scroll_locked=true; - if (p_update_history) { - - history.resize(history_pos); - history_pos++; - History h; - h.c=p_class; - h.scroll=0; - history.push_back(h); - _update_history_buttons(); - class_desc->get_v_scroll()->set_val(0); - } - class_desc->clear(); method_line.clear(); - edited_class->set_text(p_class); + edited_class=p_class; //edited_class->show(); @@ -529,7 +637,7 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/keyword_color")); class_desc->add_text("Class: "); class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/base_type_color")); - class_desc->add_text(p_class); + _add_text(p_class); class_desc->pop(); class_desc->pop(); class_desc->pop(); @@ -547,7 +655,6 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v class_desc->pop(); class_desc->add_newline(); class_desc->add_newline(); - class_desc->add_newline(); } @@ -561,8 +668,13 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v //class_desc->add_newline(); class_desc->add_newline(); + class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/text_color")); + class_desc->push_font( get_font("normal","Fonts") ); + class_desc->push_indent(1); _add_text(cd.brief_description); - class_desc->add_newline(); + class_desc->pop(); + class_desc->pop(); + class_desc->pop(); class_desc->add_newline(); class_desc->add_newline(); } @@ -578,22 +690,34 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v class_desc->pop(); //class_desc->add_newline(); - class_desc->add_newline(); +// class_desc->add_newline(); class_desc->push_indent(1); + class_desc->push_table(2); + class_desc->set_table_column_expand(1,1); for(int i=0;i<cd.methods.size();i++) { + class_desc->push_cell(); + + method_line[cd.methods[i].name]=class_desc->get_line_count()-2; //gets overriden if description + class_desc->push_align(RichTextLabel::ALIGN_RIGHT); class_desc->push_font(doc_code_font); _add_type(cd.methods[i].return_type); - class_desc->add_text(" "); + //class_desc->add_text(" "); + class_desc->pop(); //align + class_desc->pop(); //font + class_desc->pop(); //cell + class_desc->push_cell(); + class_desc->push_font(doc_code_font); + if (cd.methods[i].description!="") { method_descr=true; class_desc->push_meta("@"+cd.methods[i].name); } class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/text_color")); - class_desc->add_text(cd.methods[i].name); + _add_text(cd.methods[i].name); class_desc->pop(); if (cd.methods[i].description!="") class_desc->pop(); @@ -605,13 +729,14 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v if (j>0) class_desc->add_text(", "); _add_type(cd.methods[i].arguments[j].type); - class_desc->add_text(" "+cd.methods[i].arguments[j].name); + class_desc->add_text(" "); + _add_text(cd.methods[i].arguments[j].name); if (cd.methods[i].arguments[j].default_value!="") { class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/symbol_color")); class_desc->add_text("="); class_desc->pop(); - class_desc->add_text(cd.methods[i].arguments[j].default_value); + _add_text(cd.methods[i].arguments[j].default_value); } class_desc->pop(); @@ -623,22 +748,26 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v if (cd.methods[i].qualifiers!="") { class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/keyword_color")); - class_desc->add_text(" "+cd.methods[i].qualifiers); + class_desc->add_text(" "); + _add_text(cd.methods[i].qualifiers); class_desc->pop(); } class_desc->pop();//monofont - class_desc->add_newline(); +// class_desc->add_newline(); + class_desc->pop(); //cell } - + class_desc->pop(); //table class_desc->pop(); class_desc->add_newline(); + class_desc->add_newline(); } if (cd.properties.size()) { + class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/keyword_color")); class_desc->push_font(doc_title_font); class_desc->add_text("Members:"); @@ -656,7 +785,8 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v class_desc->push_font(doc_code_font); _add_type(cd.properties[i].type); class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/text_color")); - class_desc->add_text(" "+cd.properties[i].name); + class_desc->add_text(" "); + _add_text(cd.properties[i].name); class_desc->pop(); class_desc->pop(); @@ -664,7 +794,7 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v class_desc->push_font(doc_font); class_desc->add_text(" "); class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/comment_color")); - class_desc->add_text(cd.properties[i].description); + _add_text(cd.properties[i].description); class_desc->pop(); class_desc->pop(); @@ -699,7 +829,8 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v class_desc->push_font(doc_code_font); _add_type(cd.theme_properties[i].type); class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/text_color")); - class_desc->add_text(" "+cd.theme_properties[i].name); + class_desc->add_text(" "); + _add_text(cd.theme_properties[i].name); class_desc->pop(); class_desc->pop(); @@ -707,7 +838,7 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v class_desc->push_font(doc_font); class_desc->add_text(" "); class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/comment_color")); - class_desc->add_text(cd.theme_properties[i].description); + _add_text(cd.theme_properties[i].description); class_desc->pop(); class_desc->pop(); @@ -716,10 +847,9 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v class_desc->add_newline(); } + class_desc->add_newline(); class_desc->pop(); - class_desc->add_newline(); - class_desc->add_newline(); } if (cd.signals.size()) { @@ -738,11 +868,11 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v for(int i=0;i<cd.signals.size();i++) { signal_line[cd.signals[i].name]=class_desc->get_line_count()-2; //gets overriden if description - class_desc->push_font(doc_code_font); + class_desc->push_font(doc_code_font); // monofont //_add_type("void"); //class_desc->add_text(" "); class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/text_color")); - class_desc->add_text(cd.signals[i].name); + _add_text(cd.signals[i].name); class_desc->pop(); class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/symbol_color")); class_desc->add_text(cd.signals[i].arguments.size()?"( ":"("); @@ -752,13 +882,14 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v if (j>0) class_desc->add_text(", "); _add_type(cd.signals[i].arguments[j].type); - class_desc->add_text(" "+cd.signals[i].arguments[j].name); + class_desc->add_text(" "); + _add_text(cd.signals[i].arguments[j].name); if (cd.signals[i].arguments[j].default_value!="") { class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/symbol_color")); class_desc->add_text("="); class_desc->pop(); - class_desc->add_text(cd.signals[i].arguments[j].default_value); + _add_text(cd.signals[i].arguments[j].default_value); } class_desc->pop(); @@ -767,21 +898,21 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/symbol_color")); class_desc->add_text(cd.signals[i].arguments.size()?" )":")"); class_desc->pop(); + class_desc->pop(); // end monofont if (cd.signals[i].description!="") { class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/comment_color")); - class_desc->add_text(" "+cd.signals[i].description); + class_desc->add_text(" "); + _add_text(cd.signals[i].description); class_desc->pop(); } - class_desc->pop();//monofont class_desc->add_newline(); } class_desc->pop(); class_desc->add_newline(); - class_desc->add_newline(); } @@ -803,20 +934,20 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v constant_line[cd.constants[i].name]=class_desc->get_line_count()-2; class_desc->push_font(doc_code_font); class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/base_type_color")); - class_desc->add_text(cd.constants[i].name); + _add_text(cd.constants[i].name); class_desc->pop(); class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/symbol_color")); class_desc->add_text(" = "); class_desc->pop(); class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/keyword_color")); - class_desc->add_text(cd.constants[i].value); + _add_text(cd.constants[i].value); class_desc->pop(); class_desc->pop(); if (cd.constants[i].description!="") { class_desc->push_font(doc_font); class_desc->add_text(" "); class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/comment_color")); - class_desc->add_text(cd.constants[i].description); + _add_text(cd.constants[i].description); class_desc->pop(); class_desc->pop(); } @@ -826,7 +957,6 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v class_desc->pop(); class_desc->add_newline(); - class_desc->add_newline(); } @@ -834,7 +964,6 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v if (cd.description!="") { description_line=class_desc->get_line_count()-2; - class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/keyword_color")); class_desc->push_font(doc_title_font); class_desc->add_text("Description:"); @@ -842,8 +971,14 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v class_desc->pop(); class_desc->add_newline(); - _add_text(cd.description); class_desc->add_newline(); + class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/text_color")); + class_desc->push_font( get_font("normal","Fonts") ); + class_desc->push_indent(1); + _add_text(cd.description); + class_desc->pop(); + class_desc->pop(); + class_desc->pop(); class_desc->add_newline(); class_desc->add_newline(); } @@ -858,22 +993,18 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v class_desc->add_newline(); class_desc->add_newline(); - class_desc->push_indent(1); for(int i=0;i<cd.methods.size();i++) { method_line[cd.methods[i].name]=class_desc->get_line_count()-2; - if( cd.methods[i].description != "") { - class_desc->add_newline(); - } class_desc->push_font(doc_code_font); _add_type(cd.methods[i].return_type); class_desc->add_text(" "); class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/text_color")); - class_desc->add_text(cd.methods[i].name); + _add_text(cd.methods[i].name); class_desc->pop(); class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/symbol_color")); class_desc->add_text(cd.methods[i].arguments.size()?"( ":"("); @@ -883,13 +1014,14 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v if (j>0) class_desc->add_text(", "); _add_type(cd.methods[i].arguments[j].type); - class_desc->add_text(" "+cd.methods[i].arguments[j].name); + class_desc->add_text(" "); + _add_text(cd.methods[i].arguments[j].name); if (cd.methods[i].arguments[j].default_value!="") { class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/symbol_color")); class_desc->add_text("="); class_desc->pop(); - class_desc->add_text(cd.methods[i].arguments[j].default_value); + _add_text(cd.methods[i].arguments[j].default_value); } class_desc->pop(); @@ -901,19 +1033,23 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v if (cd.methods[i].qualifiers!="") { class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/keyword_color")); - class_desc->add_text(" "+cd.methods[i].qualifiers); + class_desc->add_text(" "); + _add_text(cd.methods[i].qualifiers); class_desc->pop(); } class_desc->pop(); - if( cd.methods[i].description != "") { - class_desc->add_text(" "); - _add_text(cd.methods[i].description); - class_desc->add_newline(); - class_desc->add_newline(); - } + class_desc->add_newline(); + class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/text_color")); + class_desc->push_font( get_font("normal","Fonts") ); + class_desc->push_indent(1); + _add_text(cd.methods[i].description); + class_desc->pop(); + class_desc->pop(); + class_desc->pop(); + class_desc->add_newline(); class_desc->add_newline(); class_desc->add_newline(); @@ -925,10 +1061,7 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v } - if (!p_update_history) { - class_desc->get_v_scroll()->set_val(history[history_pos-1].scroll); - } scroll_locked=false; @@ -938,9 +1071,7 @@ Error EditorHelp::_goto_desc(const String& p_class,bool p_update_history,int p_v void EditorHelp::_request_help(const String& p_string) { Error err = _goto_desc(p_string); if (err==OK) { - editor->call("_editor_select",3); - } else { - class_search->popup(p_string); + editor->call("_editor_select",EditorNode::EDITOR_SCRIPT); } //100 palabras } @@ -980,16 +1111,16 @@ void EditorHelp::_help_callback(const String& p_topic) { line=constant_line[name]; } - class_desc->scroll_to_line(line); + class_desc->call_deferred("scroll_to_line", line); } void EditorHelp::_add_text(const String& p_bbcode) { - class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/text_color")); + /*class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/text_color")); class_desc->push_font( get_font("normal","Fonts") ); - class_desc->push_indent(1); + class_desc->push_indent(1);*/ int pos = 0; List<String> tag_stack; @@ -1067,7 +1198,7 @@ void EditorHelp::_add_text(const String& p_bbcode) { } else if (tag=="i") { //use italics font - //class_desc->push_font(get_font("italic","Fonts")); + class_desc->push_font(get_font("italic","Fonts")); pos=brk_end+1; tag_stack.push_front(tag); } else if (tag=="code") { @@ -1203,321 +1334,160 @@ void EditorHelp::_add_text(const String& p_bbcode) { } } + /*class_desc->pop(); class_desc->pop(); - class_desc->pop(); + class_desc->pop();*/ } -void EditorHelp::add_type(const String& p_type,HashMap<String,TreeItem*>& p_types,TreeItem *p_root) { - - if (p_types.has(p_type)) - return; -// if (!ObjectTypeDB::is_type(p_type,base) || p_type==base) -// return; - - String inherits=doc->class_list[p_type].inherits; - - TreeItem *parent=p_root; - if (inherits.length()) { +void EditorHelp::_update_doc() { - if (!p_types.has(inherits)) { - add_type(inherits,p_types,p_root); - } - if (p_types.has(inherits) ) - parent=p_types[inherits]; - } +} - TreeItem *item = class_list->create_item(parent); - item->set_metadata(0,p_type); - item->set_tooltip(0,doc->class_list[p_type].brief_description); - item->set_text(0,p_type); +void EditorHelp::generate_doc() { - if (has_icon(p_type,"EditorIcons")) { + doc = memnew( DocData ); + doc->generate(true); + DocData compdoc; + compdoc.load_compressed(_doc_data_compressed,_doc_data_compressed_size,_doc_data_uncompressed_size); + doc->merge_from(compdoc); //ensure all is up to date - item->set_icon(0, get_icon(p_type,"EditorIcons")); - } - p_types[p_type]=item; } +void EditorHelp::_notification(int p_what) { -void EditorHelp::_update_doc() { - - - class_list->clear(); - - List<StringName> type_list; - - tree_item_map.clear(); + switch(p_what) { - TreeItem *root = class_list->create_item(); - class_list->set_hide_root(true); - List<StringName>::Element *I=type_list.front(); + case NOTIFICATION_READY: { - for(Map<String,DocData::ClassDoc>::Element *E=doc->class_list.front();E;E=E->next()) { +// forward->set_icon(get_icon("Forward","EditorIcons")); +// back->set_icon(get_icon("Back","EditorIcons")); + _update_doc(); - add_type(E->key(),tree_item_map,root); + } break; } +} + +void EditorHelp::go_to_help(const String& p_help) { + _help_callback(p_help); } +void EditorHelp::go_to_class(const String& p_class,int p_scroll) { -void EditorHelp::generate_doc() { + _goto_desc(p_class,p_scroll); +} - doc = memnew( DocData ); - doc->generate(true); - DocData compdoc; - compdoc.load_compressed(_doc_data_compressed,_doc_data_compressed_size,_doc_data_uncompressed_size); - doc->merge_from(compdoc); //ensure all is up to date +void EditorHelp::popup_search() { + search_dialog->popup_centered(Size2(250,80)); + search->grab_focus(); } -void EditorHelp::_notification(int p_what) { +void EditorHelp::_search_cbk() { + _search(search->get_text()); +} - switch(p_what) { +String EditorHelp::get_class_name() { - case NOTIFICATION_READY: { + return edited_class; +} +void EditorHelp::search_again() { + _search(prev_search); +} - forward->set_icon(get_icon("Forward","EditorIcons")); - back->set_icon(get_icon("Back","EditorIcons")); - _update_doc(); - editor->connect("request_help",this,"_request_help"); +int EditorHelp::get_scroll() const { - } break; - } + return class_desc->get_v_scroll()->get_val(); } +void EditorHelp::set_scroll(int p_scroll) { -void EditorHelp::_tree_item_selected() { - if (select_locked) { - select_locked = false; - return; - } - TreeItem *s=class_list->get_selected(); - if (!s) - return; - select_locked=true; - _goto_desc(s->get_text(0)); - select_locked=false; + class_desc->get_v_scroll()->set_val(p_scroll); + } void EditorHelp::_bind_methods() { ObjectTypeDB::bind_method("_class_list_select",&EditorHelp::_class_list_select); ObjectTypeDB::bind_method("_class_desc_select",&EditorHelp::_class_desc_select); - ObjectTypeDB::bind_method("_button_pressed",&EditorHelp::_button_pressed); +// ObjectTypeDB::bind_method("_button_pressed",&EditorHelp::_button_pressed); ObjectTypeDB::bind_method("_scroll_changed",&EditorHelp::_scroll_changed); ObjectTypeDB::bind_method("_request_help",&EditorHelp::_request_help); ObjectTypeDB::bind_method("_unhandled_key_input",&EditorHelp::_unhandled_key_input); ObjectTypeDB::bind_method("_search",&EditorHelp::_search); - ObjectTypeDB::bind_method("_tree_item_selected",&EditorHelp::_tree_item_selected); + ObjectTypeDB::bind_method("_search_cbk",&EditorHelp::_search_cbk); ObjectTypeDB::bind_method("_help_callback",&EditorHelp::_help_callback); + ADD_SIGNAL(MethodInfo("go_to_help")); + } -EditorHelp::EditorHelp(EditorNode *p_editor) { +EditorHelp::EditorHelp() { - editor=p_editor; + editor=EditorNode::get_singleton(); VBoxContainer *vbc = this; - HBoxContainer *panel_hb = memnew( HBoxContainer ); - - Button *b = memnew( Button ); - b->set_text("Class List"); - panel_hb->add_child(b); - vbc->add_child(panel_hb); - b->set_toggle_mode(true); - b->set_pressed(true); - b->connect("pressed",this,"_button_pressed",make_binds(PAGE_CLASS_LIST)); - class_list_button=b; - class_list_button->hide(); - - b = memnew( Button ); - b->set_text("Class"); - panel_hb->add_child(b); - edited_class=b; - edited_class->hide(); - b->set_toggle_mode(true); - b->connect("pressed",this,"_button_pressed",make_binds(PAGE_CLASS_DESC)); - - b = memnew( Button ); - b->set_text("Search in Classes"); - panel_hb->add_child(b); - b->connect("pressed",this,"_button_pressed",make_binds(CLASS_SEARCH)); - - Control *expand = memnew( Control ); - expand->set_h_size_flags(SIZE_EXPAND_FILL); - panel_hb->add_child(expand); - - b = memnew( Button ); - panel_hb->add_child(b); - back=b; - b->connect("pressed",this,"_button_pressed",make_binds(PAGE_CLASS_PREV)); - - b = memnew( Button ); - panel_hb->add_child(b); - forward=b; - b->connect("pressed",this,"_button_pressed",make_binds(PAGE_CLASS_NEXT)); - - Separator *hs = memnew( VSeparator ); - panel_hb->add_child(hs); - Control *ec = memnew( Control ); - ec->set_custom_minimum_size(Size2(200,1)); - panel_hb->add_child(ec); - search = memnew( LineEdit ); - ec->add_child(search); - search->set_area_as_parent_rect(); - search->connect("text_entered",this,"_search"); - - b = memnew( Button ); - b->set_text("Find"); - panel_hb->add_child(b); - b->connect("pressed",this,"_button_pressed",make_binds(PAGE_SEARCH)); - - hs = memnew( VSeparator ); - panel_hb->add_child(hs); - - h_split = memnew( HSplitContainer ); - h_split->set_v_size_flags(SIZE_EXPAND_FILL); - - vbc->add_child(h_split); - - class_list = memnew( Tree ); - h_split->add_child(class_list); //class_list->connect("meta_clicked",this,"_class_list_select"); //class_list->set_selection_enabled(true); { - PanelContainer *pc = memnew( PanelContainer ); + Panel *pc = memnew( Panel ); Ref<StyleBoxFlat> style( memnew( StyleBoxFlat ) ); - style->set_bg_color( EditorSettings::get_singleton()->get("text_editor/background_color") ); - style->set_default_margin(MARGIN_LEFT,20); - style->set_default_margin(MARGIN_TOP,20); + style->set_bg_color( EditorSettings::get_singleton()->get("text_editor/background_color") ); + pc->set_v_size_flags(SIZE_EXPAND_FILL); pc->add_style_override("panel", style); //get_stylebox("normal","TextEdit")); - h_split->add_child(pc); + vbc->add_child(pc); class_desc = memnew( RichTextLabel ); pc->add_child(class_desc); + class_desc->set_area_as_parent_rect(8); class_desc->connect("meta_clicked",this,"_class_desc_select"); } class_desc->get_v_scroll()->connect("value_changed",this,"_scroll_changed"); class_desc->set_selection_enabled(true); - editor=p_editor; - history_pos=0; + scroll_locked=false; select_locked=false; set_process_unhandled_key_input(true); - h_split->set_split_offset(200); - class_list->connect("cell_selected",this,"_tree_item_selected"); class_desc->hide(); - class_search = memnew( EditorHelpSearch(editor) ); - editor->get_gui_base()->add_child(class_search); - class_search->connect("go_to_help",this,"_help_callback"); -// prev_search_page=-1; -} - -EditorHelp::~EditorHelp() { - if (doc) - memdelete(doc); -} - - -void EditorHelpPlugin::edit(Object *p_object) { - - if (!p_object->cast_to<Script>()) - return; - - //editor_help->edit(p_object->cast_to<Script>()); -} - -bool EditorHelpPlugin::handles(Object *p_object) const { - - return false; -} - -void EditorHelpPlugin::make_visible(bool p_visible) { - - if (p_visible) { - editor_help->show(); - } else { - - editor_help->hide(); - } - -} - -void EditorHelpPlugin::selected_notify() { - - //editor_help->ensure_select_current(); -} - -Dictionary EditorHelpPlugin::get_state() const { - - return Dictionary(); -} - -void EditorHelpPlugin::set_state(const Dictionary& p_state) { - - //editor_help->set_state(p_state); -} -void EditorHelpPlugin::clear() { - - //editor_help->clear(); -} - -void EditorHelpPlugin::save_external_data() { - - //editor_help->save_external_data(); -} - -void EditorHelpPlugin::apply_changes() { - - //editor_help->apply_helps(); -} - -void EditorHelpPlugin::restore_global_state() { - - //if (bool(EDITOR_DEF("text_editor/restore_helps_on_load",true))) { -// editor_help->_load_files_state(); - //} - -} + search_dialog = memnew( ConfirmationDialog ); + add_child(search_dialog); + VBoxContainer *search_vb = memnew( VBoxContainer ); + search_dialog->add_child(search_vb); + search_dialog->set_child_rect(search_vb); + search = memnew( LineEdit ); + search_dialog->register_text_enter(search); + search_vb->add_margin_child("Search Text",search); + search_dialog->get_ok()->set_text("Find"); + search_dialog->connect("confirmed",this,"_search_cbk"); + search_dialog->set_hide_on_ok(false); + search_dialog->set_self_opacity(0.8); -void EditorHelpPlugin::save_global_state() { - //if (bool(EDITOR_DEF("text_editor/restore_helps_on_load",true))) { -// editor_help->_save_files_state(); -// } + /*class_search = memnew( EditorHelpSearch(editor) ); + editor->get_gui_base()->add_child(class_search); + class_search->connect("go_to_help",this,"_help_callback");*/ +// prev_search_page=-1; } - -EditorHelpPlugin::EditorHelpPlugin(EditorNode *p_node) { - - editor=p_node; - editor_help = memnew( EditorHelp(p_node) ); - editor->get_viewport()->add_child(editor_help); - editor_help->set_area_as_parent_rect(); - editor_help->hide(); - +EditorHelp::~EditorHelp() { } - -EditorHelpPlugin::~EditorHelpPlugin() -{ -} diff --git a/tools/editor/editor_help.h b/tools/editor/editor_help.h index d4066d076a..059a7ae11d 100644 --- a/tools/editor/editor_help.h +++ b/tools/editor/editor_help.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -68,11 +68,32 @@ protected: static void _bind_methods(); public: - void popup(const String& p_term=""); + void popup(); + void popup(const String& p_term); - EditorHelpSearch(EditorNode *p_editor); + EditorHelpSearch(); }; +class EditorHelpIndex : public ConfirmationDialog { + OBJ_TYPE( EditorHelpIndex, ConfirmationDialog ); + + + Tree *class_list; + HashMap<String,TreeItem*> tree_item_map; + + void _tree_item_selected(); + void add_type(const String& p_type,HashMap<String,TreeItem*>& p_types,TreeItem *p_root); +protected: + + void _notification(int p_what); + static void _bind_methods(); + +public: + + void select_class(const String& p_class); + + EditorHelpIndex(); +}; class EditorHelp : public VBoxContainer { @@ -91,17 +112,11 @@ class EditorHelp : public VBoxContainer { }; - struct History { - String c; - int scroll; - }; - - Vector<History> history; - int history_pos; bool select_locked; String prev_search; - String prev_search_page; + + String edited_class; EditorNode *editor; Map<String,int> method_line; @@ -111,21 +126,17 @@ class EditorHelp : public VBoxContainer { Map<String,int> constant_line; int description_line; - Tree *class_list; RichTextLabel *class_desc; HSplitContainer *h_split; static DocData *doc; - Button *class_list_button; - Button *edited_class; - Button *back; - Button *forward; + + ConfirmationDialog *search_dialog; LineEdit *search; - String base_path; - HashMap<String,TreeItem*> tree_item_map; + String base_path; void _help_callback(const String& p_topic); @@ -133,25 +144,24 @@ class EditorHelp : public VBoxContainer { void _add_text(const String& p_text); bool scroll_locked; - void _button_pressed(int p_idx); + //void _button_pressed(int p_idx); void _add_type(const String& p_type); void _scroll_changed(double p_scroll); void _class_list_select(const String& p_select); void _class_desc_select(const String& p_select); - Error _goto_desc(const String& p_class,bool p_update_history=true,int p_vscr=-1); - void _update_history_buttons(); + Error _goto_desc(const String& p_class, int p_vscr=-1); + //void _update_history_buttons(); void _update_doc(); void _request_help(const String& p_string); void _search(const String& p_str); + void _search_cbk(); void _unhandled_key_input(const InputEvent& p_ev); - void add_type(const String& p_type,HashMap<String,TreeItem*>& p_types,TreeItem *p_root); - void _tree_item_selected(); - EditorHelpSearch *class_search; + protected: @@ -163,41 +173,25 @@ public: static void generate_doc(); static DocData *get_doc_data() { return doc; } - EditorHelp(EditorNode *p_editor=NULL); - ~EditorHelp(); -}; - - + void go_to_help(const String& p_help); + void go_to_class(const String& p_class,int p_scroll=0); -class EditorHelpPlugin : public EditorPlugin { + void popup_search(); + void search_again(); - OBJ_TYPE( EditorHelpPlugin, EditorPlugin ); + String get_class_name(); - EditorHelp *editor_help; - EditorNode *editor; -public: + void set_focused() { class_desc->grab_focus(); } - virtual String get_name() const { return "Help"; } - bool has_main_screen() const { return true; } - virtual void edit(Object *p_node); - virtual bool handles(Object *p_node) const; - virtual void make_visible(bool p_visible); - virtual void selected_notify(); + int get_scroll() const; + void set_scroll(int p_scroll); - Dictionary get_state() const; - virtual void set_state(const Dictionary& p_state); - virtual void clear(); - - virtual void save_external_data(); - virtual void apply_changes(); + EditorHelp(); + ~EditorHelp(); +}; - virtual void restore_global_state(); - virtual void save_global_state(); - EditorHelpPlugin(EditorNode *p_node); - ~EditorHelpPlugin(); -}; #endif // EDITOR_HELP_H diff --git a/tools/editor/editor_icons.h b/tools/editor/editor_icons.h index 910febc895..191b908682 100644 --- a/tools/editor/editor_icons.h +++ b/tools/editor/editor_icons.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/editor_import_export.cpp b/tools/editor/editor_import_export.cpp index b13473e61c..bcac82fc1b 100644 --- a/tools/editor/editor_import_export.cpp +++ b/tools/editor/editor_import_export.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -41,6 +41,8 @@ #include "io/md5.h" #include "io_plugins/editor_texture_import_plugin.h" #include "tools/editor/plugins/script_editor_plugin.h" +#include "io/zip_io.h" + String EditorImportPlugin::validate_source_path(const String& p_path) { @@ -399,6 +401,40 @@ Vector<StringName> EditorExportPlatform::get_dependencies(bool p_bundles) const } +String EditorExportPlatform::find_export_template(String template_file_name, String *err) const { + String user_file = EditorSettings::get_singleton()->get_settings_path() + +"/templates/"+template_file_name; + String system_file=OS::get_singleton()->get_installed_templates_path(); + bool has_system_path=(system_file!=""); + system_file+=template_file_name; + + // Prefer user file + if (FileAccess::exists(user_file)) { + return user_file; + } + + // Now check system file + if (has_system_path) { + if (FileAccess::exists(system_file)) { + return system_file; + } + } + + // Not found + if (err) { + *err+="No export template found at \""+user_file+"\""; + if (has_system_path) + *err+="\n or \""+system_file+"\"."; + else + *err+="."; + } + return ""; +} + +bool EditorExportPlatform::exists_export_template(String template_file_name, String *err) const { + return find_export_template(template_file_name,err)!=""; +} + /////////////////////////////////////// @@ -1028,7 +1064,7 @@ Error EditorExportPlatform::save_pack_file(void *p_userdata,const String& p_path MD5Final(&ctx); pd->f->store_buffer(ctx.digest,16); } - pd->ep->step("Storing File: "+p_path,2+p_file*100/p_total); + pd->ep->step("Storing File: "+p_path,2+p_file*100/p_total,false); pd->count++; pd->ftmp->store_buffer(p_data.ptr(),p_data.size()); if (pd->alignment > 1) { @@ -1043,6 +1079,58 @@ Error EditorExportPlatform::save_pack_file(void *p_userdata,const String& p_path } +Error EditorExportPlatform::save_zip_file(void *p_userdata,const String& p_path, const Vector<uint8_t>& p_data,int p_file,int p_total) { + + + String path=p_path.replace_first("res://",""); + + ZipData *zd = (ZipData*)p_userdata; + + zipFile zip=(zipFile)zd->zip; + + zipOpenNewFileInZip(zip, + path.utf8().get_data(), + NULL, + NULL, + 0, + NULL, + 0, + NULL, + Z_DEFLATED, + Z_DEFAULT_COMPRESSION); + + zipWriteInFileInZip(zip,p_data.ptr(),p_data.size()); + zipCloseFileInZip(zip); + + zd->ep->step("Storing File: "+p_path,2+p_file*100/p_total,false); + zd->count++; + return OK; + +} + +Error EditorExportPlatform::save_zip(const String& p_path, bool p_make_bundles) { + + EditorProgress ep("savezip","Packing",102); + + //FileAccess *tmp = FileAccess::open(tmppath,FileAccess::WRITE); + + FileAccess *src_f; + zlib_filefunc_def io = zipio_create_io_from_file(&src_f); + zipFile zip=zipOpen2(p_path.utf8().get_data(),APPEND_STATUS_CREATE,NULL,&io); + + ZipData zd; + zd.count=0; + zd.ep=&ep; + zd.zip=zip; + + + Error err = export_project_files(save_zip_file,&zd,p_make_bundles); + + zipClose(zip,NULL); + + return err; +} + Error EditorExportPlatform::save_pack(FileAccess *dst,bool p_make_bundles, int p_alignment) { EditorProgress ep("savepack","Packing",102); @@ -1131,19 +1219,32 @@ Error EditorExportPlatformPC::export_project(const String& p_path, bool p_debug, ep.step("Setting Up..",0); - String exe_path = EditorSettings::get_singleton()->get_settings_path()+"/templates/"; - if (use64) { - if (p_debug) - exe_path=custom_debug_binary!=""?custom_debug_binary:exe_path+debug_binary64; - else - exe_path=custom_release_binary!=""?custom_release_binary:exe_path+release_binary64; - } else { + String exe_path=""; - if (p_debug) - exe_path=custom_debug_binary!=""?custom_debug_binary:exe_path+debug_binary32; - else - exe_path=custom_release_binary!=""?custom_release_binary:exe_path+release_binary32; + if (p_debug) + exe_path=custom_debug_binary; + else + exe_path=custom_release_binary; + if (exe_path=="") { + String fname; + if (use64) { + if (p_debug) + fname=debug_binary64; + else + fname=release_binary64; + } else { + if (p_debug) + fname=debug_binary32; + else + fname=release_binary32; + } + String err=""; + exe_path=find_export_template(fname,&err); + if (exe_path=="") { + EditorNode::add_io_error(err); + return ERR_FILE_CANT_READ; + } } FileAccess *src_exe=FileAccess::open(exe_path,FileAccess::READ); @@ -1207,32 +1308,42 @@ bool EditorExportPlatformPC::can_export(String *r_error) const { String err; bool valid=true; - String exe_path = EditorSettings::get_singleton()->get_settings_path()+"/templates/"; + if (use64 && (!exists_export_template(debug_binary64)) || !exists_export_template(release_binary64)) { + valid=false; + err="No 64 bits export templates found.\nDownload and install export templates.\n"; + } - if (!FileAccess::exists(exe_path+debug_binary32) || !FileAccess::exists(exe_path+release_binary32)) { + if (!use64 && (!exists_export_template(debug_binary32) || !exists_export_template(release_binary32))) { valid=false; err="No 32 bits export templates found.\nDownload and install export templates.\n"; } - if (!FileAccess::exists(exe_path+debug_binary64) || !FileAccess::exists(exe_path+release_binary64)) { - valid=false; - err="No 64 bits export templates found.\nDownload and install export templates.\n"; + + if(custom_debug_binary=="" && custom_release_binary=="") { + if (r_error) *r_error=err; + return valid; } + bool dvalid = true; + bool rvalid = true; - if (custom_debug_binary!="" && !FileAccess::exists(custom_debug_binary)) { - valid=false; - err+="Custom debug binary not found.\n"; + if(!FileAccess::exists(custom_debug_binary)) { + dvalid = false; + err = "Custom debug binary not found.\n"; } - if (custom_release_binary!="" && !FileAccess::exists(custom_release_binary)) { - valid=false; - err+="Custom release binary not found.\n"; + if(!FileAccess::exists(custom_release_binary)) { + rvalid = false; + err = "Custom release binary not found.\n"; } + if (dvalid || rvalid) + valid = true; + else + valid = false; + if (r_error) *r_error=err; return valid; - } @@ -1550,6 +1661,17 @@ void EditorImportExport::image_export_get_images_in_group(const StringName& p_gr } } +void EditorImportExport::set_convert_text_scenes(bool p_convert) { + + convert_text_scenes=p_convert; +} + +bool EditorImportExport::get_convert_text_scenes() const{ + + return convert_text_scenes; +} + + void EditorImportExport::load_config() { Ref<ConfigFile> cf = memnew( ConfigFile ); @@ -1592,6 +1714,12 @@ void EditorImportExport::load_config() { } } + if (cf->has_section("convert_scenes")) { + + convert_text_scenes = cf->get_value("convert_scenes","convert_text_scenes"); + } + + if (cf->has_section("export_filter_files")) { @@ -1706,6 +1834,17 @@ void EditorImportExport::load_config() { } } + if (cf->has_section("convert_samples")) { + + if (cf->has_section_key("convert_samples","max_hz")) + sample_action_max_hz=cf->get_value("convert_samples","max_hz"); + + if (cf->has_section_key("convert_samples","trim")) + sample_action_trim=cf->get_value("convert_samples","trim"); + } + + + } @@ -1814,8 +1953,18 @@ void EditorImportExport::save_config() { case SCRIPT_ACTION_ENCRYPT: cf->set_value("script","action","encrypt"); break; } + cf->set_value("convert_scenes","convert_text_scenes",convert_text_scenes); + cf->set_value("script","encrypt_key",script_key); + switch(sample_action) { + case SAMPLE_ACTION_NONE: cf->set_value("convert_samples","action","none"); break; + case SAMPLE_ACTION_COMPRESS_RAM: cf->set_value("convert_samples","action","compress_ram"); break; + } + + cf->set_value("convert_samples","max_hz",sample_action_max_hz); + cf->set_value("convert_samples","trim",sample_action_trim); + cf->save("res://export.cfg"); } @@ -1841,6 +1990,35 @@ String EditorImportExport::script_get_encryption_key() const{ } +void EditorImportExport::sample_set_action(SampleAction p_action) { + + sample_action=p_action; +} + +EditorImportExport::SampleAction EditorImportExport::sample_get_action() const{ + + return sample_action; +} + +void EditorImportExport::sample_set_max_hz(int p_hz){ + + sample_action_max_hz=p_hz; +} +int EditorImportExport::sample_get_max_hz() const{ + + return sample_action_max_hz; +} + +void EditorImportExport::sample_set_trim(bool p_trim){ + + sample_action_trim=p_trim; +} +bool EditorImportExport::sample_get_trim() const{ + + return sample_action_trim; +} + + void EditorImportExport::_bind_methods() { ObjectTypeDB::bind_method(_MD("image_export_group_create"),&EditorImportExport::image_export_group_create); @@ -1868,8 +2046,15 @@ EditorImportExport::EditorImportExport() { image_formats.insert("png"); image_shrink=1; + script_action=SCRIPT_ACTION_COMPILE; + sample_action=SAMPLE_ACTION_NONE; + sample_action_max_hz=44100; + sample_action_trim=false; + + convert_text_scenes=true; + } diff --git a/tools/editor/editor_import_export.h b/tools/editor/editor_import_export.h index 245adffbfd..3dc78c88aa 100644 --- a/tools/editor/editor_import_export.h +++ b/tools/editor/editor_import_export.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -33,6 +33,7 @@ #include "scene/main/node.h" #include "scene/resources/texture.h" + class EditorExportPlatform; class FileAccess; class EditorProgress; @@ -86,6 +87,8 @@ protected: Vector<uint8_t> get_exported_file_default(String& p_fname) const; virtual Vector<uint8_t> get_exported_file(String& p_fname) const; virtual Vector<StringName> get_dependencies(bool p_bundles) const; + virtual String find_export_template(String template_file_name, String *err=NULL) const; + virtual bool exists_export_template(String template_file_name, String *err=NULL) const; struct TempData { @@ -105,8 +108,17 @@ protected: }; + struct ZipData { + + void* zip; + EditorProgress *ep; + int count; + + }; + void gen_export_flags(Vector<String> &r_flags, int p_flags); static Error save_pack_file(void *p_userdata,const String& p_path, const Vector<uint8_t>& p_data,int p_file,int p_total); + static Error save_zip_file(void *p_userdata,const String& p_path, const Vector<uint8_t>& p_data,int p_file,int p_total); public: @@ -132,6 +144,8 @@ public: Error export_project_files(EditorExportSaveFunction p_func, void* p_udata,bool p_make_bundles); Error save_pack(FileAccess *p_where, bool p_make_bundles=false, int p_alignment = 1); + Error save_zip(const String& p_path, bool p_make_bundles=false); + virtual String get_name() const =0; virtual ImageCompression get_image_compression() const=0; virtual Ref<Texture> get_logo() const =0; @@ -245,6 +259,12 @@ public: SCRIPT_ACTION_ENCRYPT }; + enum SampleAction { + + SAMPLE_ACTION_NONE, + SAMPLE_ACTION_COMPRESS_RAM, + }; + protected: struct ImageGroup { @@ -274,6 +294,12 @@ protected: ScriptAction script_action; String script_key; + SampleAction sample_action; + int sample_action_max_hz; + bool sample_action_trim; + + bool convert_text_scenes; + static EditorImportExport* singleton; static void _bind_methods(); @@ -343,6 +369,18 @@ public: void script_set_encryption_key(const String& p_key); String script_get_encryption_key() const; + void sample_set_action(SampleAction p_action); + SampleAction sample_get_action() const; + + void sample_set_max_hz(int p_hz); + int sample_get_max_hz() const; + + void sample_set_trim(bool p_trim); + bool sample_get_trim() const; + + void set_convert_text_scenes(bool p_convert); + bool get_convert_text_scenes() const; + void load_config(); void save_config(); diff --git a/tools/editor/editor_log.cpp b/tools/editor/editor_log.cpp index 2d26490a8a..48f7c90066 100644 --- a/tools/editor/editor_log.cpp +++ b/tools/editor/editor_log.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -81,6 +81,7 @@ void EditorLog::_notification(int p_what) { log->add_color_override("default_color",get_color("font_color","Tree")); tb->set_normal_texture( get_icon("Collapse","EditorIcons")); tb->set_hover_texture( get_icon("CollapseHl","EditorIcons")); + //button->set_icon(get_icon("Console","EditorIcons")); } @@ -125,6 +126,7 @@ void EditorLog::add_message(const String& p_msg,bool p_error) { log->push_color(get_color("fg_error","Editor")); } else { button->set_icon(Ref<Texture>()); + } @@ -154,17 +156,20 @@ void EditorLog::_dragged(const Point2& p_ofs) { */ -ToolButton *EditorLog::get_button() { +Button *EditorLog::get_button() { return button; } void EditorLog::_flip_request() { - if (is_visible()) + if (is_visible()) { hide(); - else + button->show(); + } else { show(); + button->hide(); + } } void EditorLog::_undo_redo_cbk(void *p_self,const String& p_name) { @@ -200,7 +205,7 @@ EditorLog::EditorLog() { hb->add_child(title); - button = memnew( ToolButton ); + button = memnew( Button ); button->set_text_align(Button::ALIGN_LEFT); button->connect("pressed",this,"_flip_request"); button->set_focus_mode(FOCUS_NONE); diff --git a/tools/editor/editor_log.h b/tools/editor/editor_log.h index 6950ffa1a0..d7d46b70d3 100644 --- a/tools/editor/editor_log.h +++ b/tools/editor/editor_log.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -44,7 +44,7 @@ class EditorLog : public PanelContainer { OBJ_TYPE( EditorLog, PanelContainer ); - ToolButton *button; + Button *button; Button *clearbutton; Label *title; RichTextLabel *log; @@ -73,7 +73,7 @@ public: void add_message(const String& p_msg, bool p_error=false); void deinit(); - ToolButton *get_button(); + Button *get_button(); void clear(); EditorLog(); ~EditorLog(); diff --git a/tools/editor/editor_name_dialog.cpp b/tools/editor/editor_name_dialog.cpp new file mode 100644 index 0000000000..c221b908e0 --- /dev/null +++ b/tools/editor/editor_name_dialog.cpp @@ -0,0 +1,89 @@ +/*************************************************************************/ +/* editor_name_dialog.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "editor_name_dialog.h" +#include "object_type_db.h" +#include "os/keyboard.h" + +void EditorNameDialog::_line_input_event(const InputEvent& p_event) { + + if (p_event.type == InputEvent::KEY) { + + if (!p_event.key.pressed) + return; + + switch (p_event.key.scancode) { + case KEY_ENTER: + case KEY_RETURN: { + + if (get_hide_on_ok()) + hide(); + ok_pressed(); + accept_event(); + } break; + case KEY_ESCAPE: { + + hide(); + accept_event(); + } break; + } + } +} + +void EditorNameDialog::_post_popup() { + + ConfirmationDialog::_post_popup(); + name->clear(); + name->grab_focus(); +} + +void EditorNameDialog::ok_pressed() { + + if (name->get_text()!="") { + emit_signal("name_confirmed", name->get_text()); + } +} + +void EditorNameDialog::_bind_methods() { + + ObjectTypeDB::bind_method("_line_input_event",&EditorNameDialog::_line_input_event); + + ADD_SIGNAL(MethodInfo("name_confirmed",PropertyInfo( Variant::STRING,"name"))); +} + +EditorNameDialog::EditorNameDialog() +{ + name = memnew( LineEdit ); + add_child(name); + move_child(name, get_label()->get_index()+1); + name->set_margin(MARGIN_TOP,5); + name->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_BEGIN,5); + name->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,5); + name->connect("input_event", this, "_line_input_event"); +} diff --git a/tools/editor/console.h b/tools/editor/editor_name_dialog.h index aff425fcde..9e66908899 100644 --- a/tools/editor/console.h +++ b/tools/editor/editor_name_dialog.h @@ -1,11 +1,11 @@ /*************************************************************************/ -/* console.h */ +/* editor_name_dialog.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -26,91 +26,32 @@ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef CONSOLE_H -#define CONSOLE_H -#include "scene/gui/popup.h" -#include "scene/gui/button.h" -#include "scene/gui/tab_container.h" -#include "scene/gui/tree.h" -#include "scene/main/timer.h" -#include "output_strings.h" -#include "property_editor.h" -#include "scene_tree_editor.h" -#include "editor_data.h" +#ifndef EDITOR_NAME_DIALOG_H +#define EDITOR_NAME_DIALOG_H -class Console : public Popup { +#include "scene/gui/dialogs.h" +#include "scene/gui/line_edit.h" - OBJ_TYPE( Console, Popup ); +class EditorNameDialog : public ConfirmationDialog { - TabContainer *tabs; - OutputStrings *output; - OutputStrings *errors; - Control *status; - Control *inspect; - Control *globals; - Button *close; - int height; + OBJ_TYPE( EditorNameDialog, ConfirmationDialog ); - EditorHistory inspect_history; - SceneTreeEditor *inspect_tree_editor; - PropertyEditor *inspect_property_editor; - PropertyEditor *globals_property_editor; + LineEdit *name; - Tree *stats_tree; - - struct StatsItems { - - TreeItem *render_objects_in_frame; - TreeItem *material_changes_in_frame; - - TreeItem *usage_video_mem_total; - TreeItem *usage_video_mem_used; - TreeItem *usage_texture_mem_used; - TreeItem *usage_vertex_mem_used; - - TreeItem *usage_static_memory_total; - TreeItem *usage_static_memory; - TreeItem *usage_dynamic_memory_total; - TreeItem *usage_dynamic_memory; - TreeItem *usage_objects_instanced; - - } stats; - - struct OutputQueue { - - OutputStrings::LineType type; - Variant meta; - String text; - }; - - Mutex *output_queue_mutex; - List<OutputQueue> output_queue; - - - ErrorHandlerList err_handler; - PrintHandlerList print_handler; - - void _inspector_node_selected(); - - static void _error_handle(void *p_this,const char*p_function,const char* p_file,int p_line,const char *p_error, const char *p_explanation,ErrorHandlerType p_type); - static void _print_handle(void *p_this,const String& p_string); + void _line_input_event(const InputEvent& p_event); protected: - virtual void _window_input_event(InputEvent p_event); - virtual void _window_resize_event(); + static void _bind_methods(); + virtual void ok_pressed(); + virtual void _post_popup(); - void _stats_update_timer_callback(); - void _resized(); - void _close_pressed(); +public: - void _notification(int p_what); + LineEdit* get_line_edit() { return name; } - static void _bind_methods(); -public: - Console(); - ~Console(); + EditorNameDialog(); }; -#endif // CONSOLE_H +#endif // EDITOR_NAME_DIALOG_H diff --git a/tools/editor/editor_node.cpp b/tools/editor/editor_node.cpp index a3d7cbd7cf..9fe0409c0e 100644 --- a/tools/editor/editor_node.cpp +++ b/tools/editor/editor_node.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -102,6 +102,7 @@ #include "tools/editor/io_plugins/editor_sample_import_plugin.h" #include "tools/editor/io_plugins/editor_translation_import_plugin.h" #include "tools/editor/io_plugins/editor_mesh_import_plugin.h" +#include "tools/editor/io_plugins/editor_export_scene.h" #include "plugins/editor_preview_plugins.h" @@ -111,6 +112,8 @@ EditorNode *EditorNode::singleton=NULL; void EditorNode::_update_scene_tabs() { + bool show_rb = EditorSettings::get_singleton()->get("global/show_script_in_scene_tabs"); + scene_tabs->clear_tabs(); Ref<Texture> script_icon = gui_base->get_icon("Script","EditorIcons"); for(int i=0;i<editor_data.get_edited_scene_count();i++) { @@ -133,7 +136,7 @@ void EditorNode::_update_scene_tabs() { bool unsaved = (i==current)?saved_version!=editor_data.get_undo_redo().get_version():editor_data.get_scene_version(i)!=0; scene_tabs->add_tab(editor_data.get_scene_title(i)+(unsaved?"(*)":""),icon); - if (editor_data.get_scene_root_script(i).is_valid()) { + if (show_rb && editor_data.get_scene_root_script(i).is_valid()) { scene_tabs->set_tab_right_button(i,script_icon); } @@ -163,13 +166,22 @@ void EditorNode::_unhandled_input(const InputEvent& p_event) { switch(p_event.key.scancode) { + /*case KEY_F1: + if (!p_event.key.mod.shift && !p_event.key.mod.command) + _editor_select(EDITOR_SCRIPT); + break;*/ case KEY_F1: if (!p_event.key.mod.shift && !p_event.key.mod.command) - _editor_select(3); + _editor_select(EDITOR_2D); + break; + case KEY_F2: + if (!p_event.key.mod.shift && !p_event.key.mod.command) + _editor_select(EDITOR_3D); + break; + case KEY_F3: + if (!p_event.key.mod.shift && !p_event.key.mod.command) + _editor_select(EDITOR_SCRIPT); break; - case KEY_F2: _editor_select(0); break; - case KEY_F3: _editor_select(1); break; - case KEY_F4: _editor_select(2); break; case KEY_F5: _menu_option_confirm((p_event.key.mod.control&&p_event.key.mod.shift)?RUN_PLAY_CUSTOM_SCENE:RUN_PLAY,true); break; case KEY_F6: _menu_option_confirm(RUN_PLAY_SCENE,true); break; case KEY_F7: _menu_option_confirm(RUN_PAUSE,true); break; @@ -287,7 +299,7 @@ void EditorNode::_notification(int p_what) { VisualServer::get_singleton()->viewport_set_hide_canvas(get_scene_root()->get_viewport(),true); VisualServer::get_singleton()->viewport_set_disable_environment(get_viewport()->get_viewport_rid(),true); - _editor_select(1); + _editor_select(EDITOR_3D); if (defer_load_scene!="") { @@ -403,7 +415,7 @@ void EditorNode::_rebuild_import_menu() { PopupMenu* p = import_menu->get_popup(); p->clear(); - p->add_item("Sub-Scene", FILE_IMPORT_SUBSCENE); + p->add_item("Node from scene", FILE_IMPORT_SUBSCENE); p->add_separator(); for (int i = 0; i < editor_import_export->get_import_plugin_count(); i++) { p->add_item(editor_import_export->get_import_plugin(i)->get_visible_name(), IMPORT_PLUGIN_BASE + i); @@ -499,13 +511,21 @@ void EditorNode::save_resource_as(const Ref<Resource>& p_resource) { file->set_mode(EditorFileDialog::MODE_SAVE_FILE); bool relpaths = (p_resource->has_meta("__editor_relpaths__") && p_resource->get_meta("__editor_relpaths__").operator bool()); + current_option=RESOURCE_SAVE_AS; List<String> extensions; Ref<PackedScene> sd = memnew( PackedScene ); ResourceSaver::get_recognized_extensions(p_resource,&extensions); file->clear_filters(); + + List<String> preferred; for(int i=0;i<extensions.size();i++) { + if (p_resource->is_type("Script") && extensions[i]=="tres" || extensions[i]=="res" || extensions[i]=="xml") { + //this serves no purpose and confused people + continue; + } file->add_filter("*."+extensions[i]+" ; "+extensions[i].to_upper()); + preferred.push_back(extensions[i]); } //file->set_current_path(current_path); @@ -517,11 +537,11 @@ void EditorNode::save_resource_as(const Ref<Resource>& p_resource) { file->set_current_path(p_resource->get_path().replacen("."+ext,"."+extensions.front()->get())); } } - } else { + } else if (preferred.size()) { String existing; if (extensions.size()) { - existing="new_"+p_resource->get_type().to_lower()+"."+extensions.front()->get().to_lower(); + existing="new_"+p_resource->get_type().to_lower()+"."+preferred.front()->get().to_lower(); } file->set_current_path(existing); @@ -531,7 +551,6 @@ void EditorNode::save_resource_as(const Ref<Resource>& p_resource) { } - void EditorNode::_menu_option(int p_option) { _menu_option_confirm(p_option,false); @@ -573,59 +592,66 @@ void EditorNode::_dialog_display_file_error(String p_file,Error p_error) { } -void EditorNode::_get_scene_metadata() { +void EditorNode::_get_scene_metadata(const String& p_file) { Node *scene = editor_data.get_edited_scene_root(); if (!scene) return; + String path = EditorSettings::get_singleton()->get_project_settings_path().plus_file(p_file.get_file()+"-editstate-"+p_file.md5_text()+".cfg"); - if (scene->has_meta("__editor_plugin_states__")) { + Ref<ConfigFile> cf; + cf.instance(); - Dictionary md = scene->get_meta("__editor_plugin_states__"); - editor_data.set_editor_states(md); + Error err = cf->load(path); + if (err!=OK) + return; //must not exist - } + List<String> esl; + cf->get_section_keys("editor_states",&esl); - if (scene->has_meta("__editor_run_settings__")) { + Dictionary md; + for (List<String>::Element *E=esl.front();E;E=E->next()) { - Dictionary md = scene->get_meta("__editor_run_settings__"); - if (md.has("run_mode")) - run_settings_dialog->set_run_mode(md["run_mode"]); - if (md.has("custom_args")) - run_settings_dialog->set_custom_arguments(md["custom_args"]); + Variant st=cf->get_value("editor_states",E->get()); + if (st.get_type()) { + md[E->get()]=st; + } } + + editor_data.set_editor_states(md); + } -void EditorNode::_set_scene_metadata() { +void EditorNode::_set_scene_metadata(const String& p_file) { Node *scene = editor_data.get_edited_scene_root(); if (!scene) return; - { /* Editor States */ - Dictionary md = editor_data.get_editor_states(); + scene->set_meta("__editor_run_settings__",Variant()); //clear it (no point in keeping it) + scene->set_meta("__editor_plugin_states__",Variant()); - if (!md.empty()) { - scene->set_meta("__editor_plugin_states__",md); - } - } + String path = EditorSettings::get_singleton()->get_project_settings_path().plus_file(p_file.get_file()+"-editstate-"+p_file.md5_text()+".cfg"); - { /* Run Settings */ + Ref<ConfigFile> cf; + cf.instance(); + Dictionary md = editor_data.get_editor_states(); + List<Variant> keys; + md.get_key_list(&keys); - Dictionary md; - md["run_mode"]=run_settings_dialog->get_run_mode(); - md["custom_args"]=run_settings_dialog->get_custom_arguments(); - scene->set_meta("__editor_run_settings__",md); - } - + for(List<Variant>::Element *E=keys.front();E;E=E->next()) { + cf->set_value("editor_states",E->get(),md[E->get()]); + } + Error err = cf->save(path); + ERR_FAIL_COND(err!=OK); } @@ -877,7 +903,7 @@ void EditorNode::_save_scene_with_preview(String p_file) { } } - _editor_select(is2d?0:1); + _editor_select(is2d?EDITOR_2D:EDITOR_3D); VS::get_singleton()->viewport_queue_screen_capture(viewport); save.step("Creating Thumbnail",2); @@ -943,8 +969,24 @@ void EditorNode::_save_scene(String p_file) { } - _set_scene_metadata(); - Ref<PackedScene> sdata = memnew( PackedScene ); + _set_scene_metadata(p_file); + + + Ref<PackedScene> sdata; + + if (ResourceCache::has(p_file)) { + // something may be referencing this resource and we are good with that. + // we must update it, but also let the previous scene state go, as + // old version still work for referencing changes in instanced or inherited scenes + + sdata = Ref<PackedScene>( ResourceCache::get(p_file)->cast_to<PackedScene>() ); + if (sdata.is_valid()) + sdata->recreate_state(); + else + sdata.instance(); + } else { + sdata.instance(); + } Error err = sdata->pack(scene); @@ -1398,6 +1440,71 @@ void EditorNode::_dialog_action(String p_file) { save_resource_in_path(current_res,p_file); } break; + case SETTINGS_LAYOUT_SAVE: { + + if (p_file.empty()) + return; + + if (p_file=="Default") { + confirm_error->set_text("Cannot overwrite default layout!"); + confirm_error->popup_centered_minsize(); + return; + } + + Ref<ConfigFile> config; + config.instance(); + Error err = config->load(EditorSettings::get_singleton()->get_settings_path().plus_file("editor_layouts.cfg")); + + if (err==ERR_CANT_OPEN) { + config.instance(); // new config + } else if (err!=OK) { + confirm_error->set_text("Error trying to save layout!"); + confirm_error->popup_centered_minsize(); + return; + } + + _save_docks_to_config(config, p_file); + + config->save(EditorSettings::get_singleton()->get_settings_path().plus_file("editor_layouts.cfg")); + + layout_dialog->hide(); + _update_layouts_menu(); + + } break; + case SETTINGS_LAYOUT_DELETE: { + + if (p_file.empty()) + return; + + if (p_file=="Default") { + confirm_error->set_text("Cannot delete default layout!"); + confirm_error->popup_centered_minsize(); + return; + } + + Ref<ConfigFile> config; + config.instance(); + Error err = config->load(EditorSettings::get_singleton()->get_settings_path().plus_file("editor_layouts.cfg")); + + if (err!=OK || !config->has_section(p_file)) { + confirm_error->set_text("Layout name not found!"); + confirm_error->popup_centered_minsize(); + return; + } + + // erase + List<String> keys; + config->get_section_keys(p_file, &keys); + for (List<String>::Element *E=keys.front();E;E=E->next()) { + config->set_value(p_file, E->get(), Variant()); + } + + config->save(EditorSettings::get_singleton()->get_settings_path().plus_file("editor_layouts.cfg")); + + layout_dialog->hide(); + _update_layouts_menu(); + + } break; default: { //save scene? if (file->get_mode()==FileDialog::MODE_SAVE_FILE) { @@ -1551,6 +1658,10 @@ void EditorNode::_edit_current() { scene_tree_dock->set_selected(NULL); property_editor->edit( NULL ); object_menu->set_disabled(true); + + if (editor_plugin_over) + editor_plugin_over->make_visible(false); + return; } @@ -1617,10 +1728,8 @@ void EditorNode::_edit_current() { for(int i=0;i<editor_table.size();i++) { - if (editor_table[i]==main_plugin) { - main_editor_tabs->set_current_tab(i); - break; - } + + main_editor_buttons[i]->set_pressed(editor_table[i]==main_plugin); } } @@ -1740,8 +1849,10 @@ void EditorNode::_run(bool p_current,const String& p_custom) { } play_button->set_pressed(false); + play_button->set_icon(gui_base->get_icon("MainPlay","EditorIcons")); //pause_button->set_pressed(false); play_scene_button->set_pressed(false); + play_scene_button->set_icon(gui_base->get_icon("PlayScene","EditorIcons")); String current_filename; String run_filename; @@ -1859,8 +1970,10 @@ void EditorNode::_run(bool p_current,const String& p_custom) { emit_signal("play_pressed"); if (p_current) { play_scene_button->set_pressed(true); + play_scene_button->set_icon(gui_base->get_icon("Reload","EditorIcons")); } else { play_button->set_pressed(true); + play_button->set_icon(gui_base->get_icon("Reload","EditorIcons")); } _playing_edited=p_current; @@ -2008,6 +2121,11 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) { } break; + case SCENE_TAB_CLOSE: { + _remove_scene(tab_closing); + _update_scene_tabs(); + current_option = -1; + } break; case FILE_SAVE_SCENE: { @@ -2370,6 +2488,10 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) { log->add_message("REDO: "+action); } break; + case TOOLS_ORPHAN_RESOURCES: { + + orphan_resources->show(); + } break; case EDIT_REVERT: { @@ -2510,7 +2632,7 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) { case OBJECT_REQUEST_HELP: { if (current) { - _editor_select(3); + _editor_select(EDITOR_SCRIPT); emit_signal("request_help",current->get_type()); } @@ -2577,12 +2699,12 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) { call_dialog->popup_centered_ratio(); } break; case RUN_PLAY: { - + _menu_option_confirm(RUN_STOP,true); _run(false); } break; case RUN_PLAY_CUSTOM_SCENE: { - + _menu_option_confirm(RUN_STOP,true); quick_run->popup("PackedScene",true); quick_run->set_title("Quick Run Scene.."); @@ -2599,18 +2721,20 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) { editor_run.stop(); play_button->set_pressed(false); + play_button->set_icon(gui_base->get_icon("MainPlay","EditorIcons")); play_scene_button->set_pressed(false); + play_scene_button->set_icon(gui_base->get_icon("PlayScene","EditorIcons")); //pause_button->set_pressed(false); emit_signal("stop_pressed"); } break; case RUN_PLAY_SCENE: { - + _menu_option_confirm(RUN_STOP,true); _run(true); } break; case RUN_PLAY_NATIVE: { - + _menu_option_confirm(RUN_STOP,true); emit_signal("play_pressed"); editor_run.run_native_notify(); @@ -2846,7 +2970,7 @@ Control* EditorNode::get_viewport() { void EditorNode::_editor_select(int p_which) { static bool selecting=false; - if (selecting) + if (selecting || changing_scene) return; selecting=true; @@ -2854,7 +2978,9 @@ void EditorNode::_editor_select(int p_which) { ERR_FAIL_INDEX(p_which,editor_table.size()); - main_editor_tabs->set_current_tab(p_which); + for(int i=0;i<main_editor_buttons.size();i++) { + main_editor_buttons[i]->set_pressed(i==p_which); + } selecting=false; @@ -2872,6 +2998,8 @@ void EditorNode::_editor_select(int p_which) { editor_plugin_screen=new_editor; editor_plugin_screen->make_visible(true); editor_plugin_screen->selected_notify(); + + } void EditorNode::add_editor_plugin(EditorPlugin *p_editor) { @@ -2879,7 +3007,12 @@ void EditorNode::add_editor_plugin(EditorPlugin *p_editor) { if (p_editor->has_main_screen()) { - singleton->main_editor_tabs->add_tab(p_editor->get_name()); + ToolButton *tb = memnew( ToolButton ); + tb->set_toggle_mode(true); + tb->connect("pressed",singleton,"_editor_select",varray(singleton->main_editor_buttons.size())); + tb->set_text(p_editor->get_name()); + singleton->main_editor_buttons.push_back(tb); + singleton->main_editor_button_vb->add_child(tb); singleton->editor_table.push_back(p_editor); } singleton->editor_data.add_editor_plugin( p_editor ); @@ -2891,16 +3024,18 @@ void EditorNode::remove_editor_plugin(EditorPlugin *p_editor) { if (p_editor->has_main_screen()) { - for(int i=0;i<singleton->main_editor_tabs->get_tab_count();i++) { + for(int i=0;i<singleton->main_editor_buttons.size();i++) { + + if (p_editor->get_name()==singleton->main_editor_buttons[i]->get_name()) { - if (p_editor->get_name()==singleton->main_editor_tabs->get_tab_title(i)) { + memdelete( singleton->main_editor_buttons[i] ); + singleton->main_editor_buttons.remove(i); - singleton->main_editor_tabs->remove_tab(i); break; } } - singleton->main_editor_tabs->add_tab(p_editor->get_name()); + //singleton->main_editor_tabs->add_tab(p_editor->get_name()); singleton->editor_table.erase(p_editor); } singleton->remove_child(p_editor); @@ -2940,23 +3075,23 @@ void EditorNode::_remove_edited_scene() { _update_title(); _update_scene_tabs(); - if (editor_data.get_edited_scene_count()==1) { - //make new scene appear saved - set_current_version(editor_data.get_undo_redo().get_version()); - unsaved_cache=false; - } +// if (editor_data.get_edited_scene_count()==1) { +// //make new scene appear saved +// set_current_version(editor_data.get_undo_redo().get_version()); +// unsaved_cache=false; +// } } void EditorNode::_remove_scene(int index) { // printf("Attempting to remove scene %d (current is %d)\n", index, editor_data.get_edited_scene()); + if (editor_data.get_edited_scene() == index) { //Scene to remove is current scene _remove_edited_scene(); } else { - // Scene to remove is not active scene."); + // Scene to remove is not active scene editor_data.remove_scene(index); - editor_data.get_undo_redo().clear_history(); } } @@ -3034,7 +3169,7 @@ Error EditorNode::save_translatable_strings(const String& p_to_file) { OS::Time time = OS::get_singleton()->get_time(); f->store_line("# Translation Strings Dump."); f->store_line("# Created By."); - f->store_line("# \t"VERSION_FULL_NAME" (c) 2008-2015 Juan Linietsky, Ariel Manzur."); + f->store_line("# \t" VERSION_FULL_NAME " (c) 2008-2015 Juan Linietsky, Ariel Manzur."); f->store_line("# From Scene: "); f->store_line("# \t"+get_edited_scene()->get_filename()); f->store_line(""); @@ -3209,10 +3344,20 @@ Error EditorNode::save_optimized_copy(const String& p_scene,const String& p_pres } +int EditorNode::_get_current_main_editor() { + + for(int i=0;i<editor_table.size();i++) { + if (editor_table[i]==editor_plugin_screen) + return i; + } + + return 0; +} + Dictionary EditorNode::_get_main_scene_state() { Dictionary state; - state["main_tab"]=main_editor_tabs->get_current_tab(); + state["main_tab"]=_get_current_main_editor(); state["scene_tree_offset"]=scene_tree_dock->get_tree_editor()->get_scene_tree()->get_vscroll_bar()->get_val(); state["property_edit_offset"]=get_property_editor()->get_scene_tree()->get_vscroll_bar()->get_val(); state["saved_version"]=saved_version; @@ -3223,9 +3368,14 @@ Dictionary EditorNode::_get_main_scene_state() { void EditorNode::_set_main_scene_state(Dictionary p_state) { //print_line("set current 7 "); + changing_scene=false; +#if 0 if (p_state.has("main_tab")) { int idx = p_state["main_tab"]; + + + print_line("comes with tab: "+itos(idx)); int current=-1; for(int i=0;i<editor_table.size();i++) { if (editor_plugin_screen==editor_table[i]) { @@ -3234,12 +3384,41 @@ void EditorNode::_set_main_scene_state(Dictionary p_state) { } } + if (idx<2 && current<2) { //only set tab for 2D and 3D - _editor_select(p_state["main_tab"]); + _editor_select(idx); //print_line(" setting main tab: "+itos(p_state["main_tab"])); } } +#else + + if (get_edited_scene()) { + + int current=-1; + for(int i=0;i<editor_table.size();i++) { + if (editor_plugin_screen==editor_table[i]) { + current=i; + break; + } + } + + if (current<2) { + //use heuristic instead + + int n2d=0,n3d=0; + _find_node_types(get_edited_scene(),n2d,n3d); + if (n2d>n3d) { + _editor_select(EDITOR_2D); + } else if (n3d>n2d) { + _editor_select(EDITOR_3D); + + } + } + + } +#endif + if (p_state.has("scene_tree_offset")) scene_tree_dock->get_tree_editor()->get_scene_tree()->get_vscroll_bar()->set_val(p_state["scene_tree_offset"]); @@ -3248,6 +3427,14 @@ void EditorNode::_set_main_scene_state(Dictionary p_state) { //print_line("set current 8 "); + //this should only happen at the very end + + //changing_scene=true; //avoid script change from opening editor + ScriptEditor::get_singleton()->get_debugger()->update_live_edit_root(); + ScriptEditor::get_singleton()->set_scene_root_script( editor_data.get_scene_root_script(editor_data.get_edited_scene()) ); + editor_data.notify_edited_scene_changed(); + + //changing_scene=false; } @@ -3260,8 +3447,18 @@ void EditorNode::set_current_version(uint64_t p_version) { bool EditorNode::is_changing_scene() const { return changing_scene; } + +void EditorNode::_clear_undo_history() { + + get_undo_redo()->clear_history(); +} + void EditorNode::set_current_scene(int p_idx) { + if (editor_data.check_and_update_scene(p_idx)) { + call_deferred("_clear_undo_history"); + } + changing_scene=true; editor_data.save_edited_scene_state(editor_selection,&editor_history,_get_main_scene_state()); @@ -3312,8 +3509,6 @@ void EditorNode::set_current_scene(int p_idx) { call_deferred("_set_main_scene_state",state); //do after everything else is done setting up //print_line("set current 6 "); - changing_scene=false; - ScriptEditor::get_singleton()->get_debugger()->update_live_edit_root(); } @@ -3340,11 +3535,13 @@ Error EditorNode::load_scene(const String& p_scene, bool p_ignore_broken_deps,bo } - for(int i=0;i<editor_data.get_edited_scene_count();i++) { + if(!p_set_inherited) { + for(int i=0;i<editor_data.get_edited_scene_count();i++) { - if (editor_data.get_scene_path(i)==p_scene) { - _scene_tab_changed(i); - return OK; + if (editor_data.get_scene_path(i)==p_scene) { + _scene_tab_changed(i); + return OK; + } } } @@ -3464,16 +3661,17 @@ Error EditorNode::load_scene(const String& p_scene, bool p_ignore_broken_deps,bo if (p_set_inherited) { Ref<SceneState> state = sdata->get_state(); - state->set_path(lpath); + state->set_path(lpath); new_scene->set_scene_inherited_state(state); new_scene->set_filename(String()); - if (new_scene->get_scene_instance_state().is_valid()) - new_scene->get_scene_instance_state()->set_path(String()); + //if (new_scene->get_scene_instance_state().is_valid()) + // new_scene->get_scene_instance_state()->set_path(String()); } + new_scene->set_scene_instance_state(Ref<SceneState>()); set_edited_scene(new_scene); - _get_scene_metadata(); + _get_scene_metadata(p_scene); /* editor_data.set_edited_scene_root(new_scene); @@ -3752,9 +3950,7 @@ void EditorNode::_quick_run(const String& p_resource) { void EditorNode::notify_child_process_exited() { - play_button->set_pressed(false); - play_scene_button->set_pressed(false); - //pause_button->set_pressed(false); + _menu_option_confirm(RUN_STOP,false); stop_button->set_pressed(false); editor_run.stop(); @@ -3789,7 +3985,8 @@ bool EditorNode::_find_editing_changed_scene(Node *p_from) { void EditorNode::add_io_error(const String& p_error) { - + CharString err_ut = p_error.utf8(); + ERR_PRINT(err_ut.get_data()); _load_error_notify(singleton,p_error); } @@ -3862,9 +4059,9 @@ void EditorNode::progress_add_task(const String& p_task,const String& p_label, i singleton->progress_dialog->add_task(p_task,p_label,p_steps); } -void EditorNode::progress_task_step(const String& p_task, const String& p_state, int p_step) { +void EditorNode::progress_task_step(const String& p_task, const String& p_state, int p_step,bool p_force_redraw) { - singleton->progress_dialog->task_step(p_task,p_state,p_step); + singleton->progress_dialog->task_step(p_task,p_state,p_step,p_force_redraw); } @@ -3945,6 +4142,8 @@ void EditorNode::_bind_methods() { ObjectTypeDB::bind_method("_dock_move_left",&EditorNode::_dock_move_left); ObjectTypeDB::bind_method("_dock_move_right",&EditorNode::_dock_move_right); + ObjectTypeDB::bind_method("_layout_menu_option",&EditorNode::_layout_menu_option); + ObjectTypeDB::bind_method("set_current_scene",&EditorNode::set_current_scene); ObjectTypeDB::bind_method("set_current_version",&EditorNode::set_current_version); ObjectTypeDB::bind_method("_scene_tab_changed",&EditorNode::_scene_tab_changed); @@ -3956,6 +4155,9 @@ void EditorNode::_bind_methods() { ObjectTypeDB::bind_method("_prepare_history",&EditorNode::_prepare_history); ObjectTypeDB::bind_method("_select_history",&EditorNode::_select_history); + ObjectTypeDB::bind_method("_toggle_search_bar",&EditorNode::_toggle_search_bar); + ObjectTypeDB::bind_method("_clear_search_box",&EditorNode::_clear_search_box); + ObjectTypeDB::bind_method("_clear_undo_history",&EditorNode::_clear_undo_history); ObjectTypeDB::bind_method(_MD("add_editor_import_plugin", "plugin"), &EditorNode::add_editor_import_plugin); ObjectTypeDB::bind_method(_MD("remove_editor_import_plugin", "plugin"), &EditorNode::remove_editor_import_plugin); @@ -4237,6 +4439,15 @@ void EditorNode::_save_docks() { Ref<ConfigFile> config; config.instance(); + _save_docks_to_config(config, "docks"); + editor_data.get_plugin_window_layout(config); + + config->save(EditorSettings::get_singleton()->get_project_settings_path().plus_file("editor_layout.cfg")); + +} + +void EditorNode::_save_docks_to_config(Ref<ConfigFile> p_layout, const String& p_section) { + for(int i=0;i<DOCK_SLOT_MAX;i++) { String names; for(int j=0;j<dock_slot[i]->get_tab_count();j++) { @@ -4247,7 +4458,7 @@ void EditorNode::_save_docks() { } if (names!="") { - config->set_value("docks","dock_"+itos(i+1),names); + p_layout->set_value(p_section,"dock_"+itos(i+1),names); } } @@ -4261,7 +4472,7 @@ void EditorNode::_save_docks() { for(int i=0;i<DOCK_SLOT_MAX/2;i++) { if (splits[i]->is_visible()) { - config->set_value("docks","dock_split_"+itos(i+1),splits[i]->get_split_offset()); + p_layout->set_value(p_section,"dock_split_"+itos(i+1),splits[i]->get_split_offset()); } } @@ -4275,13 +4486,9 @@ void EditorNode::_save_docks() { for(int i=0;i<4;i++) { - config->set_value("docks","dock_hsplit_"+itos(i+1),h_splits[i]->get_split_offset()); + p_layout->set_value(p_section,"dock_hsplit_"+itos(i+1),h_splits[i]->get_split_offset()); } - editor_data.get_plugin_window_layout(config); - - config->save(EditorSettings::get_singleton()->get_project_settings_path().plus_file("editor_layout.cfg")); - } void EditorNode::save_layout() { @@ -4303,12 +4510,19 @@ void EditorNode::_load_docks() { return; //no config } + _load_docks_from_config(config, "docks"); + editor_data.set_plugin_window_layout(config); + +} + +void EditorNode::_load_docks_from_config(Ref<ConfigFile> p_layout, const String& p_section) { + for(int i=0;i<DOCK_SLOT_MAX;i++) { - if (!config->has_section_key("docks","dock_"+itos(i+1))) + if (!p_layout->has_section_key(p_section,"dock_"+itos(i+1))) continue; - Vector<String> names = String(config->get_value("docks","dock_"+itos(i+1))).split(","); + Vector<String> names = String(p_layout->get_value(p_section,"dock_"+itos(i+1))).split(","); for(int j=0;j<names.size();j++) { @@ -4328,7 +4542,7 @@ void EditorNode::_load_docks() { if (atidx==-1) //well, it's not anywhere continue; - if (atidx==j) { + if (atidx==i) { node->raise(); continue; } @@ -4343,7 +4557,6 @@ void EditorNode::_load_docks() { dock_slot[i]->add_child(node); dock_slot[i]->show(); } - } VSplitContainer*splits[DOCK_SLOT_MAX/2]={ @@ -4355,14 +4568,14 @@ void EditorNode::_load_docks() { for(int i=0;i<DOCK_SLOT_MAX/2;i++) { - if (!config->has_section_key("docks","dock_split_"+itos(i+1))) + if (!p_layout->has_section_key(p_section,"dock_split_"+itos(i+1))) continue; - int ofs = config->get_value("docks","dock_split_"+itos(i+1)); + int ofs = p_layout->get_value(p_section,"dock_split_"+itos(i+1)); splits[i]->set_split_offset(ofs); } - HSplitContainer *h_splits[4]={ + HSplitContainer*h_splits[4]={ left_l_hsplit, left_r_hsplit, main_hsplit, @@ -4370,9 +4583,9 @@ void EditorNode::_load_docks() { }; for(int i=0;i<4;i++) { - if (!config->has_section_key("docks","dock_hsplit_"+itos(i+1))) + if (!p_layout->has_section_key(p_section,"dock_hsplit_"+itos(i+1))) continue; - int ofs = config->get_value("docks","dock_hsplit_"+itos(i+1)); + int ofs = p_layout->get_value(p_section,"dock_hsplit_"+itos(i+1)); h_splits[i]->set_split_offset(ofs); } @@ -4390,8 +4603,75 @@ void EditorNode::_load_docks() { dock_slot[i]->set_current_tab(0); } } +} - editor_data.set_plugin_window_layout(config); + +void EditorNode::_update_layouts_menu() { + + editor_layouts->clear(); + editor_layouts->set_size(Vector2()); + editor_layouts->add_item("Save Layout", SETTINGS_LAYOUT_SAVE); + editor_layouts->add_item("Delete Layout", SETTINGS_LAYOUT_DELETE); + editor_layouts->add_separator(); + editor_layouts->add_item("Default", SETTINGS_LAYOUT_DEFAULT); + + Ref<ConfigFile> config; + config.instance(); + Error err = config->load(EditorSettings::get_singleton()->get_settings_path().plus_file("editor_layouts.cfg")); + if (err!=OK) { + return; //no config + } + + List<String> layouts; + config.ptr()->get_sections(&layouts); + + for (List<String>::Element *E=layouts.front();E;E=E->next()) { + + String layout=E->get(); + + if (layout!="Default") + editor_layouts->add_item(layout); + } + +} + +void EditorNode::_layout_menu_option(int p_id) { + + switch (p_id) { + + case SETTINGS_LAYOUT_SAVE: { + + current_option=p_id; + layout_dialog->set_title("Save Layout"); + layout_dialog->get_ok()->set_text("Save"); + layout_dialog->popup_centered(); + } break; + case SETTINGS_LAYOUT_DELETE: { + + current_option=p_id; + layout_dialog->set_title("Delete Layout"); + layout_dialog->get_ok()->set_text("Delete"); + layout_dialog->popup_centered(); + } break; + case SETTINGS_LAYOUT_DEFAULT: { + + _load_docks_from_config(default_theme, "docks"); + _save_docks(); + } break; + default: { + + Ref<ConfigFile> config; + config.instance(); + Error err = config->load(EditorSettings::get_singleton()->get_settings_path().plus_file("editor_layouts.cfg")); + if (err!=OK) { + return; //no config + } + + _load_docks_from_config(config, editor_layouts->get_item_text(p_id)); + _save_docks(); + + } + } } @@ -4404,8 +4684,19 @@ void EditorNode::_scene_tab_script_edited(int p_tab) { } void EditorNode::_scene_tab_closed(int p_tab) { - _remove_scene(p_tab); - _update_scene_tabs(); + current_option = SCENE_TAB_CLOSE; + tab_closing = p_tab; + if (unsaved_cache) { + confirmation->get_ok()->set_text("Yes"); + //confirmation->get_cancel()->show(); + confirmation->set_text("Close scene? (Unsaved changes will be lost)"); + confirmation->popup_centered_minsize(); + } + else { + _remove_scene(p_tab); + //_update_scene_tabs(); + } + } @@ -4438,6 +4729,30 @@ void EditorNode::_scene_tab_changed(int p_tab) { } +void EditorNode::_toggle_search_bar(bool p_pressed) { + + property_editor->set_use_filter(p_pressed); + + if (p_pressed) { + + search_bar->show(); + search_box->grab_focus(); + search_box->select_all(); + } else { + + search_bar->hide(); + } +} + +void EditorNode::_clear_search_box() { + + if (search_box->get_text()=="") + return; + + search_box->clear(); + property_editor->update_tree(); +} + EditorNode::EditorNode() { EditorHelp::generate_doc(); //before any editor classes are crated @@ -4469,6 +4784,8 @@ EditorNode::EditorNode() { ResourceLoader::set_abort_on_missing_resources(false); FileDialog::set_default_show_hidden_files(EditorSettings::get_singleton()->get("file_dialog/show_hidden_files")); + EditorFileDialog::set_default_show_hidden_files(EditorSettings::get_singleton()->get("file_dialog/show_hidden_files")); + EditorFileDialog::set_default_display_mode((EditorFileDialog::DisplayMode)EditorSettings::get_singleton()->get("file_dialog/display_mode").operator int()); ResourceLoader::set_error_notify_func(this,_load_error_notify); ResourceLoader::set_dependency_error_notify_func(this,_dependency_error_report); @@ -4551,6 +4868,7 @@ EditorNode::EditorNode() { gui_base->add_child(main_vbox); main_vbox->set_area_as_parent_rect(8); +#if 0 PanelContainer *top_dark_panel = memnew( PanelContainer ); Ref<StyleBoxTexture> top_dark_sb; top_dark_sb.instance();; @@ -4566,21 +4884,14 @@ EditorNode::EditorNode() { VBoxContainer *top_dark_vb = memnew( VBoxContainer ); main_vbox->add_child(top_dark_panel); top_dark_panel->add_child(top_dark_vb); - +#endif menu_hb = memnew( HBoxContainer ); - top_dark_vb->add_child(menu_hb); + main_vbox->add_child(menu_hb); - scene_tabs=memnew( Tabs ); - scene_tabs->add_tab("unsaved"); - scene_tabs->set_tab_align(Tabs::ALIGN_CENTER); - scene_tabs->set_tab_close_display_policy(Tabs::SHOW_HOVER); - scene_tabs->connect("tab_changed",this,"_scene_tab_changed"); - scene_tabs->connect("right_button_pressed",this,"_scene_tab_script_edited"); - scene_tabs->connect("tab_close", this, "_scene_tab_closed"); - top_dark_vb->add_child(scene_tabs); +// top_dark_vb->add_child(scene_tabs); //left left_l_hsplit = memnew( HSplitContainer ); main_vbox->add_child(left_l_hsplit); @@ -4613,11 +4924,15 @@ EditorNode::EditorNode() { main_hsplit = memnew( HSplitContainer ); left_r_hsplit->add_child(main_hsplit); //main_split->set_v_size_flags(Control::SIZE_EXPAND_FILL); + VBoxContainer * center_vb = memnew( VBoxContainer); + main_hsplit->add_child(center_vb); + center_vb->set_h_size_flags(Control::SIZE_EXPAND_FILL); center_split = memnew( VSplitContainer ); - main_hsplit->add_child(center_split); - center_split->set_h_size_flags(Control::SIZE_EXPAND_FILL); + //main_hsplit->add_child(center_split); + center_split->set_v_size_flags(Control::SIZE_EXPAND_FILL); center_split->set_collapsed(false); + center_vb->add_child(center_split); right_hsplit = memnew( HSplitContainer ); main_hsplit->add_child(right_hsplit); @@ -4628,6 +4943,9 @@ EditorNode::EditorNode() { right_l_vsplit->add_child(dock_slot[DOCK_SLOT_RIGHT_UL]); dock_slot[DOCK_SLOT_RIGHT_BL]=memnew( TabContainer ); right_l_vsplit->add_child(dock_slot[DOCK_SLOT_RIGHT_BL]); + //right_l_vsplit->hide(); + //dock_slot[DOCK_SLOT_RIGHT_UL]->hide(); + //dock_slot[DOCK_SLOT_RIGHT_BL]->hide(); right_r_vsplit = memnew( VSplitContainer ); right_hsplit->add_child(right_r_vsplit); @@ -4636,8 +4954,8 @@ EditorNode::EditorNode() { dock_slot[DOCK_SLOT_RIGHT_BR]=memnew( TabContainer ); right_r_vsplit->add_child(dock_slot[DOCK_SLOT_RIGHT_BR]); right_r_vsplit->hide(); - //dock_slot[DOCK_SLOT_RIGHT_UL]->hide(); - //dock_slot[DOCK_SLOT_RIGHT_BL]->hide(); + dock_slot[DOCK_SLOT_RIGHT_UR]->hide(); + dock_slot[DOCK_SLOT_RIGHT_BR]->hide(); left_l_vsplit->connect("dragged",this,"_dock_split_dragged"); left_r_vsplit->connect("dragged",this,"_dock_split_dragged"); @@ -4714,20 +5032,19 @@ EditorNode::EditorNode() { srt->add_constant_override("separation",0); - main_editor_tabs = memnew( Tabs ); +/* main_editor_tabs = memnew( Tabs ); main_editor_tabs->connect("tab_changed",this,"_editor_select"); main_editor_tabs->set_tab_close_display_policy(Tabs::SHOW_NEVER); - HBoxContainer *srth = memnew( HBoxContainer ); - srt->add_child( srth ); - Control *tec = memnew( Control ); - tec->set_custom_minimum_size(Size2(100,0)); - tec->set_h_size_flags(Control::SIZE_EXPAND_FILL); - srth->add_child(tec); - srth->add_child(main_editor_tabs); - tec = memnew( Control ); - tec->set_custom_minimum_size(Size2(100,0)); - srth->add_child(tec); - tec->set_h_size_flags(Control::SIZE_EXPAND_FILL); +*/ + scene_tabs=memnew( Tabs ); + scene_tabs->add_tab("unsaved"); + scene_tabs->set_tab_align(Tabs::ALIGN_CENTER); + scene_tabs->set_tab_close_display_policy(Tabs::SHOW_ACTIVE_ONLY); + scene_tabs->connect("tab_changed",this,"_scene_tab_changed"); + scene_tabs->connect("right_button_pressed",this,"_scene_tab_script_edited"); + scene_tabs->connect("tab_close", this, "_scene_tab_closed"); + + srt->add_child(scene_tabs); scene_root_parent = memnew( Panel ); @@ -4804,6 +5121,8 @@ EditorNode::EditorNode() { anim_close->set_pressed_texture( anim_close->get_icon("Close","EditorIcons")); + + PanelContainer *top_region = memnew( PanelContainer ); top_region->add_style_override("panel",gui_base->get_stylebox("hover","Button")); HBoxContainer *left_menu_hb = memnew( HBoxContainer ); @@ -4872,7 +5191,7 @@ EditorNode::EditorNode() { p->add_separator(); p->add_item("Revert Scene",EDIT_REVERT); p->add_separator(); - p->add_item("Quit to Project List",RUN_PROJECT_MANAGER,KEY_MASK_SHIFT+KEY_MASK_CMD+KEY_Q); + p->add_item("Quit to Project List",RUN_PROJECT_MANAGER,KEY_MASK_SHIFT+KEY_MASK_ALT+KEY_Q); p->add_item("Quit",FILE_QUIT,KEY_MASK_CMD+KEY_Q); recent_scenes = memnew( PopupMenu ); @@ -4880,6 +5199,18 @@ EditorNode::EditorNode() { p->add_child(recent_scenes); recent_scenes->connect("item_pressed",this,"_open_recent_scene"); + { + Control *sp = memnew( Control ); + sp->set_custom_minimum_size(Size2(30,0)); + menu_hb->add_child(sp); + } + + PanelContainer *editor_region = memnew( PanelContainer ); + editor_region->add_style_override("panel",gui_base->get_stylebox("hover","Button")); + main_editor_button_vb = memnew( HBoxContainer ); + editor_region->add_child(main_editor_button_vb); + menu_hb->add_child(editor_region); + //menu_hb->add_spacer(); #if 0 node_menu = memnew( MenuButton ); @@ -4918,6 +5249,17 @@ EditorNode::EditorNode() { p=import_menu->get_popup(); p->connect("item_pressed",this,"_menu_option"); + tool_menu = memnew( MenuButton ); + tool_menu->set_tooltip("Miscelaneous project or scene wide tools."); + tool_menu->set_text("Tools"); + + //tool_menu->set_icon(gui_base->get_icon("Save","EditorIcons")); + left_menu_hb->add_child( tool_menu ); + + p=tool_menu->get_popup(); + p->connect("item_pressed",this,"_menu_option"); + p->add_item("Orphan Resource Explorer",TOOLS_ORPHAN_RESOURCES); + export_button = memnew( ToolButton ); export_button->set_tooltip("Export the project to many platforms."); export_button->set_text("Export"); @@ -5040,6 +5382,39 @@ EditorNode::EditorNode() { */ + progress_hb = memnew( BackgroundProgress ); + menu_hb->add_child(progress_hb); + + { + Control *sp = memnew( Control ); + sp->set_custom_minimum_size(Size2(30,0)); + menu_hb->add_child(sp); + } + + + PanelContainer *vu_cont = memnew( PanelContainer ); + vu_cont->add_style_override("panel",gui_base->get_stylebox("hover","Button")); + menu_hb->add_child(vu_cont); + + audio_vu = memnew( TextureProgress ); + CenterContainer *vu_cc = memnew( CenterContainer ); + vu_cc->add_child(audio_vu); + vu_cont->add_child(vu_cc); + audio_vu->set_under_texture(gui_base->get_icon("VuEmpty","EditorIcons")); + audio_vu->set_progress_texture(gui_base->get_icon("VuFull","EditorIcons")); + audio_vu->set_max(24); + audio_vu->set_min(-80); + audio_vu->set_step(0.01); + audio_vu->set_val(0); + + { + Control *sp = memnew( Control ); + sp->set_custom_minimum_size(Size2(30,0)); + menu_hb->add_child(sp); + } + + + top_region = memnew( PanelContainer ); top_region->add_style_override("panel",gui_base->get_stylebox("hover","Button")); HBoxContainer *right_menu_hb = memnew( HBoxContainer ); @@ -5053,17 +5428,29 @@ EditorNode::EditorNode() { right_menu_hb->add_child( settings_menu ); p=settings_menu->get_popup(); - //p->add_item("Export Settings",SETTINGS_EXPORT_PREFERENCES); p->add_item("Editor Settings",SETTINGS_PREFERENCES); //p->add_item("Optimization Presets",SETTINGS_OPTIMIZED_PRESETS); p->add_separator(); + editor_layouts = memnew( PopupMenu ); + editor_layouts->set_name("Layouts"); + p->add_child(editor_layouts); + editor_layouts->connect("item_pressed",this,"_layout_menu_option"); + p->add_submenu_item("Editor Layout", "Layouts"); + p->add_separator(); p->add_check_item("Show Animation",SETTINGS_SHOW_ANIMATION,KEY_MASK_CMD+KEY_N); p->add_separator(); p->add_item("Install Export Templates",SETTINGS_LOAD_EXPORT_TEMPLATES); p->add_separator(); p->add_item("About",SETTINGS_ABOUT); + layout_dialog = memnew( EditorNameDialog ); + gui_base->add_child(layout_dialog); + layout_dialog->set_hide_on_ok(false); + layout_dialog->set_size(Size2(175, 70)); + confirm_error = memnew( AcceptDialog ); + layout_dialog->add_child(confirm_error); + layout_dialog->connect("name_confirmed", this,"_dialog_action"); sources_button = memnew( ToolButton ); right_menu_hb->add_child(sources_button); @@ -5071,6 +5458,15 @@ EditorNode::EditorNode() { sources_button->connect("pressed",this,"_menu_option",varray(SOURCES_REIMPORT)); sources_button->set_tooltip("Alerts when an external resource has changed."); + update_menu = memnew( MenuButton ); + update_menu->set_tooltip("Spins when the editor window repaints!"); + right_menu_hb->add_child(update_menu); + update_menu->set_icon(gui_base->get_icon("Progress1","EditorIcons")); + p=update_menu->get_popup(); + p->add_check_item("Update Always",SETTINGS_UPDATE_ALWAYS); + p->add_check_item("Update Changes",SETTINGS_UPDATE_CHANGES); + p->set_item_checked(1,true); + //sources_button->connect(); /* @@ -5173,6 +5569,7 @@ EditorNode::EditorNode() { editor_history_menu = memnew( MenuButton ); + editor_history_menu->set_tooltip("History of recently edited objects"); editor_history_menu->set_icon( gui_base->get_icon("History","EditorIcons")); prop_editor_hb->add_child(editor_history_menu); editor_history_menu->connect("about_to_show",this,"_prepare_history"); @@ -5186,6 +5583,12 @@ EditorNode::EditorNode() { editor_path->set_h_size_flags(Control::SIZE_EXPAND_FILL); prop_editor_hb->add_child(editor_path); + search_button = memnew( ToolButton ); + search_button->set_toggle_mode(true); + search_button->set_pressed(false); + search_button->set_icon(gui_base->get_icon("Zoom","EditorIcons")); + prop_editor_hb->add_child(search_button); + search_button->connect("toggled",this,"_toggle_search_bar"); object_menu = memnew( MenuButton ); object_menu->set_icon(gui_base->get_icon("Tools","EditorIcons")); @@ -5197,6 +5600,22 @@ EditorNode::EditorNode() { create_dialog->set_base_type("Resource"); create_dialog->connect("create",this,"_resource_created"); + search_bar = memnew( HBoxContainer ); + search_bar->set_h_size_flags(Control::SIZE_EXPAND_FILL); + prop_editor_base->add_child(search_bar); + search_bar->hide(); + + l = memnew( Label("Search: ") ); + search_bar->add_child(l); + + search_box = memnew( LineEdit ); + search_box->set_h_size_flags(Control::SIZE_EXPAND_FILL); + search_bar->add_child(search_box); + + ToolButton *clear_button = memnew( ToolButton ); + clear_button->set_icon(gui_base->get_icon("Close","EditorIcons")); + search_bar->add_child(clear_button); + clear_button->connect("pressed",this,"_clear_search_box"); property_editor = memnew( PropertyEditor ); property_editor->set_autoclear(true); @@ -5205,6 +5624,7 @@ EditorNode::EditorNode() { property_editor->set_use_doc_hints(true); property_editor->hide_top_label(); + property_editor->register_text_enter(search_box); prop_editor_base->add_child( property_editor ); property_editor->set_undo_redo(&editor_data.get_undo_redo()); @@ -5212,18 +5632,33 @@ EditorNode::EditorNode() { scenes_dock = memnew( ScenesDock(this) ); scenes_dock->set_name("FileSystem"); + scenes_dock->set_use_thumbnails(int(EditorSettings::get_singleton()->get("file_dialog/display_mode"))==EditorFileDialog::DISPLAY_THUMBNAILS); dock_slot[DOCK_SLOT_LEFT_BR]->add_child(scenes_dock); //prop_pallete->add_child(scenes_dock); scenes_dock->connect("open",this,"open_request"); scenes_dock->connect("instance",this,"_instance_request"); + const String docks_section = "docks"; + + default_theme.instance(); + default_theme->set_value(docks_section, "dock_3", "Scene"); + default_theme->set_value(docks_section, "dock_4", "FileSystem"); + default_theme->set_value(docks_section, "dock_5", "Inspector"); + for(int i=0;i<DOCK_SLOT_MAX/2;i++) + default_theme->set_value(docks_section, "dock_hsplit_"+itos(i+1), 0); + for(int i=0;i<DOCK_SLOT_MAX/2;i++) + default_theme->set_value(docks_section, "dock_split_"+itos(i+1), 0); + + _update_layouts_menu(); log = memnew( EditorLog ); center_split->add_child(log); log->connect("close_request",this,"_close_messages"); log->connect("show_request",this,"_show_messages"); //left_split->set_dragger_visible(false); + + old_split_ofs=0; @@ -5241,37 +5676,18 @@ EditorNode::EditorNode() { animation_editor->hide(); - PanelContainer *bottom_pc = memnew( PanelContainer ); - main_vbox->add_child(bottom_pc); + /*PanelContainer *bottom_pc = memnew( PanelContainer ); + srt->add_child(bottom_pc); bottom_hb = memnew( HBoxContainer ); - bottom_pc->add_child(bottom_hb); + bottom_pc->add_child(bottom_hb);*/ - bottom_hb->add_child( log->get_button() ); + center_vb->add_child( log->get_button() ); log->get_button()->set_h_size_flags(Control::SIZE_EXPAND_FILL); - progress_hb = memnew( BackgroundProgress ); - bottom_hb->add_child(progress_hb); + //progress_hb->set_h_size_flags(Control::SIZE_EXPAND_FILL); - audio_vu = memnew( TextureProgress ); - CenterContainer *vu_cc = memnew( CenterContainer ); - vu_cc->add_child(audio_vu); - bottom_hb->add_child(vu_cc); - audio_vu->set_under_texture(gui_base->get_icon("VuEmpty","EditorIcons")); - audio_vu->set_progress_texture(gui_base->get_icon("VuFull","EditorIcons")); - audio_vu->set_max(24); - audio_vu->set_min(-80); - audio_vu->set_step(0.01); - audio_vu->set_val(0); - update_menu = memnew( MenuButton ); - update_menu->set_tooltip("Spins when the editor window repaints!"); - bottom_hb->add_child(update_menu); - update_menu->set_icon(gui_base->get_icon("Progress1","EditorIcons")); - p=update_menu->get_popup(); - p->add_check_item("Update Always",SETTINGS_UPDATE_ALWAYS); - p->add_check_item("Update Changes",SETTINGS_UPDATE_CHANGES); - p->set_item_checked(1,true); /* animation_menu = memnew( ToolButton ); @@ -5297,7 +5713,8 @@ EditorNode::EditorNode() { - + orphan_resources = memnew( OrphanResourcesDialog ); + gui_base->add_child(orphan_resources); @@ -5488,11 +5905,12 @@ EditorNode::EditorNode() { editor_import_export->add_import_plugin( Ref<EditorTranslationImportPlugin>( memnew(EditorTranslationImportPlugin(this)))); editor_import_export->add_export_plugin( Ref<EditorTextureExportPlugin>( memnew(EditorTextureExportPlugin))); + editor_import_export->add_export_plugin( Ref<EditorSampleExportPlugin>( memnew(EditorSampleExportPlugin))); + editor_import_export->add_export_plugin( Ref<EditorSceneExportPlugin>( memnew(EditorSceneExportPlugin))); add_editor_plugin( memnew( CanvasItemEditorPlugin(this) ) ); add_editor_plugin( memnew( SpatialEditorPlugin(this) ) ); add_editor_plugin( memnew( ScriptEditorPlugin(this) ) ); - add_editor_plugin( memnew( EditorHelpPlugin(this) ) ); add_editor_plugin( memnew( AnimationPlayerEditorPlugin(this) ) ); add_editor_plugin( memnew( ShaderGraphEditorPlugin(this,true) ) ); add_editor_plugin( memnew( ShaderGraphEditorPlugin(this,false) ) ); @@ -5539,9 +5957,10 @@ EditorNode::EditorNode() { resource_preview->add_preview_generator( Ref<EditorScriptPreviewPlugin>( memnew(EditorScriptPreviewPlugin ))); resource_preview->add_preview_generator( Ref<EditorSamplePreviewPlugin>( memnew(EditorSamplePreviewPlugin ))); resource_preview->add_preview_generator( Ref<EditorMeshPreviewPlugin>( memnew(EditorMeshPreviewPlugin ))); + resource_preview->add_preview_generator( Ref<EditorBitmapPreviewPlugin>( memnew(EditorBitmapPreviewPlugin ))); circle_step_msec=OS::get_singleton()->get_ticks_msec(); - circle_step_frame=OS::get_singleton()->get_frames_drawn();; + circle_step_frame=OS::get_singleton()->get_frames_drawn(); circle_step=0; _rebuild_import_menu(); @@ -5559,9 +5978,9 @@ EditorNode::EditorNode() { Globals::get_singleton()->set("debug/indicators_enabled",true); Globals::get_singleton()->set("render/room_cull_enabled",false); - theme->set_color("prop_category","Editor",Color::hex(0x403d41ff)); - theme->set_color("prop_section","Editor",Color::hex(0x383539ff)); - theme->set_color("prop_subsection","Editor",Color::hex(0x343135ff)); + theme->set_color("prop_category","Editor",Color::hex(0x3f3a44ff)); + theme->set_color("prop_section","Editor",Color::hex(0x35313aff)); + theme->set_color("prop_subsection","Editor",Color::hex(0x312e37ff)); theme->set_color("fg_selected","Editor",Color::html("ffbd8e8e")); theme->set_color("fg_error","Editor",Color::html("ffbd8e8e")); @@ -5668,6 +6087,7 @@ EditorNode::EditorNode() { EditorNode::~EditorNode() { + memdelete( EditorHelp::get_doc_data() ); memdelete(editor_selection); memdelete(file_server); EditorSettings::destroy(); diff --git a/tools/editor/editor_node.h b/tools/editor/editor_node.h index 56e455c9c0..2228e0948b 100644 --- a/tools/editor/editor_node.h +++ b/tools/editor/editor_node.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -76,6 +76,7 @@ #include "editor_reimport_dialog.h" #include "import_settings.h" #include "tools/editor/editor_plugin.h" +#include "tools/editor/editor_name_dialog.h" #include "fileserver/editor_file_server.h" #include "editor_resource_preview.h" @@ -133,6 +134,7 @@ class EditorNode : public Node { EDIT_UNDO, EDIT_REDO, EDIT_REVERT, + TOOLS_ORPHAN_RESOURCES, RESOURCE_NEW, RESOURCE_LOAD, RESOURCE_SAVE, @@ -166,6 +168,9 @@ class EditorNode : public Node { SETTINGS_EXPORT_PREFERENCES, SETTINGS_PREFERENCES, SETTINGS_OPTIMIZED_PRESETS, + SETTINGS_LAYOUT_SAVE, + SETTINGS_LAYOUT_DELETE, + SETTINGS_LAYOUT_DEFAULT, SETTINGS_SHOW_ANIMATION, SETTINGS_LOAD_EXPORT_TEMPLATES, SETTINGS_HELP, @@ -173,6 +178,7 @@ class EditorNode : public Node { SOURCES_REIMPORT, DEPENDENCY_LOAD_CHANGED_IMAGES, DEPENDENCY_UPDATE_IMPORTED, + SCENE_TAB_CLOSE, IMPORT_PLUGIN_BASE=100, @@ -217,6 +223,7 @@ class EditorNode : public Node { //main tabs Tabs *scene_tabs; + int tab_closing; int old_split_ofs; @@ -235,6 +242,7 @@ class EditorNode : public Node { Control *viewport; MenuButton *file_menu; MenuButton *import_menu; + MenuButton *tool_menu; ToolButton *export_button; ToolButton *prev_scene; MenuButton *object_menu; @@ -248,6 +256,7 @@ class EditorNode : public Node { ToolButton *play_scene_button; ToolButton *play_custom_scene_button; MenuButton *debug_button; + ToolButton *search_button; TextureProgress *audio_vu; //MenuButton *fileserver_menu; @@ -266,6 +275,9 @@ class EditorNode : public Node { ScenesDock *scenes_dock; EditorRunNative *run_native; + HBoxContainer *search_bar; + LineEdit *search_box; + CreateDialog *create_dialog; CallDialog *call_dialog; @@ -276,6 +288,11 @@ class EditorNode : public Node { AcceptDialog *about; AcceptDialog *warning; + Ref<ConfigFile> default_theme; + PopupMenu *editor_layouts; + EditorNameDialog *layout_dialog; + AcceptDialog *confirm_error; + //OptimizedPresetsDialog *optimized_presets; EditorSettingsDialog *settings_config_dialog; RunSettingsDialog *run_settings_dialog; @@ -314,7 +331,9 @@ class EditorNode : public Node { CenterContainer *tabs_center; EditorQuickOpen *quick_open; EditorQuickOpen *quick_run; - Tabs *main_editor_tabs; + + HBoxContainer *main_editor_button_vb; + Vector<ToolButton*> main_editor_buttons; Vector<EditorPlugin*> editor_table; EditorReImportDialog *reimport_dialog; @@ -325,6 +344,7 @@ class EditorNode : public Node { DependencyErrorDialog *dependency_error; DependencyEditor *dependency_fixer; + OrphanResourcesDialog *orphan_resources; TabContainer *dock_slot[DOCK_SLOT_MAX]; Rect2 dock_select_rect[DOCK_SLOT_MAX]; @@ -400,8 +420,8 @@ class EditorNode : public Node { void _node_renamed(); void _editor_select(int p_which); - void _set_scene_metadata(); - void _get_scene_metadata(); + void _set_scene_metadata(const String &p_file); + void _get_scene_metadata(const String& p_file); void _update_title(); void _update_scene_tabs(); void _close_messages(); @@ -508,14 +528,31 @@ class EditorNode : public Node { Dictionary _get_main_scene_state(); void _set_main_scene_state(Dictionary p_state); + int _get_current_main_editor(); + void _save_docks(); void _load_docks(); + void _save_docks_to_config(Ref<ConfigFile> p_layout, const String& p_section); + void _load_docks_from_config(Ref<ConfigFile> p_layout, const String& p_section); + + void _update_layouts_menu(); + void _layout_menu_option(int p_idx); + + void _toggle_search_bar(bool p_pressed); + void _clear_search_box(); + void _clear_undo_history(); protected: void _notification(int p_what); - static void _bind_methods(); + static void _bind_methods(); public: + enum EditorTable { + EDITOR_2D = 0, + EDITOR_3D, + EDITOR_SCRIPT + }; + static EditorNode* get_singleton() { return singleton; } @@ -610,7 +647,7 @@ public: static void add_io_error(const String& p_error); static void progress_add_task(const String& p_task,const String& p_label, int p_steps); - static void progress_task_step(const String& p_task,const String& p_state, int p_step=-1); + static void progress_task_step(const String& p_task,const String& p_state, int p_step=-1,bool p_force_refresh=true); static void progress_end_task(const String& p_task); static void progress_add_task_bg(const String& p_task,const String& p_label, int p_steps); @@ -637,7 +674,7 @@ public: struct EditorProgress { String task; - void step(const String& p_state, int p_step=-1) { EditorNode::progress_task_step(task,p_state,p_step); } + void step(const String& p_state, int p_step=-1,bool p_force_refresh=true) { EditorNode::progress_task_step(task,p_state,p_step,p_force_refresh); } EditorProgress(const String& p_task,const String& p_label,int p_amount) { EditorNode::progress_add_task(p_task,p_label,p_amount); task=p_task; } ~EditorProgress() { EditorNode::progress_end_task(task); } }; diff --git a/tools/editor/editor_path.cpp b/tools/editor/editor_path.cpp index 94e2efe346..4cf98e832c 100644 --- a/tools/editor/editor_path.cpp +++ b/tools/editor/editor_path.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/editor_path.h b/tools/editor/editor_path.h index 2edaeb92a3..11e1005ba3 100644 --- a/tools/editor/editor_path.h +++ b/tools/editor/editor_path.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/editor_plugin.cpp b/tools/editor/editor_plugin.cpp index 7417d707bb..b7ccb452e9 100644 --- a/tools/editor/editor_plugin.cpp +++ b/tools/editor/editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/editor_plugin.h b/tools/editor/editor_plugin.h index 0f3a1e2e3c..bf1e185a37 100644 --- a/tools/editor/editor_plugin.h +++ b/tools/editor/editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -92,6 +92,7 @@ public: virtual bool get_remove_list(List<Node*> *p_list); virtual void set_window_layout(Ref<ConfigFile> p_layout); virtual void get_window_layout(Ref<ConfigFile> p_layout); + virtual void edited_scene_changed(){}; // if changes are pending in editor, apply them virtual void restore_global_state(); virtual void save_global_state(); diff --git a/tools/editor/editor_reimport_dialog.cpp b/tools/editor/editor_reimport_dialog.cpp index 8842a485b3..eab5a5e32d 100644 --- a/tools/editor/editor_reimport_dialog.cpp +++ b/tools/editor/editor_reimport_dialog.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/editor_reimport_dialog.h b/tools/editor/editor_reimport_dialog.h index 9726bac805..0c2d0eb52c 100644 --- a/tools/editor/editor_reimport_dialog.h +++ b/tools/editor/editor_reimport_dialog.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/editor_run.cpp b/tools/editor/editor_run.cpp index b635cea84b..fb0f24c084 100644 --- a/tools/editor/editor_run.cpp +++ b/tools/editor/editor_run.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/editor_run.h b/tools/editor/editor_run.h index e1b0b081c7..0b96a2c91c 100644 --- a/tools/editor/editor_run.h +++ b/tools/editor/editor_run.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/editor_run_native.cpp b/tools/editor/editor_run_native.cpp index 2eedba93dc..234dd03087 100644 --- a/tools/editor/editor_run_native.cpp +++ b/tools/editor/editor_run_native.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/editor_run_native.h b/tools/editor/editor_run_native.h index 77d6dc198e..04dad6b6aa 100644 --- a/tools/editor/editor_run_native.h +++ b/tools/editor/editor_run_native.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/editor_selection.cpp b/tools/editor/editor_selection.cpp index d8fd8735fc..f3fbdba907 100644 --- a/tools/editor/editor_selection.cpp +++ b/tools/editor/editor_selection.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/editor_selection.h b/tools/editor/editor_selection.h index f10f313a4e..d238d86567 100644 --- a/tools/editor/editor_selection.h +++ b/tools/editor/editor_selection.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/editor_settings.cpp b/tools/editor/editor_settings.cpp index 651b30c724..4195ba97e6 100644 --- a/tools/editor/editor_settings.cpp +++ b/tools/editor/editor_settings.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -447,7 +447,7 @@ void EditorSettings::_load_defaults() { hints["global/default_project_path"]=PropertyInfo(Variant::STRING,"global/default_project_path",PROPERTY_HINT_GLOBAL_DIR); set("global/default_project_export_path",""); hints["global/default_project_export_path"]=PropertyInfo(Variant::STRING,"global/default_project_export_path",PROPERTY_HINT_GLOBAL_DIR); - + set("global/show_script_in_scene_tabs",false); set("text_editor/background_color",Color::html("3b000000")); set("text_editor/text_color",Color::html("aaaaaa")); set("text_editor/text_selected_color",Color::html("000000")); @@ -515,6 +515,8 @@ void EditorSettings::_load_defaults() { set("text_editor/create_signal_callbacks",true); set("file_dialog/show_hidden_files", false); + set("file_dialog/display_mode", 0); + hints["file_dialog/display_mode"]=PropertyInfo(Variant::INT,"file_dialog/display_mode",PROPERTY_HINT_ENUM,"Thumbnails,List"); set("file_dialog/thumbnail_size", 64); hints["file_dialog/thumbnail_size"]=PropertyInfo(Variant::INT,"file_dialog/thumbnail_size",PROPERTY_HINT_RANGE,"32,128,16"); diff --git a/tools/editor/editor_settings.h b/tools/editor/editor_settings.h index 4ba940cd1c..d1a11360af 100644 --- a/tools/editor/editor_settings.h +++ b/tools/editor/editor_settings.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -107,6 +107,7 @@ public: static EditorSettings *get_singleton(); void erase(String p_var); String get_settings_path() const; + String get_global_settings_path() const; String get_project_settings_path() const; const Map<String,Plugin>& get_plugins() const { return plugins; } diff --git a/tools/editor/editor_sub_scene.cpp b/tools/editor/editor_sub_scene.cpp index 2a6eba2554..e58e2c1351 100644 --- a/tools/editor/editor_sub_scene.cpp +++ b/tools/editor/editor_sub_scene.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -196,7 +196,11 @@ void EditorSubScene::_bind_methods() { EditorSubScene::EditorSubScene() { + scene=NULL; + set_title("Select Sub-Scene.."); + set_hide_on_ok(false); + VBoxContainer *vb = memnew( VBoxContainer ); add_child(vb); set_child_rect(vb); @@ -211,9 +215,11 @@ EditorSubScene::EditorSubScene() { hb->add_child(b); b->connect("pressed",this,"_path_browse"); vb->add_margin_child("Scene Path:",hb); + tree = memnew( Tree ); tree->set_v_size_flags(SIZE_EXPAND_FILL); - vb->add_margin_child("Import From Node:",tree)->set_v_size_flags(SIZE_EXPAND_FILL); + vb->add_margin_child("Import From Node:",tree,true); + tree->connect("item_activated",this,"_ok"); file_dialog = memnew( EditorFileDialog ); List<String> extensions; @@ -228,8 +234,4 @@ EditorSubScene::EditorSubScene() { add_child(file_dialog); file_dialog->connect("file_selected",this,"_path_selected"); - scene=NULL; - - set_hide_on_ok(false); - } diff --git a/tools/editor/editor_sub_scene.h b/tools/editor/editor_sub_scene.h index dfd6c531e2..3dd86eefda 100644 --- a/tools/editor/editor_sub_scene.h +++ b/tools/editor/editor_sub_scene.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/editor_vu.cpp b/tools/editor/editor_vu.cpp index ac11aceb21..7a133c9736 100644 --- a/tools/editor/editor_vu.cpp +++ b/tools/editor/editor_vu.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/editor_vu.h b/tools/editor/editor_vu.h index 4c51ac31c0..78fe3eda86 100644 --- a/tools/editor/editor_vu.h +++ b/tools/editor/editor_vu.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/file_type_cache.cpp b/tools/editor/file_type_cache.cpp index a86400a560..7044a9900c 100644 --- a/tools/editor/file_type_cache.cpp +++ b/tools/editor/file_type_cache.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/file_type_cache.h b/tools/editor/file_type_cache.h index efc6d22b25..18451cbe19 100644 --- a/tools/editor/file_type_cache.h +++ b/tools/editor/file_type_cache.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/fileserver/SCsub b/tools/editor/fileserver/SCsub index b525fb3f75..363a2ce4c0 100644 --- a/tools/editor/fileserver/SCsub +++ b/tools/editor/fileserver/SCsub @@ -1,7 +1,3 @@ Import('env') Export('env') env.add_source_files(env.tool_sources,"*.cpp") - - - - diff --git a/tools/editor/groups_editor.cpp b/tools/editor/groups_editor.cpp index 2e82854014..6840a8b205 100644 --- a/tools/editor/groups_editor.cpp +++ b/tools/editor/groups_editor.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -27,151 +27,130 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "groups_editor.h" -#include "scene/gui/box_container.h" +#include "scene/gui/box_container.h" #include "scene/gui/label.h" +void GroupsEditor::_add_group(const String& p_group) { -#include "print_string.h" + if (!node) + return; -void GroupsEditor::_notification(int p_what) { - - if (p_what==NOTIFICATION_ENTER_TREE) { - connect("confirmed", this,"_close"); - } - if (p_what==NOTIFICATION_EXIT_TREE) { - disconnect("confirmed", this,"_close"); - } -} + String name = group_name->get_text(); + if (name.strip_edges()=="") + return; -void GroupsEditor::_close() { - - hide(); - -} -void GroupsEditor::_add() { - - if (!node) + if (node->is_in_group(name)) return; - - undo_redo->create_action("Add To Group"); - undo_redo->add_do_method(node,"add_to_group",group_name->get_text(),true); - undo_redo->add_undo_method(node,"remove_from_group",group_name->get_text()); + undo_redo->create_action("Add to Group"); + + undo_redo->add_do_method(node,"add_to_group",name,true); undo_redo->add_do_method(this,"update_tree"); + undo_redo->add_undo_method(node,"remove_from_group",name,get_text()); undo_redo->add_undo_method(this,"update_tree"); undo_redo->commit_action(); } +void GroupsEditor::_remove_group(Object *p_item, int p_column, int p_id) { -void GroupsEditor::_remove() { - - if (!tree->get_selected()) - return; if (!node) return; - TreeItem *sel = tree->get_selected(); - if (!sel) + TreeItem *ti = p_item->cast_to<TreeItem>(); + if (!ti) return; - - node->remove_from_group( sel->get_text(0) ); - update_tree(); + + String name = ti->get_text(0); + + undo_redo->create_action("Remove from Group"); + + undo_redo->add_do_method(node,"remove_from_group",name); + undo_redo->add_do_method(this,"update_tree"); + undo_redo->add_undo_method(node,"add_to_group",name,true); + undo_redo->add_undo_method(this,"update_tree"); + + undo_redo->commit_action(); } +struct _GroupInfoComparator { + + bool operator()(const Node::GroupInfo& p_a, const Node::GroupInfo& p_b) const { + return p_a.name.operator String() < p_b.name.operator String(); + } +}; + void GroupsEditor::update_tree() { - tree->clear(); - + if (!node) return; - - List<GroupInfo> groups; + + List<Node::GroupInfo> groups; node->get_groups(&groups); - + groups.sort_custom<_GroupInfoComparator>(); + TreeItem *root=tree->create_item(); - + for(List<GroupInfo>::Element *E=groups.front();E;E=E->next()) { - - if (!E->get().persistent) + + Node::GroupInfo gi = E->get(); + if (!gi.persistent) continue; + TreeItem *item=tree->create_item(root); - item->set_text(0, E->get().name); - + item->set_text(0, gi.name); + item->add_button(0, get_icon("Remove", "EditorIcons"), 0); } - } void GroupsEditor::set_current(Node* p_node) { - + node=p_node; update_tree(); - } void GroupsEditor::_bind_methods() { - - ObjectTypeDB::bind_method("_add",&GroupsEditor::_add); - ObjectTypeDB::bind_method("_close",&GroupsEditor::_close); - ObjectTypeDB::bind_method("_remove",&GroupsEditor::_remove); + + ObjectTypeDB::bind_method("_add_group",&GroupsEditor::_add_group); + ObjectTypeDB::bind_method("_remove_group",&GroupsEditor::_remove_group); ObjectTypeDB::bind_method("update_tree",&GroupsEditor::update_tree); } GroupsEditor::GroupsEditor() { + node=NULL; + set_title("Group Editor"); - - Label * label = memnew( Label ); - label->set_pos( Point2( 8,11) ); - label->set_text("Groups:"); - - add_child(label); - - group_name = memnew(LineEdit); - group_name->set_anchor( MARGIN_RIGHT, ANCHOR_END ); - group_name->set_begin( Point2( 15,28) ); - group_name->set_end( Point2( 94,48 ) ); - - add_child(group_name); - - tree = memnew( Tree ); - tree->set_anchor( MARGIN_RIGHT, ANCHOR_END ); - tree->set_anchor( MARGIN_BOTTOM, ANCHOR_END ); - tree->set_begin( Point2( 15,52) ); - tree->set_end( Point2( 94,42 ) ); - tree->set_hide_root(true); - add_child(tree); - + + VBoxContainer *vbc = memnew( VBoxContainer ); + add_child(vbc); + set_child_rect(vbc); + + HBoxContainer *hbc = memnew( HBoxContainer ); + vbc->add_margin_child("Group", hbc); + + group_name = memnew( LineEdit ); + group_name->set_h_size_flags(SIZE_EXPAND_FILL); + hbc->add_child(group_name); + group_name->connect("text_entered",this,"_add_group"); + add = memnew( Button ); - add->set_anchor( MARGIN_LEFT, ANCHOR_END ); - add->set_anchor( MARGIN_RIGHT, ANCHOR_END ); - add->set_begin( Point2( 90, 28 ) ); - add->set_end( Point2( 15, 48 ) ); add->set_text("Add"); - - add_child(add); - - remove = memnew( Button ); - remove->set_anchor( MARGIN_LEFT, ANCHOR_END ); - remove->set_anchor( MARGIN_RIGHT, ANCHOR_END ); - remove->set_begin( Point2( 90, 52 ) ); - remove->set_end( Point2( 15, 72 ) ); - remove->set_text("Remove"); - - add_child(remove); + hbc->add_child(add); + add->connect("pressed", this,"_add_group", varray(String())); - get_ok()->set_text("Close"); - - add->connect("pressed", this,"_add"); - remove->connect("pressed", this,"_remove"); + tree = memnew( Tree ); + tree->set_hide_root(true); + tree->set_v_size_flags(SIZE_EXPAND_FILL); + vbc->add_margin_child("Node Group(s)", tree, true); + tree->connect("button_pressed",this,"_remove_group"); - - node=NULL; + get_ok()->set_text("Close"); } - GroupsEditor::~GroupsEditor() { } diff --git a/tools/editor/groups_editor.h b/tools/editor/groups_editor.h index 09883a150f..b5bccb2766 100644 --- a/tools/editor/groups_editor.h +++ b/tools/editor/groups_editor.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -29,42 +29,42 @@ #ifndef GROUPS_EDITOR_H #define GROUPS_EDITOR_H - #include "scene/gui/dialogs.h" #include "scene/gui/button.h" #include "scene/gui/tree.h" #include "scene/gui/line_edit.h" #include "undo_redo.h" + /** @author Juan Linietsky <reduzio@gmail.com> */ -class GroupsEditor : public ConfirmationDialog { - - OBJ_TYPE( GroupsEditor, ConfirmationDialog ); - + +class GroupsEditor : public AcceptDialog { + + OBJ_TYPE(GroupsEditor,AcceptDialog); + + Node *node; + LineEdit *group_name; - Tree *tree; Button *add; - Button *remove; - Node *node; + Tree *tree; + UndoRedo *undo_redo; - + void update_tree(); - void _add(); - void _remove(); + void _add_group(const String& p_group=""); + void _remove_group(Object *p_item, int p_column, int p_id); void _close(); - protected: - - void _notification(int p_what); - static void _bind_methods(); + + static void _bind_methods(); public: - + void set_undo_redo(UndoRedo *p_undoredo) { undo_redo=p_undoredo; } void set_current(Node* p_node); - + GroupsEditor(); ~GroupsEditor(); - }; + #endif diff --git a/tools/editor/icons/SCsub b/tools/editor/icons/SCsub index aea053d22b..addf6879a2 100644 --- a/tools/editor/icons/SCsub +++ b/tools/editor/icons/SCsub @@ -9,30 +9,30 @@ def make_editor_icons_action(target, source, env): pixmaps = source s = cStringIO.StringIO() - + s.write("#include \"editor_icons.h\"\n\n") s.write("#include \"scene/resources/theme.h\"\n\n") for x in pixmaps: - + x=str(x) var_str=os.path.basename(x)[:-4]+"_png"; #print(var_str) - + s.write("static const unsigned char "+ var_str +"[]={\n"); - + pngf=open(x,"rb"); - + b=pngf.read(1); while(len(b)==1): s.write(hex(ord(b))) b=pngf.read(1); if (len(b)==1): s.write(",") - + s.write("\n};\n\n\n"); pngf.close(); - + s.write("static Ref<ImageTexture> make_icon(const uint8_t* p_png) {\n") s.write("\tRef<ImageTexture> texture( memnew( ImageTexture ) );\n") s.write("\ttexture->create_from_image( Image(p_png),ImageTexture::FLAG_FILTER );\n") @@ -42,14 +42,14 @@ def make_editor_icons_action(target, source, env): s.write("void editor_register_icons(Ref<Theme> p_theme) {\n\n") for x in pixmaps: - + x=os.path.basename(str(x)) type=x[5:-4].title().replace("_",""); var_str=x[:-4]+"_png"; s.write("\tp_theme->set_icon(\""+type+"\",\"EditorIcons\",make_icon("+var_str+"));\n"); s.write("\n\n}\n\n"); - + f = open(dst,"wb") f.write(s.getvalue()) f.close() @@ -63,4 +63,3 @@ env.Alias('editor_icons',[env.MakeEditorIconsBuilder('#tools/editor/editor_icons env.tool_sources.append("#tools/editor/editor_icons.cpp") Export('env') - diff --git a/tools/editor/icons/icon_back.png b/tools/editor/icons/icon_back.png Binary files differindex d60e3b2640..f7e507d92b 100644 --- a/tools/editor/icons/icon_back.png +++ b/tools/editor/icons/icon_back.png diff --git a/tools/editor/icons/icon_class_list.png b/tools/editor/icons/icon_class_list.png Binary files differnew file mode 100644 index 0000000000..fb756c0fe1 --- /dev/null +++ b/tools/editor/icons/icon_class_list.png diff --git a/tools/editor/icons/icon_console.png b/tools/editor/icons/icon_console.png Binary files differnew file mode 100644 index 0000000000..7dc7407ef7 --- /dev/null +++ b/tools/editor/icons/icon_console.png diff --git a/tools/editor/icons/icon_edit_pivot.png b/tools/editor/icons/icon_edit_pivot.png Binary files differnew file mode 100644 index 0000000000..d68f7bbf25 --- /dev/null +++ b/tools/editor/icons/icon_edit_pivot.png diff --git a/tools/editor/icons/icon_forward.png b/tools/editor/icons/icon_forward.png Binary files differindex ca6838ae9e..14e8bc9a5a 100644 --- a/tools/editor/icons/icon_forward.png +++ b/tools/editor/icons/icon_forward.png diff --git a/tools/editor/icons/icon_godot.png b/tools/editor/icons/icon_godot.png Binary files differnew file mode 100644 index 0000000000..e80820fc10 --- /dev/null +++ b/tools/editor/icons/icon_godot.png diff --git a/tools/editor/icons/icon_help.png b/tools/editor/icons/icon_help.png Binary files differindex 3f4f8453a7..d2085589ae 100644 --- a/tools/editor/icons/icon_help.png +++ b/tools/editor/icons/icon_help.png diff --git a/tools/editor/icons/icon_key_invalid.png b/tools/editor/icons/icon_key_invalid.png Binary files differnew file mode 100644 index 0000000000..e8e6c87180 --- /dev/null +++ b/tools/editor/icons/icon_key_invalid.png diff --git a/tools/editor/icons/icon_key_invalid_hover.png b/tools/editor/icons/icon_key_invalid_hover.png Binary files differnew file mode 100644 index 0000000000..6f0396d96a --- /dev/null +++ b/tools/editor/icons/icon_key_invalid_hover.png diff --git a/tools/editor/icons/icon_list_select.png b/tools/editor/icons/icon_list_select.png Binary files differnew file mode 100644 index 0000000000..cbe81d4328 --- /dev/null +++ b/tools/editor/icons/icon_list_select.png diff --git a/tools/editor/icons/icon_multi_edit.png b/tools/editor/icons/icon_multi_edit.png Binary files differnew file mode 100644 index 0000000000..70faee3d6a --- /dev/null +++ b/tools/editor/icons/icon_multi_edit.png diff --git a/tools/editor/import_settings.cpp b/tools/editor/import_settings.cpp index 36d7828be0..2bbd1e3805 100644 --- a/tools/editor/import_settings.cpp +++ b/tools/editor/import_settings.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/import_settings.h b/tools/editor/import_settings.h index 31237dd8cf..5a383a1a1a 100644 --- a/tools/editor/import_settings.h +++ b/tools/editor/import_settings.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/io_plugins/SCsub b/tools/editor/io_plugins/SCsub index b525fb3f75..363a2ce4c0 100644 --- a/tools/editor/io_plugins/SCsub +++ b/tools/editor/io_plugins/SCsub @@ -1,7 +1,3 @@ Import('env') Export('env') env.add_source_files(env.tool_sources,"*.cpp") - - - - diff --git a/tools/editor/io_plugins/editor_atlas.cpp b/tools/editor/io_plugins/editor_atlas.cpp index 4a260a9a6f..f894e7e8b2 100644 --- a/tools/editor/io_plugins/editor_atlas.cpp +++ b/tools/editor/io_plugins/editor_atlas.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -27,7 +27,7 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "editor_atlas.h" - +#include "print_string.h" struct _EditorAtlasWorkRect { @@ -83,6 +83,7 @@ void EditorAtlas::fit(const Vector<Size2i>& p_rects,Vector<Point2i>& r_result, S //place them int ofs=0; int limit_h=0; + for(int j=0;j<wrects.size();j++) { @@ -100,6 +101,9 @@ void EditorAtlas::fit(const Vector<Size2i>& p_rects,Vector<Point2i>& r_result, S wrects[j].p.x=ofs; wrects[j].p.y=from_y; + + + int end_h = from_y+wrects[j].s.height; int end_w = ofs+wrects[j].s.width; if (ofs==0) @@ -116,7 +120,7 @@ void EditorAtlas::fit(const Vector<Size2i>& p_rects,Vector<Point2i>& r_result, S if (end_w > max_w) max_w=end_w; - if (ofs==0 || end_h>limit_h ) //while h limit not reched, keep stacking + //if (ofs==0 || end_h>limit_h ) //while h limit not reched, keep stacking ofs+=wrects[j].s.width; } @@ -136,8 +140,8 @@ void EditorAtlas::fit(const Vector<Size2i>& p_rects,Vector<Point2i>& r_result, S for(int i=0;i<results.size();i++) { - float h = nearest_power_of_2(results[i].max_h); - float w = nearest_power_of_2(results[i].max_w); + float h = results[i].max_h; + float w = results[i].max_w; float aspect = h>w ? h/w : w/h; if (aspect < best_aspect) { best=i; diff --git a/tools/editor/io_plugins/editor_atlas.h b/tools/editor/io_plugins/editor_atlas.h index 716faff0c6..0135e76622 100644 --- a/tools/editor/io_plugins/editor_atlas.h +++ b/tools/editor/io_plugins/editor_atlas.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/io_plugins/editor_export_scene.cpp b/tools/editor/io_plugins/editor_export_scene.cpp new file mode 100644 index 0000000000..dff41a59ed --- /dev/null +++ b/tools/editor/io_plugins/editor_export_scene.cpp @@ -0,0 +1,112 @@ +#include "editor_export_scene.h" +#include "io/resource_loader.h" +#include "io/resource_saver.h" +#include "os/dir_access.h" +#include "os/file_access.h" +#include "tools/editor/editor_settings.h" +#include "scene/resources/packed_scene.h" +#include "globals.h" + +Vector<uint8_t> EditorSceneExportPlugin::custom_export(String& p_path,const Ref<EditorExportPlatform> &p_platform) { + + if (!EditorImportExport::get_singleton()->get_convert_text_scenes()) { + return Vector<uint8_t>(); + } + + + String extension = p_path.extension(); + + //step 1 check if scene + + if (extension=="xml" || extension=="xres") { + + String type = ResourceLoader::get_resource_type(p_path); + + if (type!="PackedScene") + return Vector<uint8_t>(); + + } else if (extension!="tscn" && extension!="xscn") { + return Vector<uint8_t>(); + } + + //step 2 check if cached + + uint64_t sd=0; + String smd5; + String gp = Globals::get_singleton()->globalize_path(p_path); + String md5=gp.md5_text(); + String tmp_path = EditorSettings::get_singleton()->get_settings_path().plus_file("tmp/"); + + bool valid=false; + { + //if existing, make sure it's valid + FileAccessRef f = FileAccess::open(tmp_path+"scnexp-"+md5+".txt",FileAccess::READ); + if (f) { + + uint64_t d = f->get_line().strip_edges().to_int64(); + sd = FileAccess::get_modified_time(p_path); + + if (d==sd) { + valid=true; + } else { + String cmd5 = f->get_line().strip_edges(); + smd5 = FileAccess::get_md5(p_path); + if (cmd5==smd5) { + valid=true; + } + } + + + } + } + + if (!valid) { + //cache failed, convert + DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + + String copy = p_path+".convert."+extension; + + // a copy will allow loading the internal resources without conflicting with opened scenes + da->copy(p_path,copy); + + //@todo for tscn use something more efficient + + Ref<PackedScene> copyres = ResourceLoader::load(copy,"PackedScene"); + + da->remove(copy); + + memdelete(da); + + ERR_FAIL_COND_V(!copyres.is_valid(),Vector<uint8_t>()); + + Error err = ResourceSaver::save(tmp_path+"scnexp-"+md5+".scn",copyres); + + copyres=Ref<PackedScene>(); + + ERR_FAIL_COND_V(err!=OK,Vector<uint8_t>()); + + FileAccessRef f = FileAccess::open(tmp_path+"scnexp-"+md5+".txt",FileAccess::WRITE); + + if (sd==0) + sd = FileAccess::get_modified_time(p_path); + if (smd5==String()) + smd5 = FileAccess::get_md5(p_path); + + f->store_line(String::num(sd)); + f->store_line(smd5); + f->store_line(gp); //source path for reference + } + + + Vector<uint8_t> ret = FileAccess::get_file_as_array(tmp_path+"scnexp-"+md5+".scn"); + + p_path+=".converted.scn"; + + return ret; + +} + + +EditorSceneExportPlugin::EditorSceneExportPlugin() +{ +} diff --git a/tools/editor/io_plugins/editor_export_scene.h b/tools/editor/io_plugins/editor_export_scene.h new file mode 100644 index 0000000000..134da6c234 --- /dev/null +++ b/tools/editor/io_plugins/editor_export_scene.h @@ -0,0 +1,16 @@ +#ifndef EDITOR_EXPORT_SCENE_H +#define EDITOR_EXPORT_SCENE_H + +#include "tools/editor/editor_import_export.h" + + +class EditorSceneExportPlugin : public EditorExportPlugin { + OBJ_TYPE( EditorSceneExportPlugin, EditorExportPlugin ); +public: + + virtual Vector<uint8_t> custom_export(String& p_path,const Ref<EditorExportPlatform> &p_platform); + + EditorSceneExportPlugin(); +}; + +#endif // EDITOR_EXPORT_SCENE_H diff --git a/tools/editor/io_plugins/editor_font_import_plugin.cpp b/tools/editor/io_plugins/editor_font_import_plugin.cpp index 10a3877529..9b4ca246e7 100644 --- a/tools/editor/io_plugins/editor_font_import_plugin.cpp +++ b/tools/editor/io_plugins/editor_font_import_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -520,6 +520,10 @@ class EditorFontImportDialog : public ConfirmationDialog { return; } + if (dest->get_line_edit()->get_text().get_file()==".fnt") { + dest->get_line_edit()->set_text(dest->get_line_edit()->get_text().get_base_dir() + "/" + source->get_line_edit()->get_text().get_file().basename() + ".fnt" ); + } + Ref<ResourceImportMetadata> rimd = get_rimd(); if (rimd.is_null()) { @@ -617,6 +621,7 @@ public: source->get_file_dialog()->set_mode(EditorFileDialog::MODE_OPEN_FILE); source->get_file_dialog()->add_filter("*.ttf;TrueType"); source->get_file_dialog()->add_filter("*.otf;OpenType"); + source->get_file_dialog()->add_filter("*.fnt;BMFont"); source->get_line_edit()->connect("text_entered",this,"_src_changed"); vbl->add_margin_child("Source Font:",source); @@ -872,10 +877,31 @@ static unsigned char get_SDF_radial( Ref<Font> EditorFontImportPlugin::generate_font(const Ref<ResourceImportMetadata>& p_from, const String &p_existing) { + + Ref<ResourceImportMetadata> from = p_from; ERR_FAIL_COND_V(from->get_source_count()!=1,Ref<Font>()); String src_path = EditorImportPlugin::expand_source_path(from->get_source_path(0)); + + if (src_path.extension().to_lower()=="fnt") { + + if (ResourceLoader::load(src_path).is_valid()) { + EditorNode::get_singleton()->show_warning("Path: "+src_path+"\nIs a Godot font file, please supply a BMFont type file instead."); + return Ref<Font>(); + } + + Ref<Font> font; + font.instance(); + Error err = font->create_from_fnt(src_path); + if (err) { + EditorNode::get_singleton()->show_warning("Path: "+src_path+"\nFailed opening as BMFont file."); + return Ref<Font>(); + } + + return font; + } + int size = from->get_option("font/size"); #ifdef FREETYPE_ENABLED diff --git a/tools/editor/io_plugins/editor_font_import_plugin.h b/tools/editor/io_plugins/editor_font_import_plugin.h index 451f01080e..814897c5f0 100644 --- a/tools/editor/io_plugins/editor_font_import_plugin.h +++ b/tools/editor/io_plugins/editor_font_import_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/io_plugins/editor_import_collada.cpp b/tools/editor/io_plugins/editor_import_collada.cpp index d57cff850e..7de9d978f2 100644 --- a/tools/editor/io_plugins/editor_import_collada.cpp +++ b/tools/editor/io_plugins/editor_import_collada.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -68,6 +68,7 @@ struct ColladaImport { Map<String,NodeMap> node_map; //map from collada node to engine node + Map<String,String> node_name_map; //map from collada node to engine node Map<String, Ref<Mesh> > mesh_cache; Map<String, Ref<Curve3D> > curve_cache; Map<String, Ref<Material> > material_cache; @@ -124,6 +125,7 @@ Error ColladaImport::_populate_skeleton(Skeleton *p_skeleton,Collada::Node *p_no nm.node=p_skeleton; nm.bone = r_bone; node_map[p_node->id]=nm; + node_name_map[p_node->name]=p_node->id; skeleton_bone_map[p_skeleton][joint->sid]=r_bone; @@ -345,6 +347,7 @@ Error ColladaImport::_create_scene(Collada::Node *p_node, Spatial *p_parent) { NodeMap nm; nm.node=node; node_map[p_node->id]=nm; + node_name_map[p_node->name]=p_node->id; Transform xf = p_node->default_transform; xf = collada.fix_transform( xf ) * p_node->post_transform; @@ -1906,9 +1909,20 @@ void ColladaImport::create_animations(bool p_make_tracks_in_all_bones) { Collada::AnimationTrack &at = collada.state.animation_tracks[i]; //print_line("CHANNEL: "+at.target+" PARAM: "+at.param); + + String node; + if (!node_map.has(at.target)) { - print_line("Coudlnt find node: "+at.target); - continue; + + if (node_name_map.has(at.target)) { + + node=node_name_map[at.target]; + } else { + print_line("Coudlnt find node: "+at.target); + continue; + } + } else { + node=at.target; } @@ -1917,8 +1931,9 @@ void ColladaImport::create_animations(bool p_make_tracks_in_all_bones) { valid_animated_properties.push_back(i); } else { - node_map[at.target].anim_tracks.push_back(i); - valid_animated_nodes.insert(at.target); + + node_map[node].anim_tracks.push_back(i); + valid_animated_nodes.insert(node); } } @@ -1934,6 +1949,7 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones Ref<Animation> animation = Ref<Animation>( memnew( Animation )); + if (p_clip==-1) { //print_line("default"); @@ -2007,10 +2023,12 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones while(f<anim_length) { base_snapshots.push_back(f); + f+=snapshot_interval; if (f>=anim_length) { base_snapshots.push_back(anim_length); + } } @@ -2019,11 +2037,17 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones bool tracks_found=false; + + for(Set<String>::Element* E=valid_animated_nodes.front();E;E=E->next()) { // take snapshots - if (!collada.state.scene_map.has(E->get())) + + + if (!collada.state.scene_map.has(E->get())) { + continue; + } NodeMap &nm = node_map[E->get()]; String path = scene->get_path_to(nm.node); @@ -2039,7 +2063,7 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones Collada::Node *cn = collada.state.scene_map[E->get()]; if (cn->ignore_anim) { - //print_line("warning, ignoring animation on node: "+path); + continue; } @@ -2058,20 +2082,23 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones for(int i=0;i<at.keys.size();i++) snapshots.push_back(at.keys[i].time); - print_line("using anim snapshots"); } for(int i=0;i<snapshots.size();i++) { + for(List<int>::Element *ET=nm.anim_tracks.front();ET;ET=ET->next()) { //apply tracks + if (p_clip==-1) { - if (track_filter.has(ET->get())) + if (track_filter.has(ET->get())) { + continue; + } } else { if (!track_filter.has(ET->get())) diff --git a/tools/editor/io_plugins/editor_import_collada.h b/tools/editor/io_plugins/editor_import_collada.h index 243cd043a0..de45dc38f4 100644 --- a/tools/editor/io_plugins/editor_import_collada.h +++ b/tools/editor/io_plugins/editor_import_collada.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/io_plugins/editor_mesh_import_plugin.cpp b/tools/editor/io_plugins/editor_mesh_import_plugin.cpp index 2139513025..b32ab8cb0b 100644 --- a/tools/editor/io_plugins/editor_mesh_import_plugin.cpp +++ b/tools/editor/io_plugins/editor_mesh_import_plugin.cpp @@ -128,7 +128,7 @@ class EditorMeshImportDialog : public ConfirmationDialog { LineEdit *save_path; EditorFileDialog *file_select; EditorDirDialog *save_select; - ConfirmationDialog *error_dialog; + AcceptDialog *error_dialog; PropertyEditor *option_editor; _EditorMeshImportOptions *options; @@ -169,13 +169,12 @@ public: void _browse_target() { save_select->popup_centered_ratio(); - } - void popup_import(const String& p_path) { popup_centered(Size2(400,400)); + if (p_path!="") { Ref<ResourceImportMetadata> rimd = ResourceLoader::load_import_metadata(p_path); @@ -199,14 +198,13 @@ public: } } - void _import() { Vector<String> meshes = import_path->get_text().split(","); - if (meshes.size()==0) { error_dialog->set_text("No meshes to import!"); - error_dialog->popup_centered(Size2(200,100)); + error_dialog->popup_centered_minsize(); + return; } for(int i=0;i<meshes.size();i++) { @@ -229,19 +227,18 @@ public: String dst = save_path->get_text(); if (dst=="") { error_dialog->set_text("Save path is empty!"); - error_dialog->popup_centered(Size2(200,100)); + error_dialog->popup_centered_minsize(); + return; } dst = dst.plus_file(meshes[i].get_file().basename()+".msh"); - Error err = plugin->import(dst,imd); + plugin->import(dst,imd); } hide(); - } - void _notification(int p_what) { @@ -253,27 +250,24 @@ public: static void _bind_methods() { - ObjectTypeDB::bind_method("_choose_files",&EditorMeshImportDialog::_choose_files); ObjectTypeDB::bind_method("_choose_save_dir",&EditorMeshImportDialog::_choose_save_dir); ObjectTypeDB::bind_method("_import",&EditorMeshImportDialog::_import); ObjectTypeDB::bind_method("_browse",&EditorMeshImportDialog::_browse); ObjectTypeDB::bind_method("_browse_target",&EditorMeshImportDialog::_browse_target); - // ADD_SIGNAL( MethodInfo("imported",PropertyInfo(Variant::OBJECT,"scene")) ); } EditorMeshImportDialog(EditorMeshImportPlugin *p_plugin) { plugin=p_plugin; - set_title("Single Mesh Import"); + set_hide_on_ok(false); VBoxContainer *vbc = memnew( VBoxContainer ); add_child(vbc); set_child_rect(vbc); - HBoxContainer *hbc = memnew( HBoxContainer ); vbc->add_margin_child("Source Mesh(es):",hbc); @@ -300,28 +294,23 @@ public: save_choose->connect("pressed", this,"_browse_target"); - file_select = memnew(EditorFileDialog); + file_select = memnew( EditorFileDialog ); file_select->set_access(EditorFileDialog::ACCESS_FILESYSTEM); - add_child(file_select); file_select->set_mode(EditorFileDialog::MODE_OPEN_FILES); - file_select->connect("files_selected", this,"_choose_files"); file_select->add_filter("*.obj ; Wavefront OBJ"); - save_select = memnew( EditorDirDialog ); - add_child(save_select); + add_child(file_select); + file_select->connect("files_selected", this,"_choose_files"); - // save_select->set_mode(EditorFileDialog::MODE_OPEN_DIR); + save_select = memnew( EditorDirDialog ); + add_child(save_select); save_select->connect("dir_selected", this,"_choose_save_dir"); get_ok()->connect("pressed", this,"_import"); get_ok()->set_text("Import"); - - error_dialog = memnew ( ConfirmationDialog ); + error_dialog = memnew( AcceptDialog ); add_child(error_dialog); - error_dialog->get_ok()->set_text("Accept"); - // error_dialog->get_cancel()->hide(); - set_hide_on_ok(false); options = memnew( _EditorMeshImportOptions ); option_editor = memnew( PropertyEditor ); diff --git a/tools/editor/io_plugins/editor_sample_import_plugin.cpp b/tools/editor/io_plugins/editor_sample_import_plugin.cpp index 9298b35b3b..b81c88c817 100644 --- a/tools/editor/io_plugins/editor_sample_import_plugin.cpp +++ b/tools/editor/io_plugins/editor_sample_import_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -35,6 +35,7 @@ #include "io/resource_saver.h" #include "os/file_access.h" #include "io/marshalls.h" +#include "tools/editor/editor_settings.h" class _EditorSampleImportOptions : public Object { @@ -156,7 +157,7 @@ public: edit_normalize=true; edit_loop=false; - compress_mode=COMPRESS_MODE_DISABLED; + compress_mode=COMPRESS_MODE_RAM; compress_bitrate=COMPRESS_128; } @@ -580,8 +581,7 @@ Error EditorSampleImportPlugin::import(const String& p_path, const Ref<ResourceI int compression = from->get_option("compress/mode"); bool force_mono = from->get_option("force/mono"); - if (compression==_EditorSampleImportOptions::COMPRESS_MODE_RAM) - force_mono=true; + if (force_mono && chans==2) { @@ -608,9 +608,47 @@ Error EditorSampleImportPlugin::import(const String& p_path, const Ref<ResourceI if ( compression == _EditorSampleImportOptions::COMPRESS_MODE_RAM) { dst_format=Sample::FORMAT_IMA_ADPCM; + if (chans==1) { + _compress_ima_adpcm(data,dst_data); + } else { + + print_line("INTERLEAAVE!"); + + + + //byte interleave + Vector<float> left; + Vector<float> right; + + int tlen = data.size()/2; + left.resize(tlen); + right.resize(tlen); + + for(int i=0;i<tlen;i++) { + left[i]=data[i*2+0]; + right[i]=data[i*2+1]; + } + + DVector<uint8_t> bleft; + DVector<uint8_t> bright; - _compress_ima_adpcm(data,dst_data); - print_line("compressing ima-adpcm, resulting buffersize is "+itos(dst_data.size())+" from "+itos(data.size())); + _compress_ima_adpcm(left,bleft); + _compress_ima_adpcm(right,bright); + + int dl = bleft.size(); + dst_data.resize( dl *2 ); + + DVector<uint8_t>::Write w=dst_data.write(); + DVector<uint8_t>::Read rl=bleft.read(); + DVector<uint8_t>::Read rr=bright.read(); + + for(int i=0;i<dl;i++) { + w[i*2+0]=rl[i]; + w[i*2+1]=rr[i]; + } + } + +// print_line("compressing ima-adpcm, resulting buffersize is "+itos(dst_data.size())+" from "+itos(data.size())); } else { @@ -781,9 +819,54 @@ void EditorSampleImportPlugin::_compress_ima_adpcm(const Vector<float>& p_data,D } + +EditorSampleImportPlugin* EditorSampleImportPlugin::singleton=NULL; + + + EditorSampleImportPlugin::EditorSampleImportPlugin(EditorNode* p_editor) { + singleton=this; dialog = memnew( EditorSampleImportDialog(this)); p_editor->get_gui_base()->add_child(dialog); } +Vector<uint8_t> EditorSampleExportPlugin::custom_export(String& p_path,const Ref<EditorExportPlatform> &p_platform) { + + + + if (EditorImportExport::get_singleton()->sample_get_action()==EditorImportExport::SAMPLE_ACTION_NONE || p_path.extension().to_lower()!="wav") { + + return Vector<uint8_t>(); + } + + Ref<ResourceImportMetadata> imd = memnew( ResourceImportMetadata ); + + imd->add_source(EditorImportPlugin::validate_source_path(p_path)); + + imd->set_option("force/8_bit",false); + imd->set_option("force/mono",false); + imd->set_option("force/max_rate",true); + imd->set_option("force/max_rate_hz",EditorImportExport::get_singleton()->sample_get_max_hz()); + imd->set_option("edit/trim",EditorImportExport::get_singleton()->sample_get_trim()); + imd->set_option("edit/normalize",false); + imd->set_option("edit/loop",false); + imd->set_option("compress/mode",1); + + String savepath = EditorSettings::get_singleton()->get_settings_path().plus_file("tmp/smpconv.smp"); + Error err = EditorSampleImportPlugin::singleton->import(savepath,imd); + + + ERR_FAIL_COND_V(err!=OK,Vector<uint8_t>()); + + p_path=p_path.basename()+".converted.smp"; + return FileAccess::get_file_as_array(savepath); + +} + + +EditorSampleExportPlugin::EditorSampleExportPlugin() { + +} + + diff --git a/tools/editor/io_plugins/editor_sample_import_plugin.h b/tools/editor/io_plugins/editor_sample_import_plugin.h index 03a4d38ab3..b31562af76 100644 --- a/tools/editor/io_plugins/editor_sample_import_plugin.h +++ b/tools/editor/io_plugins/editor_sample_import_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -43,6 +43,8 @@ class EditorSampleImportPlugin : public EditorImportPlugin { void _compress_ima_adpcm(const Vector<float>& p_data,DVector<uint8_t>& dst_data); public: + static EditorSampleImportPlugin *singleton; + virtual String get_name() const; virtual String get_visible_name() const; virtual void import_dialog(const String& p_from=""); @@ -52,4 +54,16 @@ public: EditorSampleImportPlugin(EditorNode* p_editor); }; +class EditorSampleExportPlugin : public EditorExportPlugin { + + OBJ_TYPE( EditorSampleExportPlugin, EditorExportPlugin); + + +public: + + virtual Vector<uint8_t> custom_export(String& p_path,const Ref<EditorExportPlatform> &p_platform); + + EditorSampleExportPlugin(); +}; + #endif // EDITOR_SAMPLE_IMPORT_PLUGIN_H diff --git a/tools/editor/io_plugins/editor_scene_import_plugin.cpp b/tools/editor/io_plugins/editor_scene_import_plugin.cpp index 99dcf4ed28..a3b6827cd4 100644 --- a/tools/editor/io_plugins/editor_scene_import_plugin.cpp +++ b/tools/editor/io_plugins/editor_scene_import_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -1814,8 +1814,8 @@ Node* EditorSceneImportPlugin::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh> for(int i=0;i<portal_points.size()-1;i++) { - float a = portal_points[i].atan2(); - float b = portal_points[i+1].atan2(); + float a = portal_points[i].angle(); + float b = portal_points[i+1].angle(); if (a>b) { SWAP( portal_points[i], portal_points[i+1] ); diff --git a/tools/editor/io_plugins/editor_scene_import_plugin.h b/tools/editor/io_plugins/editor_scene_import_plugin.h index 71efab9503..1f3b73fe7f 100644 --- a/tools/editor/io_plugins/editor_scene_import_plugin.h +++ b/tools/editor/io_plugins/editor_scene_import_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/io_plugins/editor_texture_import_plugin.cpp b/tools/editor/io_plugins/editor_texture_import_plugin.cpp index 8d5a4f1dcf..29273ebd06 100644 --- a/tools/editor/io_plugins/editor_texture_import_plugin.cpp +++ b/tools/editor/io_plugins/editor_texture_import_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -1666,7 +1666,7 @@ EditorTextureImportPlugin::EditorTextureImportPlugin(EditorNode *p_editor, Mode if (pl.is_valid()) { Vector<uint8_t> ce = pl->custom_export(p_path,p_platform); if (ce.size()) { - p_path=p_path.basename()+".tex"; + p_path=p_path.basename()+".converted.tex"; return ce; } } @@ -1680,7 +1680,7 @@ EditorTextureImportPlugin::EditorTextureImportPlugin(EditorNode *p_editor, Mode if (pl.is_valid()) { Vector<uint8_t> ce = pl->custom_export(p_path,p_platform); if (ce.size()) { - p_path=p_path.basename()+".tex"; + p_path=p_path.basename()+".converted.tex"; return ce; } } diff --git a/tools/editor/io_plugins/editor_texture_import_plugin.h b/tools/editor/io_plugins/editor_texture_import_plugin.h index 78383d1d77..cb63ba98c8 100644 --- a/tools/editor/io_plugins/editor_texture_import_plugin.h +++ b/tools/editor/io_plugins/editor_texture_import_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -123,6 +123,7 @@ public: virtual Vector<uint8_t> custom_export(String& p_path,const Ref<EditorExportPlatform> &p_platform); EditorTextureExportPlugin(); }; + class EditorImportTextureOptions : public VBoxContainer { OBJ_TYPE( EditorImportTextureOptions, VBoxContainer ); diff --git a/tools/editor/io_plugins/editor_translation_import_plugin.cpp b/tools/editor/io_plugins/editor_translation_import_plugin.cpp index d152d71af4..1edfe697b6 100644 --- a/tools/editor/io_plugins/editor_translation_import_plugin.cpp +++ b/tools/editor/io_plugins/editor_translation_import_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/io_plugins/editor_translation_import_plugin.h b/tools/editor/io_plugins/editor_translation_import_plugin.h index f3c2884534..cadcdc03b3 100644 --- a/tools/editor/io_plugins/editor_translation_import_plugin.h +++ b/tools/editor/io_plugins/editor_translation_import_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/optimized_save_dialog.cpp b/tools/editor/optimized_save_dialog.cpp index 687d3675fc..4814b3b021 100644 --- a/tools/editor/optimized_save_dialog.cpp +++ b/tools/editor/optimized_save_dialog.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/optimized_save_dialog.h b/tools/editor/optimized_save_dialog.h index 739d0e1506..bdc36eddc1 100644 --- a/tools/editor/optimized_save_dialog.h +++ b/tools/editor/optimized_save_dialog.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/output_strings.cpp b/tools/editor/output_strings.cpp index 30569d11b0..a19352f4ec 100644 --- a/tools/editor/output_strings.cpp +++ b/tools/editor/output_strings.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/output_strings.h b/tools/editor/output_strings.h index ad893534fa..3d5deb1646 100644 --- a/tools/editor/output_strings.h +++ b/tools/editor/output_strings.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/pane_drag.cpp b/tools/editor/pane_drag.cpp index fb137de5ce..8e8c2941ec 100644 --- a/tools/editor/pane_drag.cpp +++ b/tools/editor/pane_drag.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/pane_drag.h b/tools/editor/pane_drag.h index a6cd9b6662..24f2ef7ed8 100644 --- a/tools/editor/pane_drag.h +++ b/tools/editor/pane_drag.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/SCsub b/tools/editor/plugins/SCsub index b525fb3f75..363a2ce4c0 100644 --- a/tools/editor/plugins/SCsub +++ b/tools/editor/plugins/SCsub @@ -1,7 +1,3 @@ Import('env') Export('env') env.add_source_files(env.tool_sources,"*.cpp") - - - - diff --git a/tools/editor/plugins/animation_data_editor_plugin.cpp b/tools/editor/plugins/animation_data_editor_plugin.cpp index d8d65b875a..a73c75056b 100644 --- a/tools/editor/plugins/animation_data_editor_plugin.cpp +++ b/tools/editor/plugins/animation_data_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/animation_data_editor_plugin.h b/tools/editor/plugins/animation_data_editor_plugin.h index 0daa67d0a5..0a12638474 100644 --- a/tools/editor/plugins/animation_data_editor_plugin.h +++ b/tools/editor/plugins/animation_data_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/animation_player_editor_plugin.cpp b/tools/editor/plugins/animation_player_editor_plugin.cpp index f8c484e886..12a707b2ca 100644 --- a/tools/editor/plugins/animation_player_editor_plugin.cpp +++ b/tools/editor/plugins/animation_player_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -27,7 +27,9 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "animation_player_editor_plugin.h" +#include "globals.h" #include "io/resource_loader.h" +#include "io/resource_saver.h" #include "os/keyboard.h" #include "tools/editor/editor_settings.h" @@ -98,6 +100,8 @@ void AnimationPlayerEditor::_notification(int p_what) { duplicate_anim->set_icon( get_icon("Duplicate","EditorIcons") ); autoplay->set_icon( get_icon("AutoPlay","EditorIcons") ); load_anim->set_icon( get_icon("Folder","EditorIcons") ); + save_anim->set_icon(get_icon("Save", "EditorIcons")); + save_anim->get_popup()->connect("item_pressed", this, "_animation_save_menu"); remove_anim->set_icon( get_icon("Remove","EditorIcons") ); edit_anim->set_icon( get_icon("Edit","EditorIcons") ); blend_anim->set_icon( get_icon("Blend","EditorIcons") ); @@ -367,9 +371,79 @@ void AnimationPlayerEditor::_animation_load() { } file->popup_centered_ratio(); + current_option = RESOURCE_LOAD; +} + + +void AnimationPlayerEditor::_animation_save_in_path(const Ref<Resource>& p_resource, const String& p_path) { + int flg = 0; + if (EditorSettings::get_singleton()->get("on_save/compress_binary_resources")) + flg |= ResourceSaver::FLAG_COMPRESS; + if (EditorSettings::get_singleton()->get("on_save/save_paths_as_relative")) + flg |= ResourceSaver::FLAG_RELATIVE_PATHS; + + String path = Globals::get_singleton()->localize_path(p_path); + Error err = ResourceSaver::save(path, p_resource, flg | ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS); + + if (err != OK) { + accept->set_text("Error saving resource!"); + accept->popup_centered_minsize(); + return; + } + // EditorFileSystem::get_singleton()->update_file(path,p_resource->get_type()); + + ((Resource*)p_resource.ptr())->set_path(path); + editor->emit_signal("resource_saved", p_resource); } + +void AnimationPlayerEditor::_animation_save(const Ref<Resource>& p_resource) { + + if (p_resource->get_path().is_resource_file()) { + _animation_save_in_path(p_resource, p_resource->get_path()); + } + else { + _animation_save_as(p_resource); + } +} + +void AnimationPlayerEditor::_animation_save_as(const Ref<Resource>& p_resource) { + + file->set_mode(EditorFileDialog::MODE_SAVE_FILE); + bool relpaths = (p_resource->has_meta("__editor_relpaths__") && p_resource->get_meta("__editor_relpaths__").operator bool()); + + List<String> extensions; + ResourceSaver::get_recognized_extensions(p_resource, &extensions); + file->clear_filters(); + for (int i = 0; i<extensions.size(); i++) { + + file->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper()); + } + + //file->set_current_path(current_path); + if (p_resource->get_path() != "") { + file->set_current_path(p_resource->get_path()); + if (extensions.size()) { + String ext = p_resource->get_path().extension().to_lower(); + if (extensions.find(ext) == NULL) { + file->set_current_path(p_resource->get_path().replacen("." + ext, "." + extensions.front()->get())); + } + } + } + else { + + String existing; + if (extensions.size()) { + existing = "new_" + p_resource->get_type().to_lower() + "." + extensions.front()->get().to_lower(); + } + file->set_current_path(existing); + + } + file->popup_centered_ratio(); + file->set_title("Save Resource As.."); + current_option = RESOURCE_SAVE; +} void AnimationPlayerEditor::_animation_remove() { if (animation->get_item_count()==0) @@ -635,38 +709,55 @@ void AnimationPlayerEditor::_animation_edit() { //get_scene()->get_root_node()->call("_resource_selected",anim,""); } -void AnimationPlayerEditor::_file_selected(String p_file) { +void AnimationPlayerEditor::_dialog_action(String p_file) { - ERR_FAIL_COND(!player); + switch (current_option) { + case RESOURCE_LOAD: { + ERR_FAIL_COND(!player); - Ref<Resource> res = ResourceLoader::load(p_file,"Animation"); - ERR_FAIL_COND(res.is_null()); - ERR_FAIL_COND( !res->is_type("Animation") ); - if (p_file.find_last("/")!=-1) { + Ref<Resource> res = ResourceLoader::load(p_file, "Animation"); + ERR_FAIL_COND(res.is_null()); + ERR_FAIL_COND(!res->is_type("Animation")); + if (p_file.find_last("/") != -1) { - p_file=p_file.substr( p_file.find_last("/")+1, p_file.length() ); + p_file = p_file.substr(p_file.find_last("/") + 1, p_file.length()); - } - if (p_file.find_last("\\")!=-1) { + } + if (p_file.find_last("\\") != -1) { - p_file=p_file.substr( p_file.find_last("\\")+1, p_file.length() ); + p_file = p_file.substr(p_file.find_last("\\") + 1, p_file.length()); - } + } - if (p_file.find(".")!=-1) - p_file=p_file.substr(0,p_file.find(".")); + if (p_file.find(".") != -1) + p_file = p_file.substr(0, p_file.find(".")); - undo_redo->create_action("Load Animation"); - undo_redo->add_do_method(player,"add_animation",p_file,res); - undo_redo->add_undo_method(player,"remove_animation",p_file); - if (player->has_animation(p_file)) { - undo_redo->add_undo_method(player,"add_animation",p_file,player->get_animation(p_file)); + undo_redo->create_action("Load Animation"); + undo_redo->add_do_method(player, "add_animation", p_file, res); + undo_redo->add_undo_method(player, "remove_animation", p_file); + if (player->has_animation(p_file)) { + undo_redo->add_undo_method(player, "add_animation", p_file, player->get_animation(p_file)); - } - undo_redo->add_do_method(this,"_animation_player_changed",player); - undo_redo->add_undo_method(this,"_animation_player_changed",player); - undo_redo->commit_action(); + } + undo_redo->add_do_method(this, "_animation_player_changed", player); + undo_redo->add_undo_method(this, "_animation_player_changed", player); + undo_redo->commit_action(); + break; + } + case RESOURCE_SAVE: { + + String current = animation->get_item_text(animation->get_selected()); + if (current != "") { + Ref<Animation> anim = player->get_animation(current); + + ERR_FAIL_COND(!anim->cast_to<Resource>()) + + RES current_res = RES(anim->cast_to<Resource>()); + _animation_save_in_path(current_res, p_file); + } + } + } } void AnimationPlayerEditor::_scale_changed(const String& p_scale) { @@ -730,6 +821,8 @@ void AnimationPlayerEditor::_update_player() { blend_anim->set_disabled(animlist.size()==0); remove_anim->set_disabled(animlist.size()==0); resource_edit_anim->set_disabled(animlist.size()==0); + save_anim->set_disabled(animlist.size() == 0); + int active_idx=-1; for (List<StringName>::Element *E=animlist.front();E;E=E->next()) { @@ -1072,6 +1165,23 @@ void AnimationPlayerEditor::_animation_tool_menu(int p_option) { } } +void AnimationPlayerEditor::_animation_save_menu(int p_option) { + + String current = animation->get_item_text(animation->get_selected()); + if (current != "") { + Ref<Animation> anim = player->get_animation(current); + + switch (p_option) { + case ANIM_SAVE: + _animation_save(anim); + break; + case ANIM_SAVE_AS: + _animation_save_as(anim); + break; + } + } +} + void AnimationPlayerEditor::_unhandled_key_input(const InputEvent& p_ev) { if (is_visible() && p_ev.type==InputEvent::KEY && p_ev.key.pressed && !p_ev.key.echo && !p_ev.key.mod.alt && !p_ev.key.mod.control && !p_ev.key.mod.meta) { @@ -1117,7 +1227,7 @@ void AnimationPlayerEditor::_bind_methods() { ObjectTypeDB::bind_method(_MD("_animation_blend"),&AnimationPlayerEditor::_animation_blend); ObjectTypeDB::bind_method(_MD("_animation_edit"),&AnimationPlayerEditor::_animation_edit); ObjectTypeDB::bind_method(_MD("_animation_resource_edit"),&AnimationPlayerEditor::_animation_resource_edit); - ObjectTypeDB::bind_method(_MD("_file_selected"),&AnimationPlayerEditor::_file_selected); + ObjectTypeDB::bind_method(_MD("_dialog_action"),&AnimationPlayerEditor::_dialog_action); ObjectTypeDB::bind_method(_MD("_seek_value_changed"),&AnimationPlayerEditor::_seek_value_changed); ObjectTypeDB::bind_method(_MD("_animation_player_changed"),&AnimationPlayerEditor::_animation_player_changed); ObjectTypeDB::bind_method(_MD("_blend_edited"),&AnimationPlayerEditor::_blend_edited); @@ -1133,14 +1243,22 @@ void AnimationPlayerEditor::_bind_methods() { ObjectTypeDB::bind_method(_MD("_blend_editor_next_changed"),&AnimationPlayerEditor::_blend_editor_next_changed); ObjectTypeDB::bind_method(_MD("_unhandled_key_input"),&AnimationPlayerEditor::_unhandled_key_input); ObjectTypeDB::bind_method(_MD("_animation_tool_menu"),&AnimationPlayerEditor::_animation_tool_menu); + ObjectTypeDB::bind_method(_MD("_animation_save_menu"), &AnimationPlayerEditor::_animation_save_menu); } +AnimationPlayerEditor *AnimationPlayerEditor::singleton=NULL; + +AnimationPlayer *AnimationPlayerEditor::get_player() const { + + return player; +} AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor) { editor=p_editor; + singleton=this; updating=false; @@ -1170,6 +1288,17 @@ AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor) { load_anim->set_tooltip("Load an animation from disk."); hb->add_child(load_anim); + save_anim = memnew(MenuButton); + save_anim->set_tooltip("Save the current animation"); + save_anim->get_popup()->add_item("Save", ANIM_SAVE); + save_anim->get_popup()->add_item("Save As..", ANIM_SAVE_AS); + save_anim->set_focus_mode(Control::FOCUS_NONE); + hb->add_child(save_anim); + + accept = memnew(AcceptDialog); + add_child(accept); + accept->connect("confirmed", this, "_menu_confirm_current"); + duplicate_anim = memnew( ToolButton ); hb->add_child(duplicate_anim); duplicate_anim->set_tooltip("Duplicate Animation"); @@ -1279,6 +1408,7 @@ AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor) { add_child(file); name_dialog = memnew( ConfirmationDialog ); + name_dialog->set_title("Create New Animation"); name_dialog->set_hide_on_ok(false); add_child(name_dialog); name = memnew( LineEdit ); @@ -1339,7 +1469,7 @@ AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor) { remove_anim->connect("pressed", this,"_animation_remove"); animation->connect("item_selected", this,"_animation_selected",Vector<Variant>(),true); resource_edit_anim->connect("pressed", this,"_animation_resource_edit"); - file->connect("file_selected", this,"_file_selected"); + file->connect("file_selected", this,"_dialog_action"); seek->connect("value_changed", this, "_seek_value_changed",Vector<Variant>(),true); scale->connect("text_entered", this, "_scale_changed",Vector<Variant>(),true); editor->get_animation_editor()->connect("timeline_changed",this,"_animation_key_editor_seek"); diff --git a/tools/editor/plugins/animation_player_editor_plugin.h b/tools/editor/plugins/animation_player_editor_plugin.h index 5705742565..9fbd92e4f0 100644 --- a/tools/editor/plugins/animation_player_editor_plugin.h +++ b/tools/editor/plugins/animation_player_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -55,6 +55,17 @@ class AnimationPlayerEditor : public VBoxContainer { TOOL_EDIT_RESOURCE }; + enum { + ANIM_SAVE, + ANIM_SAVE_AS + }; + + enum { + RESOURCE_LOAD, + RESOURCE_SAVE + }; + + OptionButton *animation; Button *stop; Button *play; @@ -70,6 +81,7 @@ class AnimationPlayerEditor : public VBoxContainer { Button *edit_anim; Button *resource_edit_anim; Button *load_anim; + MenuButton *save_anim; Button *blend_anim; Button *remove_anim; MenuButton *tool_anim; @@ -85,6 +97,8 @@ class AnimationPlayerEditor : public VBoxContainer { bool last_active; EditorFileDialog *file; + AcceptDialog *accept; + int current_option; struct BlendEditor { @@ -116,13 +130,18 @@ class AnimationPlayerEditor : public VBoxContainer { void _animation_rename(); void _animation_name_edited(); void _animation_load(); + + void _animation_save_in_path(const Ref<Resource>& p_resource, const String& p_path); + void _animation_save(const Ref<Resource>& p_resource); + void _animation_save_as(const Ref<Resource>& p_resource); + void _animation_remove(); void _animation_blend(); void _animation_edit(); void _animation_duplicate(); void _animation_resource_edit(); void _scale_changed(const String& p_scale); - void _file_selected(String p_file); + void _dialog_action(String p_file); void _seek_frame_changed(const String& p_frame); void _seek_value_changed(float p_value); void _blend_editor_next_changed(const String& p_string); @@ -141,6 +160,8 @@ class AnimationPlayerEditor : public VBoxContainer { void _animation_key_editor_anim_len_changed(float p_new); void _unhandled_key_input(const InputEvent& p_ev); void _animation_tool_menu(int p_option); + void _animation_save_menu(int p_option); + AnimationPlayerEditor(); protected: @@ -151,6 +172,9 @@ protected: static void _bind_methods(); public: + AnimationPlayer *get_player() const; + static AnimationPlayerEditor *singleton; + Dictionary get_state() const; void set_state(const Dictionary& p_state); diff --git a/tools/editor/plugins/animation_tree_editor_plugin.cpp b/tools/editor/plugins/animation_tree_editor_plugin.cpp index 382bc44726..609b1ccb63 100644 --- a/tools/editor/plugins/animation_tree_editor_plugin.cpp +++ b/tools/editor/plugins/animation_tree_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/animation_tree_editor_plugin.h b/tools/editor/plugins/animation_tree_editor_plugin.h index bd29530c7a..fb7eb58f8d 100644 --- a/tools/editor/plugins/animation_tree_editor_plugin.h +++ b/tools/editor/plugins/animation_tree_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/camera_editor_plugin.cpp b/tools/editor/plugins/camera_editor_plugin.cpp index 08ed2c745d..7433264b16 100644 --- a/tools/editor/plugins/camera_editor_plugin.cpp +++ b/tools/editor/plugins/camera_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/camera_editor_plugin.h b/tools/editor/plugins/camera_editor_plugin.h index afb8f9415d..ea016ecb4d 100644 --- a/tools/editor/plugins/camera_editor_plugin.h +++ b/tools/editor/plugins/camera_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/canvas_item_editor_plugin.cpp b/tools/editor/plugins/canvas_item_editor_plugin.cpp index d318f6f6fa..f3cf53cbdf 100644 --- a/tools/editor/plugins/canvas_item_editor_plugin.cpp +++ b/tools/editor/plugins/canvas_item_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -41,9 +41,9 @@ class SnapDialog : public ConfirmationDialog { OBJ_TYPE(SnapDialog,ConfirmationDialog); - -protected: - friend class CanvasItemEditor; + +friend class CanvasItemEditor; + SpinBox *grid_offset_x; SpinBox *grid_offset_y; SpinBox *grid_step_x; @@ -58,63 +58,75 @@ public: Label *label; VBoxContainer *container; GridContainer *child_container; - + set_title("Configure Snap"); get_ok()->set_text("Close"); - container = memnew(VBoxContainer); + + container = memnew( VBoxContainer ); add_child(container); - - child_container = memnew(GridContainer); + set_child_rect(container); + + child_container = memnew( GridContainer ); child_container->set_columns(3); container->add_child(child_container); - - label = memnew(Label); + + label = memnew( Label ); label->set_text("Grid Offset:"); child_container->add_child(label); - grid_offset_x=memnew(SpinBox); + label->set_h_size_flags(SIZE_EXPAND_FILL); + + grid_offset_x = memnew( SpinBox ); grid_offset_x->set_min(-SPIN_BOX_GRID_RANGE); grid_offset_x->set_max(SPIN_BOX_GRID_RANGE); grid_offset_x->set_suffix("px"); child_container->add_child(grid_offset_x); - grid_offset_y=memnew(SpinBox); + + grid_offset_y = memnew( SpinBox ); grid_offset_y->set_min(-SPIN_BOX_GRID_RANGE); grid_offset_y->set_max(SPIN_BOX_GRID_RANGE); grid_offset_y->set_suffix("px"); child_container->add_child(grid_offset_y); - label = memnew(Label); + label = memnew( Label ); label->set_text("Grid Step:"); child_container->add_child(label); - grid_step_x=memnew(SpinBox); + label->set_h_size_flags(SIZE_EXPAND_FILL); + + grid_step_x = memnew( SpinBox ); grid_step_x->set_min(-SPIN_BOX_GRID_RANGE); grid_step_x->set_max(SPIN_BOX_GRID_RANGE); grid_step_x->set_suffix("px"); child_container->add_child(grid_step_x); - grid_step_y=memnew(SpinBox); + + grid_step_y = memnew( SpinBox ); grid_step_y->set_min(-SPIN_BOX_GRID_RANGE); grid_step_y->set_max(SPIN_BOX_GRID_RANGE); grid_step_y->set_suffix("px"); child_container->add_child(grid_step_y); - - container->add_child(memnew(HSeparator)); - child_container = memnew(GridContainer); + container->add_child( memnew( HSeparator ) ); + + child_container = memnew( GridContainer ); child_container->set_columns(2); container->add_child(child_container); - label = memnew(Label); + label = memnew( Label ); label->set_text("Rotation Offset:"); child_container->add_child(label); - rotation_offset=memnew(SpinBox); + label->set_h_size_flags(SIZE_EXPAND_FILL); + + rotation_offset = memnew( SpinBox ); rotation_offset->set_min(-SPIN_BOX_ROTATION_RANGE); rotation_offset->set_max(SPIN_BOX_ROTATION_RANGE); rotation_offset->set_suffix("deg"); child_container->add_child(rotation_offset); - - label = memnew(Label); + + label = memnew( Label ); label->set_text("Rotation Step:"); child_container->add_child(label); - rotation_step=memnew(SpinBox); + label->set_h_size_flags(SIZE_EXPAND_FILL); + + rotation_step = memnew( SpinBox ); rotation_step->set_min(-SPIN_BOX_ROTATION_RANGE); rotation_step->set_max(SPIN_BOX_ROTATION_RANGE); rotation_step->set_suffix("deg"); @@ -140,6 +152,46 @@ public: } }; +void CanvasItemEditor::_edit_set_pivot(const Vector2& mouse_pos) { + List<Node*> &selection = editor_selection->get_selected_node_list(); + + undo_redo->create_action("Move Pivot"); + + for(List<Node*>::Element *E=selection.front();E;E=E->next()) { + + Node2D *n2d = E->get()->cast_to<Node2D>(); + + if (n2d && n2d->edit_has_pivot()) { + + Vector2 offset = n2d->edit_get_pivot(); + Vector2 gpos = n2d->get_global_pos(); + + Vector2 local_mouse_pos = n2d->get_canvas_transform().affine_inverse().xform(mouse_pos); + + Vector2 motion_ofs = gpos-local_mouse_pos; + + undo_redo->add_do_method(n2d,"set_global_pos",local_mouse_pos); + undo_redo->add_do_method(n2d,"edit_set_pivot",offset+n2d->get_global_transform().affine_inverse().basis_xform(motion_ofs)); + undo_redo->add_undo_method(n2d,"set_global_pos",gpos); + undo_redo->add_undo_method(n2d,"edit_set_pivot",offset); + for(int i=0;i<n2d->get_child_count();i++) { + Node2D *n2dc = n2d->get_child(i)->cast_to<Node2D>(); + if (!n2dc) + continue; + + undo_redo->add_do_method(n2dc,"set_global_pos",n2dc->get_global_pos()); + undo_redo->add_undo_method(n2dc,"set_global_pos",n2dc->get_global_pos()); + + } + + } + + } + + undo_redo->commit_action(); + +} + void CanvasItemEditor::_unhandled_key_input(const InputEvent& p_ev) { if (!is_visible()) @@ -167,38 +219,7 @@ void CanvasItemEditor::_unhandled_key_input(const InputEvent& p_ev) { mouse_pos=transform.affine_inverse().xform(mouse_pos); mouse_pos=snap_point(mouse_pos); - undo_redo->create_action("Move Pivot"); - - for(List<Node*>::Element *E=selection.front();E;E=E->next()) { - - Node2D *n2d = E->get()->cast_to<Node2D>(); - - if (n2d && n2d->edit_has_pivot()) { - - Vector2 offset = n2d->edit_get_pivot(); - Vector2 gpos = n2d->get_global_pos(); - - Vector2 motion_ofs = gpos-mouse_pos; - - undo_redo->add_do_method(n2d,"set_global_pos",mouse_pos); - undo_redo->add_do_method(n2d,"edit_set_pivot",offset+n2d->get_global_transform().affine_inverse().basis_xform(motion_ofs)); - undo_redo->add_undo_method(n2d,"set_global_pos",gpos); - undo_redo->add_undo_method(n2d,"edit_set_pivot",offset); - for(int i=0;i<n2d->get_child_count();i++) { - Node2D *n2dc = n2d->get_child(i)->cast_to<Node2D>(); - if (!n2dc) - continue; - - undo_redo->add_do_method(n2dc,"set_global_pos",n2dc->get_global_pos()); - undo_redo->add_undo_method(n2dc,"set_global_pos",n2dc->get_global_pos()); - - } - - } - - } - - undo_redo->commit_action(); + _edit_set_pivot(mouse_pos); } } @@ -209,7 +230,7 @@ void CanvasItemEditor::_unhandled_key_input(const InputEvent& p_ev) { void CanvasItemEditor::_tool_select(int p_index) { - ToolButton *tb[TOOL_MAX]={select_button,move_button,rotate_button,pan_button}; + ToolButton *tb[TOOL_MAX]={select_button,list_select_button,move_button,rotate_button,pivot_button,pan_button}; for(int i=0;i<TOOL_MAX;i++) { tb[i]->set_pressed(i==p_index); @@ -411,8 +432,6 @@ CanvasItem* CanvasItemEditor::_select_canvas_item_at_pos(const Point2& p_pos,Nod r=_select_canvas_item_at_pos(p_pos,p_node->get_child(i),p_parent_xform * c->get_transform(),p_canvas_xform); else { CanvasLayer *cl = p_node->cast_to<CanvasLayer>(); - if (cl) - return NULL; r=_select_canvas_item_at_pos(p_pos,p_node->get_child(i),transform ,cl ? cl->get_transform() : p_canvas_xform); //use base transform } @@ -421,7 +440,7 @@ CanvasItem* CanvasItemEditor::_select_canvas_item_at_pos(const Point2& p_pos,Nod } - if (c && c->is_visible() && !c->has_meta("_edit_lock_")) { + if (c && c->is_visible() && !c->has_meta("_edit_lock_") && !c->cast_to<CanvasLayer>()) { Rect2 rect = c->get_item_rect(); Point2 local_pos = (p_parent_xform * p_canvas_xform * c->get_transform()).affine_inverse().xform(p_pos); @@ -435,6 +454,45 @@ CanvasItem* CanvasItemEditor::_select_canvas_item_at_pos(const Point2& p_pos,Nod return NULL; } +void CanvasItemEditor::_find_canvas_items_at_pos(const Point2 &p_pos,Node* p_node,const Matrix32& p_parent_xform,const Matrix32& p_canvas_xform, Vector<_SelectResult> &r_items) { + if (!p_node) + return; + if (p_node->cast_to<Viewport>()) + return; + + CanvasItem *c=p_node->cast_to<CanvasItem>(); + + for (int i=p_node->get_child_count()-1;i>=0;i--) { + + if (c && !c->is_set_as_toplevel()) + _find_canvas_items_at_pos(p_pos,p_node->get_child(i),p_parent_xform * c->get_transform(),p_canvas_xform, r_items); + else { + CanvasLayer *cl = p_node->cast_to<CanvasLayer>(); + _find_canvas_items_at_pos(p_pos,p_node->get_child(i),transform ,cl ? cl->get_transform() : p_canvas_xform, r_items); //use base transform + } + } + + + if (c && c->is_visible() && !c->has_meta("_edit_lock_") && !c->cast_to<CanvasLayer>()) { + + Rect2 rect = c->get_item_rect(); + Point2 local_pos = (p_parent_xform * p_canvas_xform * c->get_transform()).affine_inverse().xform(p_pos); + + + if (rect.has_point(local_pos)) { + Node2D *node=c->cast_to<Node2D>(); + + _SelectResult res; + res.item=c; + res.z=node?node->get_z():0; + res.has_z=node; + r_items.push_back(res); + } + + } + + return; +} void CanvasItemEditor::_find_canvas_items_at_rect(const Rect2& p_rect,Node* p_node,const Matrix32& p_parent_xform,const Matrix32& p_canvas_xform,List<CanvasItem*> *r_items) { @@ -452,14 +510,12 @@ void CanvasItemEditor::_find_canvas_items_at_rect(const Rect2& p_rect,Node* p_no _find_canvas_items_at_rect(p_rect,p_node->get_child(i),p_parent_xform * c->get_transform(),p_canvas_xform,r_items); else { CanvasLayer *cl = p_node->cast_to<CanvasLayer>(); - if (cl) - return; _find_canvas_items_at_rect(p_rect,p_node->get_child(i),transform,cl?cl->get_transform():p_canvas_xform,r_items); } } - if (c && c->is_visible() && !c->has_meta("_edit_lock_")) { + if (c && c->is_visible() && !c->has_meta("_edit_lock_") && !c->cast_to<CanvasLayer>()) { Rect2 rect = c->get_item_rect(); Matrix32 xform = p_parent_xform * p_canvas_xform * c->get_transform(); @@ -477,6 +533,96 @@ void CanvasItemEditor::_find_canvas_items_at_rect(const Rect2& p_rect,Node* p_no } +bool CanvasItemEditor::_select(CanvasItem *item, Point2 p_click_pos, bool p_append, bool p_drag) { + + if (p_append) { + //additive selection + + if (!item) { + + if (p_drag) { + drag_from=transform.affine_inverse().xform(p_click_pos); + + box_selecting=true; + box_selecting_to=drag_from; + } + + return false; //nothing to add + } + + if (editor_selection->is_selected(item)) { + //already in here, erase it + editor_selection->remove_node(item); + //_remove_canvas_item(c); + + viewport->update(); + return false; + + } + _append_canvas_item(item); + viewport->update(); + + } else { + //regular selection + + if (!item) { + //clear because nothing clicked + editor_selection->clear();; + + if (p_drag) { + drag_from=transform.affine_inverse().xform(p_click_pos); + + box_selecting=true; + box_selecting_to=drag_from; + } + + viewport->update(); + return false; + } + + if (!editor_selection->is_selected(item)) { + //select a new one and clear previous selection + editor_selection->clear(); + editor_selection->add_node(item); + //reselect + if (get_tree()->is_editor_hint()) { + editor->call("edit_node",item); + } + + } + + if (p_drag) { + //prepare to move! + + List<Node*> &selection = editor_selection->get_selected_node_list(); + + for(List<Node*>::Element *E=selection.front();E;E=E->next()) { + + CanvasItem *canvas_item = E->get()->cast_to<CanvasItem>(); + if (!canvas_item || !canvas_item->is_visible()) + continue; + CanvasItemEditorSelectedItem *se=editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item); + if (!se) + continue; + + se->undo_state=canvas_item->edit_get_state(); + if (canvas_item->cast_to<Node2D>()) + se->undo_pivot=canvas_item->cast_to<Node2D>()->edit_get_pivot(); + + } + + drag=DRAG_ALL; + drag_from=transform.affine_inverse().xform(p_click_pos); + drag_point_from=_find_topleftmost_point(); + } + + viewport->update(); + + return true; + + } +} + void CanvasItemEditor::_key_move(const Vector2& p_dir, bool p_snap, KeyMoveMODE p_move_mode) { @@ -776,6 +922,24 @@ void CanvasItemEditor::_dialog_value_changed(double) { } } +void CanvasItemEditor::_selection_result_pressed(int p_result) { + + if (selection_results.size() <= p_result) + return; + + CanvasItem *item=selection_results[p_result].item; + + if (item) + _select(item, Point2(), additive_selection, false); +} + +void CanvasItemEditor::_selection_menu_hide() { + + selection_results.clear(); + selection_menu->clear(); + selection_menu->set_size(Vector2(0, 0)); +} + bool CanvasItemEditor::get_remove_list(List<Node*> *p_list) { @@ -783,6 +947,75 @@ bool CanvasItemEditor::get_remove_list(List<Node*> *p_list) { } +void CanvasItemEditor::_list_select(const InputEventMouseButton& b) { + + Point2 click=Point2(b.x,b.y); + + Node* scene = editor->get_edited_scene(); + if (!scene) + return; + + _find_canvas_items_at_pos(click, scene,transform,Matrix32(), selection_results); + + for(int i=0;i<selection_results.size();i++) { + CanvasItem *item=selection_results[i].item; + if (item!=scene && item->get_owner()!=scene && !scene->is_editable_instance(item->get_owner())) { + //invalid result + selection_results.remove(i); + i--; + } + + } + + if (selection_results.size() == 1) { + + CanvasItem *item = selection_results[0].item; + selection_results.clear(); + + additive_selection=b.mod.shift; + if (!_select(item, click, additive_selection, false)) + return; + + } else if (!selection_results.empty()) { + + selection_results.sort(); + + NodePath root_path = get_tree()->get_edited_scene_root()->get_path(); + StringName root_name = root_path.get_name(root_path.get_name_count()-1); + + for (int i = 0; i < selection_results.size(); i++) { + + CanvasItem *item=selection_results[i].item; + + + Ref<Texture> icon; + if (item->has_meta("_editor_icon")) + icon=item->get_meta("_editor_icon"); + else + icon=get_icon( has_icon(item->get_type(),"EditorIcons")?item->get_type():String("Object"),"EditorIcons"); + + String node_path="/"+root_name+"/"+root_path.rel_path_to(item->get_path()); + + selection_menu->add_item(item->get_name()); + selection_menu->set_item_icon(i, icon ); + selection_menu->set_item_metadata(i, node_path); + selection_menu->set_item_tooltip(i,String(item->get_name())+ + "\nType: "+item->get_type()+"\nPath: "+node_path); + } + + additive_selection=b.mod.shift; + + selection_menu->set_global_pos(Vector2( b.global_x, b.global_y )); + selection_menu->popup(); + selection_menu->call_deferred("grab_click_focus"); + selection_menu->set_invalidate_click_until_motion(); + + + return; + } + +} + void CanvasItemEditor::_viewport_input_event(const InputEvent& p_event) { { @@ -839,6 +1072,11 @@ void CanvasItemEditor::_viewport_input_event(const InputEvent& p_event) { if (b.button_index==BUTTON_RIGHT) { + if (b.pressed && (tool==TOOL_SELECT && b.mod.alt)) { + + _list_select(b); + return; + } if (get_item_count() > 0 && drag!=DRAG_NONE) { //cancel drag @@ -895,6 +1133,26 @@ void CanvasItemEditor::_viewport_input_event(const InputEvent& p_event) { //if (!canvas_items.size()) // return; + if (b.button_index==BUTTON_LEFT && tool==TOOL_LIST_SELECT) { + if (b.pressed) + _list_select(b); + return; + } + + + if (b.button_index==BUTTON_LEFT && tool==TOOL_EDIT_PIVOT) { + if (b.pressed) { + + Point2 mouse_pos(b.x,b.y); + mouse_pos=transform.affine_inverse().xform(mouse_pos); + mouse_pos=snap_point(mouse_pos); + _edit_set_pivot(mouse_pos); + } + return; + } + + + if (tool==TOOL_PAN || b.button_index!=BUTTON_LEFT || Input::get_singleton()->is_key_pressed(KEY_SPACE)) return; @@ -1203,82 +1461,10 @@ void CanvasItemEditor::_viewport_input_event(const InputEvent& p_event) { #if 0 if ( b.pressed ) box_selection_start( click ); #endif - if (b.mod.shift) { //additive selection - - if (!c) { - - drag_from=transform.affine_inverse().xform(click); - - box_selecting=true; - box_selecting_to=drag_from; - - return; //nothing to add - } - - if (editor_selection->is_selected(c)) { - //already in here, erase it - editor_selection->remove_node(c); - //_remove_canvas_item(c); - - viewport->update(); - return; - - } - _append_canvas_item(c); - viewport->update(); - } else { - //regular selection - - - - if (!c) { - //clear because nothing clicked - editor_selection->clear();; - - drag_from=transform.affine_inverse().xform(click); - - box_selecting=true; - box_selecting_to=drag_from; - viewport->update(); - return; - } - - if (!editor_selection->is_selected(c)) { - //select a new one and clear previous selection - editor_selection->clear(); - editor_selection->add_node(c); - //reselect - if (get_tree()->is_editor_hint()) { - editor->call("edit_node",c); - } - } - - //prepare to move! - - List<Node*> &selection = editor_selection->get_selected_node_list(); - - for(List<Node*>::Element *E=selection.front();E;E=E->next()) { - - CanvasItem *canvas_item = E->get()->cast_to<CanvasItem>(); - if (!canvas_item || !canvas_item->is_visible()) - continue; - CanvasItemEditorSelectedItem *se=editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item); - if (!se) - continue; - - se->undo_state=canvas_item->edit_get_state(); - if (canvas_item->cast_to<Node2D>()) - se->undo_pivot=canvas_item->cast_to<Node2D>()->edit_get_pivot(); - - } - - drag=DRAG_ALL; - drag_from=transform.affine_inverse().xform(click); - drag_point_from=_find_topleftmost_point(); - viewport->update(); - - } + additive_selection=b.mod.shift; + if (!_select(c, click, additive_selection)) + return; } @@ -1346,7 +1532,7 @@ void CanvasItemEditor::_viewport_input_event(const InputEvent& p_event) { Matrix32 rot; rot.elements[1] = (dfrom - center).normalized(); rot.elements[0] = rot.elements[1].tangent(); - node->set_rot(snap_angle(rot.xform_inv(dto-center).atan2(), node->get_rot())); + node->set_rot(snap_angle(rot.xform_inv(dto-center).angle(), node->get_rot())); display_rotate_to = dto; display_rotate_from = center; viewport->update(); @@ -1695,6 +1881,8 @@ void CanvasItemEditor::_viewport_draw() { CanvasItem *single_item=NULL; + bool pivot_found=false; + for(Map<Node*,Object*>::Element *E=selection.front();E;E=E->next()) { @@ -1736,7 +1924,7 @@ void CanvasItemEditor::_viewport_draw() { viewport->draw_line(endpoints[i],endpoints[(i+1)%4],c,2); } - if (single && (tool==TOOL_SELECT || tool == TOOL_MOVE || tool == TOOL_ROTATE)) { //kind of sucks + if (single && (tool==TOOL_SELECT || tool == TOOL_MOVE || tool == TOOL_ROTATE || tool==TOOL_EDIT_PIVOT)) { //kind of sucks if (canvas_item->cast_to<Node2D>()) { @@ -1744,6 +1932,7 @@ void CanvasItemEditor::_viewport_draw() { if (canvas_item->cast_to<Node2D>()->edit_has_pivot()) { viewport->draw_texture(pivot,xform.get_origin()+(-pivot->get_size()/2).floor()); can_move_pivot=true; + pivot_found=true; } } @@ -1778,6 +1967,7 @@ void CanvasItemEditor::_viewport_draw() { //E->get().last_rect = rect; } + pivot_button->set_disabled(!pivot_found); VisualServer::get_singleton()->canvas_item_add_set_transform(ci,Matrix32()); @@ -1982,9 +2172,11 @@ void CanvasItemEditor::_notification(int p_what) { } select_button->set_icon( get_icon("ToolSelect","EditorIcons")); + list_select_button->set_icon( get_icon("ListSelect","EditorIcons")); move_button->set_icon( get_icon("ToolMove","EditorIcons")); rotate_button->set_icon( get_icon("ToolRotate","EditorIcons")); pan_button->set_icon( get_icon("ToolPan", "EditorIcons")); + pivot_button->set_icon( get_icon("EditPivot", "EditorIcons")); select_handle=get_icon("EditorHandle","EditorIcons"); lock_button->set_icon(get_icon("Lock","EditorIcons")); unlock_button->set_icon(get_icon("Unlock","EditorIcons")); @@ -2278,7 +2470,7 @@ void CanvasItemEditor::_popup_callback(int p_op) { } break; case SNAP_CONFIGURE: { ((SnapDialog *)snap_dialog)->set_fields(snap_offset, snap_step, snap_rotation_offset, snap_rotation_step); - snap_dialog->popup_centered(Size2(200,160)); + snap_dialog->popup_centered(Size2(220,160)); } break; case ZOOM_IN: { zoom=zoom*(1.0/0.5); @@ -2867,6 +3059,8 @@ void CanvasItemEditor::_bind_methods() { ObjectTypeDB::bind_method("_viewport_draw",&CanvasItemEditor::_viewport_draw); ObjectTypeDB::bind_method("_viewport_input_event",&CanvasItemEditor::_viewport_input_event); ObjectTypeDB::bind_method("_snap_changed",&CanvasItemEditor::_snap_changed); + ObjectTypeDB::bind_method(_MD("_selection_result_pressed"),&CanvasItemEditor::_selection_result_pressed); + ObjectTypeDB::bind_method(_MD("_selection_menu_hide"),&CanvasItemEditor::_selection_menu_hide); ADD_SIGNAL( MethodInfo("item_lock_status_changed") ); ADD_SIGNAL( MethodInfo("item_group_status_changed") ); @@ -3017,7 +3211,8 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { hb->add_child(select_button); select_button->connect("pressed",this,"_tool_select",make_binds(TOOL_SELECT)); select_button->set_pressed(true); - select_button->set_tooltip("Select Mode (Q)\n"+keycode_get_string(KEY_MASK_CMD)+"Drag: Rotate\nAlt+Drag: Move\nPress 'v' to Change Pivot, 'Shift+v' to Drag Pivot (while moving)."); + select_button->set_tooltip("Select Mode (Q)\n"+keycode_get_string(KEY_MASK_CMD)+"Drag: Rotate\nAlt+Drag: Move\nPress 'v' to Change Pivot, 'Shift+v' to Drag Pivot (while moving).\nAlt+RMB: Depth list selection"); + move_button = memnew( ToolButton ); move_button->set_toggle_mode(true); @@ -3033,6 +3228,18 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { hb->add_child(memnew(VSeparator)); + list_select_button = memnew( ToolButton ); + list_select_button->set_toggle_mode(true); + hb->add_child(list_select_button); + list_select_button->connect("pressed",this,"_tool_select",make_binds(TOOL_LIST_SELECT)); + list_select_button->set_tooltip("Show a list of all objects at the position clicked\n(same as Alt+RMB in selet mode)."); + + pivot_button = memnew( ToolButton ); + pivot_button->set_toggle_mode(true); + hb->add_child(pivot_button); + pivot_button->connect("pressed",this,"_tool_select",make_binds(TOOL_EDIT_PIVOT)); + pivot_button->set_tooltip("Click to change object's rotation pivot"); + pan_button = memnew( ToolButton ); pan_button->set_toggle_mode(true); hb->add_child(pan_button); @@ -3173,7 +3380,7 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { p->add_item("Paste Pose",ANIM_PASTE_POSE); p->add_item("Clear Pose",ANIM_CLEAR_POSE,KEY_MASK_SHIFT|KEY_K); - snap_dialog = memnew(SnapDialog); + snap_dialog = memnew( SnapDialog ); snap_dialog->connect("confirmed",this,"_snap_changed"); add_child(snap_dialog); @@ -3196,6 +3403,12 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { dialog_val->connect("value_changed",this,"_dialog_value_changed"); select_sb = Ref<StyleBoxTexture>( memnew( StyleBoxTexture) ); + selection_menu = memnew( PopupMenu ); + add_child(selection_menu); + selection_menu->set_custom_minimum_size(Vector2(100, 0)); + selection_menu->connect("item_pressed", this, "_selection_result_pressed"); + selection_menu->connect("popup_hide", this, "_selection_menu_hide"); + key_pos=true; key_rot=true; key_scale=false; @@ -3218,6 +3431,7 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { can_move_pivot=false; drag=DRAG_NONE; bone_last_frame=0; + additive_selection=false; } CanvasItemEditor *CanvasItemEditor::singleton=NULL; diff --git a/tools/editor/plugins/canvas_item_editor_plugin.h b/tools/editor/plugins/canvas_item_editor_plugin.h index 485422028e..91cfab9863 100644 --- a/tools/editor/plugins/canvas_item_editor_plugin.h +++ b/tools/editor/plugins/canvas_item_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -67,8 +67,10 @@ class CanvasItemEditor : public VBoxContainer { enum Tool { TOOL_SELECT, + TOOL_LIST_SELECT, TOOL_MOVE, TOOL_ROTATE, + TOOL_EDIT_PIVOT, TOOL_PAN, TOOL_MAX }; @@ -150,6 +152,7 @@ class CanvasItemEditor : public VBoxContainer { }; EditorSelection *editor_selection; + bool additive_selection; Tool tool; bool first_update; @@ -183,6 +186,18 @@ class CanvasItemEditor : public VBoxContainer { MenuOption last_option; + struct _SelectResult { + + CanvasItem* item; + float z; + bool has_z; + _FORCE_INLINE_ bool operator<(const _SelectResult& p_rr) const { + return has_z && p_rr.has_z ? p_rr.z < z : p_rr.has_z; + } + }; + + Vector<_SelectResult> selection_results; + struct LockList { Point2 pos; bool lock; @@ -227,9 +242,11 @@ class CanvasItemEditor : public VBoxContainer { List<PoseClipboard> pose_clipboard; ToolButton *select_button; + ToolButton *list_select_button; ToolButton *move_button; ToolButton *rotate_button; + ToolButton *pivot_button; ToolButton *pan_button; ToolButton *lock_button; @@ -249,6 +266,9 @@ class CanvasItemEditor : public VBoxContainer { Button *key_scale_button; Button *key_insert_button; + PopupMenu *selection_menu; + + //PopupMenu *popup; DragType drag; Point2 drag_from; @@ -276,8 +296,11 @@ class CanvasItemEditor : public VBoxContainer { int handle_len; CanvasItem* _select_canvas_item_at_pos(const Point2 &p_pos,Node* p_node,const Matrix32& p_parent_xform,const Matrix32& p_canvas_xform); + void _find_canvas_items_at_pos(const Point2 &p_pos,Node* p_node,const Matrix32& p_parent_xform,const Matrix32& p_canvas_xform, Vector<_SelectResult> &r_items); void _find_canvas_items_at_rect(const Rect2& p_rect,Node* p_node,const Matrix32& p_parent_xform,const Matrix32& p_canvas_xform,List<CanvasItem*> *r_items); + bool _select(CanvasItem *item, Point2 p_click_pos, bool p_append, bool p_drag=true); + ConfirmationDialog *snap_dialog; AcceptDialog *value_dialog; @@ -286,11 +309,13 @@ class CanvasItemEditor : public VBoxContainer { CanvasItem *ref_item; + void _edit_set_pivot(const Vector2& mouse_pos); void _add_canvas_item(CanvasItem *p_canvas_item); void _remove_canvas_item(CanvasItem *p_canvas_item); void _clear_canvas_items(); void _visibility_changed(ObjectID p_canvas_item); void _key_move(const Vector2& p_dir, bool p_snap, KeyMoveMODE p_move_mode); + void _list_select(const InputEventMouseButton& b); DragType _find_drag_type(const Matrix32& p_xform, const Rect2& p_local_rect, const Point2& p_click, Vector2& r_point); @@ -304,6 +329,9 @@ class CanvasItemEditor : public VBoxContainer { void _append_canvas_item(CanvasItem *p_item); void _dialog_value_changed(double); void _snap_changed(); + void _selection_result_pressed(int); + void _selection_menu_hide(); + UndoRedo *undo_redo; Point2 _find_topleftmost_point(); diff --git a/tools/editor/plugins/collision_polygon_editor_plugin.cpp b/tools/editor/plugins/collision_polygon_editor_plugin.cpp index 381cfd74ab..d4198f3166 100644 --- a/tools/editor/plugins/collision_polygon_editor_plugin.cpp +++ b/tools/editor/plugins/collision_polygon_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -113,6 +113,7 @@ bool CollisionPolygonEditor::forward_spatial_input_event(Camera* p_camera,const return false; Transform gt = node->get_global_transform(); + Transform gi = gt.affine_inverse(); float depth = node->get_depth()*0.5; Vector3 n = gt.basis.get_axis(2).normalized(); Plane p(gt.origin+n*depth,n); @@ -135,6 +136,8 @@ bool CollisionPolygonEditor::forward_spatial_input_event(Camera* p_camera,const if (!p.intersects_ray(ray_from,ray_dir,&spoint)) break; + spoint = gi.xform(spoint); + Vector2 cpoint(spoint.x,spoint.y); cpoint=CanvasItemEditor::get_singleton()->snap_point(cpoint); @@ -349,6 +352,8 @@ bool CollisionPolygonEditor::forward_spatial_input_event(Camera* p_camera,const if (!p.intersects_ray(ray_from,ray_dir,&spoint)) break; + spoint = gi.xform(spoint); + Vector2 cpoint(spoint.x,spoint.y); cpoint=CanvasItemEditor::get_singleton()->snap_point(cpoint); diff --git a/tools/editor/plugins/collision_polygon_editor_plugin.h b/tools/editor/plugins/collision_polygon_editor_plugin.h index 20a0b3c3f6..45e287ef00 100644 --- a/tools/editor/plugins/collision_polygon_editor_plugin.h +++ b/tools/editor/plugins/collision_polygon_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/collision_shape_2d_editor_plugin.cpp b/tools/editor/plugins/collision_shape_2d_editor_plugin.cpp index 62cf1b4acb..7e5d52d17d 100644 --- a/tools/editor/plugins/collision_shape_2d_editor_plugin.cpp +++ b/tools/editor/plugins/collision_shape_2d_editor_plugin.cpp @@ -42,6 +42,13 @@ Variant CollisionShape2DEditor::get_handle_value(int idx) const { } break; case LINE_SHAPE: { + Ref<LineShape2D> line = node->get_shape(); + + if (idx==0) { + return line->get_d(); + } else { + return line->get_normal(); + } } break; @@ -115,6 +122,18 @@ void CollisionShape2DEditor::set_handle(int idx, Point2& p_point) { } break; case LINE_SHAPE: { + if (idx<2) { + Ref<LineShape2D> line = node->get_shape(); + + if (idx==0){ + line->set_d(p_point.length()); + }else{ + line->set_normal(p_point.normalized()); + } + + canvas_item_editor->get_viewport_control()->update(); + } + } break; @@ -200,6 +219,19 @@ void CollisionShape2DEditor::commit_handle(int idx, Variant& p_org) { } break; case LINE_SHAPE: { + Ref<LineShape2D> line = node->get_shape(); + + if (idx==0) { + undo_redo->add_do_method(line.ptr(),"set_d",line->get_d()); + undo_redo->add_do_method(c,"update"); + undo_redo->add_undo_method(line.ptr(),"set_d",p_org); + undo_redo->add_undo_method(c,"update"); + } else { + undo_redo->add_do_method(line.ptr(),"set_normal",line->get_normal()); + undo_redo->add_do_method(c,"update"); + undo_redo->add_undo_method(line.ptr(),"set_normal",p_org); + undo_redo->add_undo_method(c,"update"); + } } break; @@ -418,6 +450,14 @@ void CollisionShape2DEditor::_canvas_draw() { } break; case LINE_SHAPE: { + Ref<LineShape2D> shape = node->get_shape(); + + handles.resize(2); + handles[0] = shape->get_normal() * shape->get_d(); + handles[1] = shape->get_normal() * (shape->get_d() + 30.0); + + c->draw_texture(h,gt.xform(handles[0])-size); + c->draw_texture(h,gt.xform(handles[1])-size); } break; diff --git a/tools/editor/plugins/control_editor_plugin.cpp b/tools/editor/plugins/control_editor_plugin.cpp index 7348a69665..375622a89c 100644 --- a/tools/editor/plugins/control_editor_plugin.cpp +++ b/tools/editor/plugins/control_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/control_editor_plugin.h b/tools/editor/plugins/control_editor_plugin.h index 074298d0df..94cffc8d8d 100644 --- a/tools/editor/plugins/control_editor_plugin.h +++ b/tools/editor/plugins/control_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/cube_grid_theme_editor_plugin.cpp b/tools/editor/plugins/cube_grid_theme_editor_plugin.cpp index c118485083..c861a5841a 100644 --- a/tools/editor/plugins/cube_grid_theme_editor_plugin.cpp +++ b/tools/editor/plugins/cube_grid_theme_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/cube_grid_theme_editor_plugin.h b/tools/editor/plugins/cube_grid_theme_editor_plugin.h index 583ddf6e14..72ee171e19 100644 --- a/tools/editor/plugins/cube_grid_theme_editor_plugin.h +++ b/tools/editor/plugins/cube_grid_theme_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/editor_preview_plugins.cpp b/tools/editor/plugins/editor_preview_plugins.cpp index c2b3ecfcda..a0ce294219 100644 --- a/tools/editor/plugins/editor_preview_plugins.cpp +++ b/tools/editor/plugins/editor_preview_plugins.cpp @@ -6,6 +6,7 @@ #include "scene/resources/material.h" #include "scene/resources/sample.h" #include "scene/resources/mesh.h" +#include "scene/resources/bit_mask.h" bool EditorTexturePreviewPlugin::handles(const String& p_type) const { @@ -58,6 +59,81 @@ EditorTexturePreviewPlugin::EditorTexturePreviewPlugin() { } +//////////////////////////////////////////////////////////////////////////// + +bool EditorBitmapPreviewPlugin::handles(const String& p_type) const { + + return ObjectTypeDB::is_type(p_type,"BitMap"); +} + +Ref<Texture> EditorBitmapPreviewPlugin::generate(const RES& p_from) { + + Ref<BitMap> bm =p_from; + + if (bm->get_size()==Size2()) { + return Ref<Texture>(); + } + + DVector<uint8_t> data; + + data.resize(bm->get_size().width*bm->get_size().height); + + { + DVector<uint8_t>::Write w=data.write(); + + for(int i=0;i<bm->get_size().width;i++) { + for(int j=0;j<bm->get_size().height;j++) { + if (bm->get_bit(Point2i(i,j))) { + w[j*bm->get_size().width+i]=255; + } else { + w[j*bm->get_size().width+i]=0; + + } + } + + } + } + + + Image img(bm->get_size().width,bm->get_size().height,0,Image::FORMAT_GRAYSCALE,data); + + int thumbnail_size = EditorSettings::get_singleton()->get("file_dialog/thumbnail_size"); + if (img.is_compressed()) { + if (img.decompress()!=OK) + return Ref<Texture>(); + } else if (img.get_format()!=Image::FORMAT_RGB && img.get_format()!=Image::FORMAT_RGBA) { + img.convert(Image::FORMAT_RGBA); + } + + int width,height; + if (img.get_width() > thumbnail_size && img.get_width() >= img.get_height()) { + + width=thumbnail_size; + height = img.get_height() * thumbnail_size / img.get_width(); + } else if (img.get_height() > thumbnail_size && img.get_height() >= img.get_width()) { + + height=thumbnail_size; + width = img.get_width() * thumbnail_size / img.get_height(); + } else { + + width=img.get_width(); + height=img.get_height(); + } + + img.resize(width,height); + + Ref<ImageTexture> ptex = Ref<ImageTexture>( memnew( ImageTexture )); + + ptex->create_from_image(img,0); + return ptex; + +} + +EditorBitmapPreviewPlugin::EditorBitmapPreviewPlugin() { + + +} + /////////////////////////////////////////////////////////////////////////// @@ -491,8 +567,14 @@ Ref<Texture> EditorSamplePreviewPlugin::generate(const RES& p_from) { ima_adpcm.last_nibble++; const uint8_t *src_ptr=sdata; + int ofs = ima_adpcm.last_nibble>>1; + + if (stereo) + ofs*=2; + + nibble = (ima_adpcm.last_nibble&1)? - (src_ptr[ima_adpcm.last_nibble>>1]>>4):(src_ptr[ima_adpcm.last_nibble>>1]&0xF); + (src_ptr[ofs]>>4):(src_ptr[ofs]&0xF); step=_ima_adpcm_step_table[ima_adpcm.step_index]; ima_adpcm.step_index += _ima_adpcm_index_table[nibble]; diff --git a/tools/editor/plugins/editor_preview_plugins.h b/tools/editor/plugins/editor_preview_plugins.h index 98071e2a0e..b3bfda8045 100644 --- a/tools/editor/plugins/editor_preview_plugins.h +++ b/tools/editor/plugins/editor_preview_plugins.h @@ -13,6 +13,17 @@ public: }; +class EditorBitmapPreviewPlugin : public EditorResourcePreviewGenerator { +public: + + virtual bool handles(const String& p_type) const; + virtual Ref<Texture> generate(const RES& p_from); + + EditorBitmapPreviewPlugin(); +}; + + + class EditorPackedScenePreviewPlugin : public EditorResourcePreviewGenerator { Ref<Texture> _gen_from_imd(Ref<ResourceImportMetadata> p_imd); diff --git a/tools/editor/plugins/item_list_editor_plugin.cpp b/tools/editor/plugins/item_list_editor_plugin.cpp index fa261edea3..6f0db959ba 100644 --- a/tools/editor/plugins/item_list_editor_plugin.cpp +++ b/tools/editor/plugins/item_list_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -30,7 +30,6 @@ #include "io/resource_loader.h" - bool ItemListPlugin::_set(const StringName& p_name, const Variant& p_value) { String name = p_name; @@ -45,12 +44,10 @@ bool ItemListPlugin::_set(const StringName& p_name, const Variant& p_value) { set_item_checkable(idx,p_value); else if (what=="checked") set_item_checked(idx,p_value); - else if (what=="enabled") - set_item_enabled(idx,p_value); - else if (what=="accel") - set_item_accel(idx,p_value); else if (what=="id") set_item_id(idx,p_value); + else if (what=="enabled") + set_item_enabled(idx,p_value); else if (what=="separator") set_item_separator(idx,p_value); else @@ -60,6 +57,7 @@ bool ItemListPlugin::_set(const StringName& p_name, const Variant& p_value) { } bool ItemListPlugin::_get(const StringName& p_name,Variant &r_ret) const { + String name = p_name; int idx = name.get_slice("/",0).to_int(); String what=name.get_slice("/",1); @@ -72,12 +70,10 @@ bool ItemListPlugin::_get(const StringName& p_name,Variant &r_ret) const { r_ret=is_item_checkable(idx); else if (what=="checked") r_ret=is_item_checked(idx); - else if (what=="enabled") - r_ret=is_item_enabled(idx); - else if (what=="accel") - r_ret=get_item_accel(idx); else if (what=="id") r_ret=get_item_id(idx); + else if (what=="enabled") + r_ret=is_item_enabled(idx); else if (what=="separator") r_ret=is_item_separator(idx); else @@ -93,66 +89,119 @@ void ItemListPlugin::_get_property_list( List<PropertyInfo> *p_list) const { p_list->push_back( PropertyInfo(Variant::STRING,base+"text") ); p_list->push_back( PropertyInfo(Variant::OBJECT,base+"icon",PROPERTY_HINT_RESOURCE_TYPE,"Texture") ); - if (get_flags()&FLAG_CHECKABLE) { + int flags = get_flags(); + + if (flags&FLAG_CHECKABLE) { p_list->push_back( PropertyInfo(Variant::BOOL,base+"checkable") ); p_list->push_back( PropertyInfo(Variant::BOOL,base+"checked") ); - } - if (get_flags()&FLAG_ENABLE) { + if (flags&FLAG_ID) + p_list->push_back( PropertyInfo(Variant::INT,base+"id",PROPERTY_HINT_RANGE,"-1,4096") ); + + if (flags&FLAG_ENABLE) p_list->push_back( PropertyInfo(Variant::BOOL,base+"enabled") ); - } - if (get_flags()&FLAG_ACCEL) { + if (flags&FLAG_SEPARATOR) + p_list->push_back( PropertyInfo(Variant::BOOL,base+"separator") ); + } +} - p_list->push_back( PropertyInfo(Variant::INT,base+"accel",PROPERTY_HINT_KEY_ACCEL) ); +/////////////////////////////////////////////////////////////// +///////////////////////// PLUGINS ///////////////////////////// +/////////////////////////////////////////////////////////////// - } - if (get_flags()&FLAG_ID) { +void ItemListOptionButtonPlugin::set_object(Object *p_object) { - p_list->push_back( PropertyInfo(Variant::INT,base+"id",PROPERTY_HINT_RANGE,"-1,4096") ); + ob = p_object->cast_to<OptionButton>(); +} - } - if (get_flags()&FLAG_SEPARATOR) { +bool ItemListOptionButtonPlugin::handles(Object *p_object) const { - p_list->push_back( PropertyInfo(Variant::BOOL,base+"separator") ); + return p_object->is_type("OptionButton"); +} - } - } +int ItemListOptionButtonPlugin::get_flags() const { + + return FLAG_ICON|FLAG_ID|FLAG_ENABLE; } -void ItemListEditor::_node_removed(Node *p_node) { +void ItemListOptionButtonPlugin::add_item() { - if(p_node==item_list) { - item_list=NULL; - hide(); - dialog->hide(); - } + ob->add_item( "Item "+itos(ob->get_item_count())); + _change_notify(); +} +int ItemListOptionButtonPlugin::get_item_count() const { + return ob->get_item_count(); } -void ItemListEditor::_delete_pressed() { +void ItemListOptionButtonPlugin::erase(int p_idx) { - String p = prop_editor->get_selected_path(); + ob->remove_item(p_idx); + _change_notify(); +} - if (p.find("/")!=-1) { +ItemListOptionButtonPlugin::ItemListOptionButtonPlugin() { - if (selected_idx<0 || selected_idx>=item_plugins.size()) - return; + ob=NULL; +} - item_plugins[selected_idx]->erase(p.get_slice("/",0).to_int());; - } +/////////////////////////////////////////////////////////////// + +void ItemListPopupMenuPlugin::set_object(Object *p_object) { + if (p_object->is_type("MenuButton")) + pp = p_object->cast_to<MenuButton>()->get_popup(); + else + pp = p_object->cast_to<PopupMenu>(); } -void ItemListEditor::_add_pressed() { +bool ItemListPopupMenuPlugin::handles(Object *p_object) const { - if (selected_idx<0 || selected_idx>=item_plugins.size()) - return; + return p_object->is_type("PopupMenu") || p_object->is_type("MenuButton"); +} - item_plugins[selected_idx]->add_item(); +int ItemListPopupMenuPlugin::get_flags() const { + + return FLAG_ICON|FLAG_CHECKABLE|FLAG_ID|FLAG_ENABLE|FLAG_SEPARATOR; +} + +void ItemListPopupMenuPlugin::add_item() { + + pp->add_item( "Item "+itos(pp->get_item_count())); + _change_notify(); +} + +int ItemListPopupMenuPlugin::get_item_count() const { + + return pp->get_item_count(); +} + +void ItemListPopupMenuPlugin::erase(int p_idx) { + + pp->remove_item(p_idx); + _change_notify(); +} + +ItemListPopupMenuPlugin::ItemListPopupMenuPlugin() { + + pp=NULL; +} + +/////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////// + +void ItemListEditor::_node_removed(Node *p_node) { + + if(p_node==item_list) { + item_list=NULL; + hide(); + dialog->hide(); + } } void ItemListEditor::_notification(int p_notification) { @@ -160,57 +209,73 @@ void ItemListEditor::_notification(int p_notification) { if (p_notification==NOTIFICATION_ENTER_TREE) { add_button->set_icon(get_icon("Add","EditorIcons")); - del_button->set_icon(get_icon("Del","EditorIcons")); + del_button->set_icon(get_icon("Remove","EditorIcons")); } } +void ItemListEditor::_add_pressed() { -void ItemListEditor::_menu_option(int p_option) { + if (selected_idx==-1) + return; + item_plugins[selected_idx]->add_item(); +} - switch(p_option) { +void ItemListEditor::_delete_pressed() { - case MENU_EDIT_ITEMS: { + TreeItem *ti = tree->get_selected(); - dialog->popup_centered_ratio(); - } break; - } + if (!ti) + return; + + if (ti->get_parent()!=tree->get_root()) + return; + + int idx = ti->get_text(0).to_int(); + + if (selected_idx==-1) + return; + + item_plugins[selected_idx]->erase(idx); } +void ItemListEditor::_edit_items() { + + dialog->popup_centered(Vector2(300, 400)); +} void ItemListEditor::edit(Node *p_item_list) { item_list=p_item_list; + if (!item_list) { + selected_idx=-1; + property_editor->edit(NULL); + return; + } + for(int i=0;i<item_plugins.size();i++) { if (item_plugins[i]->handles(p_item_list)) { item_plugins[i]->set_object(p_item_list); - prop_editor->edit(item_plugins[i]); + property_editor->edit(item_plugins[i]); + + if (has_icon(item_list->get_type(), "EditorIcons")) + toolbar_button->set_icon(get_icon(item_list->get_type(), "EditorIcons")); + else + toolbar_button->set_icon(Ref<Texture>()); + selected_idx=i; return; } } selected_idx=-1; - - prop_editor->edit(NULL); - -} - - -void ItemListEditor::_bind_methods() { - - ObjectTypeDB::bind_method("_menu_option",&ItemListEditor::_menu_option); - ObjectTypeDB::bind_method("_add_button",&ItemListEditor::_add_pressed); - ObjectTypeDB::bind_method("_delete_button",&ItemListEditor::_delete_pressed); - - //ObjectTypeDB::bind_method("_populate",&ItemListEditor::_populate); - + property_editor->edit(NULL); } bool ItemListEditor::handles(Object *p_object) const { - return false; + for(int i=0;i<item_plugins.size();i++) { if (item_plugins[i]->handles(p_object)) { return true; @@ -218,57 +283,65 @@ bool ItemListEditor::handles(Object *p_object) const { } return false; +} +void ItemListEditor::_bind_methods() { + + ObjectTypeDB::bind_method("_edit_items",&ItemListEditor::_edit_items); + ObjectTypeDB::bind_method("_add_button",&ItemListEditor::_add_pressed); + ObjectTypeDB::bind_method("_delete_button",&ItemListEditor::_delete_pressed); } + ItemListEditor::ItemListEditor() { selected_idx=-1; - options = memnew( MenuButton ); - add_child(options); - options->set_area_as_parent_rect(); - options->set_text("Items"); - options->get_popup()->add_item("Edit Items",MENU_EDIT_ITEMS); - //options->get_popup()->add_item("Clear",MENU_CLEAR); + add_child( memnew( VSeparator ) ); - options->get_popup()->connect("item_pressed", this,"_menu_option"); + toolbar_button = memnew( ToolButton ); + toolbar_button->set_text("Items"); + add_child(toolbar_button); + toolbar_button->connect("pressed",this,"_edit_items"); dialog = memnew( AcceptDialog ); + dialog->set_title("Item List Editor"); add_child( dialog ); - + VBoxContainer *vbc = memnew( VBoxContainer ); + dialog->add_child(vbc); + dialog->set_child_rect(vbc); HBoxContainer *hbc = memnew( HBoxContainer ); - - dialog->add_child(hbc); - dialog->set_child_rect(hbc); - - prop_editor = memnew( PropertyEditor ); - - hbc->add_child(prop_editor); - prop_editor->set_h_size_flags(SIZE_EXPAND_FILL); - - VBoxContainer *vbc = memnew( VBoxContainer ); - hbc->add_child(vbc); + hbc->set_h_size_flags(SIZE_EXPAND_FILL); + vbc->add_child(hbc); add_button = memnew( Button ); - //add_button->set_text("Add"); + add_button->set_text("Add"); + hbc->add_child(add_button); add_button->connect("pressed",this,"_add_button"); - vbc->add_child(add_button); + + hbc->add_spacer(); del_button = memnew( Button ); - //del_button->set_text("Del"); + del_button->set_text("Delete"); + hbc->add_child(del_button); del_button->connect("pressed",this,"_delete_button"); - vbc->add_child(del_button); - dialog->set_title("Item List"); - prop_editor->hide_top_label(); + property_editor = memnew( PropertyEditor ); + property_editor->hide_top_label(); + property_editor->set_subsection_selectable(true); + vbc->add_child(property_editor); + property_editor->set_v_size_flags(SIZE_EXPAND_FILL); + tree = property_editor->get_scene_tree(); +} +ItemListEditor::~ItemListEditor() { + for(int i=0;i<item_plugins.size();i++) + memdelete( item_plugins[i] ); } - void ItemListEditorPlugin::edit(Object *p_object) { item_list_editor->edit(p_object->cast_to<Node>()); @@ -288,127 +361,19 @@ void ItemListEditorPlugin::make_visible(bool p_visible) { item_list_editor->hide(); item_list_editor->edit(NULL); } - -} - - -ItemListEditor::~ItemListEditor() { - - for(int i=0;i<item_plugins.size();i++) - memdelete( item_plugins[i] ); } -///////////////////////// PLUGINS ///////////////////////////// -///////////////////////// PLUGINS ///////////////////////////// -///////////////////////// PLUGINS ///////////////////////////// -///////////////////////// PLUGINS ///////////////////////////// -///////////////////////// PLUGINS ///////////////////////////// - - -class ItemListOptionButtonPlugin : public ItemListPlugin { - - OBJ_TYPE(ItemListOptionButtonPlugin,ItemListPlugin); - - OptionButton *ob; -public: - - virtual void set_object(Object *p_object) { ob = p_object->cast_to<OptionButton>(); } - - virtual bool handles(Object *p_object) const { return p_object->cast_to<OptionButton>()!=NULL; } - - virtual int get_flags() const { return FLAG_ICON|FLAG_ID|FLAG_ENABLE; } - - virtual void set_item_text(int p_idx,const String& p_text){ ob->set_item_text(p_idx,p_text);} - virtual void set_item_icon(int p_idx,const Ref<Texture>& p_tex){ ob->set_item_icon(p_idx,p_tex);} - virtual void set_item_enabled(int p_idx,int p_enabled){ ob->set_item_disabled(p_idx,!p_enabled);} - virtual void set_item_id(int p_idx,int p_id){ ob->set_item_ID(p_idx,p_id);} - - - virtual String get_item_text(int p_idx) const{ return ob->get_item_text(p_idx); }; - virtual Ref<Texture> get_item_icon(int p_idx) const{ return ob->get_item_icon(p_idx); }; - virtual bool is_item_enabled(int p_idx) const{ return !ob->is_item_disabled(p_idx); }; - virtual int get_item_id(int p_idx) const{ return ob->get_item_ID(p_idx); }; - - virtual void add_item() { ob->add_item( "New Item "+itos(ob->get_item_count())); _change_notify();} - virtual int get_item_count() const { return ob->get_item_count(); } - virtual void erase(int p_idx) { ob->remove_item(p_idx); _change_notify();} - - - ItemListOptionButtonPlugin() { ob=NULL; } -}; - -class ItemListPopupMenuPlugin : public ItemListPlugin { - - OBJ_TYPE(ItemListPopupMenuPlugin,ItemListPlugin); - - PopupMenu *pp; -public: - - virtual void set_object(Object *p_object) { - if (p_object->cast_to<MenuButton>()) - pp = p_object->cast_to<MenuButton>()->get_popup(); - else - pp = p_object->cast_to<PopupMenu>(); - } - - virtual bool handles(Object *p_object) const { return p_object->cast_to<PopupMenu>()!=NULL || p_object->cast_to<MenuButton>()!=NULL; } - - virtual int get_flags() const { return FLAG_ICON|FLAG_ID|FLAG_ENABLE|FLAG_CHECKABLE|FLAG_SEPARATOR|FLAG_ACCEL; } - - virtual void set_item_text(int p_idx,const String& p_text){ pp->set_item_text(p_idx,p_text); } - virtual void set_item_icon(int p_idx,const Ref<Texture>& p_tex){ pp->set_item_icon(p_idx,p_tex);} - virtual void set_item_checkable(int p_idx,bool p_check){ pp->set_item_as_checkable(p_idx,p_check);} - virtual void set_item_checked(int p_idx,bool p_checked){ pp->set_item_checked(p_idx,p_checked);} - virtual void set_item_accel(int p_idx,int p_accel){ pp->set_item_accelerator(p_idx,p_accel);} - virtual void set_item_enabled(int p_idx,int p_enabled){ pp->set_item_disabled(p_idx,!p_enabled);} - virtual void set_item_id(int p_idx,int p_id){ pp->set_item_ID(p_idx,p_idx);} - virtual void set_item_separator(int p_idx,bool p_separator){ pp->set_item_as_separator(p_idx,p_separator);} - - - virtual String get_item_text(int p_idx) const{ return pp->get_item_text(p_idx); }; - virtual Ref<Texture> get_item_icon(int p_idx) const{ return pp->get_item_icon(p_idx); }; - virtual bool is_item_checkable(int p_idx) const{ return pp->is_item_checkable(p_idx); }; - virtual bool is_item_checked(int p_idx) const{ return pp->is_item_checked(p_idx); }; - virtual int get_item_accel(int p_idx) const{ return pp->get_item_accelerator(p_idx); }; - virtual bool is_item_enabled(int p_idx) const{ return !pp->is_item_disabled(p_idx); }; - virtual int get_item_id(int p_idx) const{ return pp->get_item_ID(p_idx); }; - virtual bool is_item_separator(int p_idx) const{ return pp->is_item_separator(p_idx); }; - - - - virtual void add_item() { pp->add_item( "New Item "+itos(pp->get_item_count())); _change_notify();} - virtual int get_item_count() const { return pp->get_item_count(); } - virtual void erase(int p_idx) { pp->remove_item(p_idx); _change_notify();} - - - ItemListPopupMenuPlugin() { pp=NULL; } -}; - - - - - - ItemListEditorPlugin::ItemListEditorPlugin(EditorNode *p_node) { editor=p_node; item_list_editor = memnew( ItemListEditor ); - editor->get_viewport()->add_child(item_list_editor); - -// item_list_editor->set_anchor(MARGIN_LEFT,Control::ANCHOR_END); -// item_list_editor->set_anchor(MARGIN_RIGHT,Control::ANCHOR_END); - item_list_editor->set_margin(MARGIN_LEFT,180); - item_list_editor->set_margin(MARGIN_RIGHT,230); - item_list_editor->set_margin(MARGIN_TOP,0); - item_list_editor->set_margin(MARGIN_BOTTOM,10); - + CanvasItemEditor::get_singleton()->add_control_to_menu_panel(item_list_editor); item_list_editor->hide(); - item_list_editor->add_plugin( memnew( ItemListOptionButtonPlugin) ); - item_list_editor->add_plugin( memnew( ItemListPopupMenuPlugin) ); + item_list_editor->add_plugin( memnew( ItemListOptionButtonPlugin ) ); + item_list_editor->add_plugin( memnew( ItemListPopupMenuPlugin ) ); } - ItemListEditorPlugin::~ItemListEditorPlugin() { } diff --git a/tools/editor/plugins/item_list_editor_plugin.h b/tools/editor/plugins/item_list_editor_plugin.h index 351dbb800d..95d316b199 100644 --- a/tools/editor/plugins/item_list_editor_plugin.h +++ b/tools/editor/plugins/item_list_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -31,10 +31,11 @@ #include "tools/editor/editor_plugin.h" #include "tools/editor/editor_node.h" +#include "canvas_item_editor_plugin.h" + #include "scene/gui/option_button.h" #include "scene/gui/menu_button.h" #include "scene/gui/popup_menu.h" -#include "scene/gui/spin_box.h" /** @author Juan Linietsky <reduzio@gmail.com> @@ -51,43 +52,42 @@ protected: bool _get(const StringName& p_name,Variant &r_ret) const; void _get_property_list( List<PropertyInfo> *p_list) const; - public: enum Flags { FLAG_ICON=1, FLAG_CHECKABLE=2, - FLAG_ACCEL=4, - FLAG_ID=8, - FLAG_ENABLE=16, - FLAG_SEPARATOR=32 + FLAG_ID=4, + FLAG_ENABLE=8, + FLAG_SEPARATOR=16 }; virtual void set_object(Object *p_object)=0; - virtual bool handles(Object *p_object) const=0; virtual int get_flags() const=0; - virtual void set_item_text(int p_idx,const String& p_text){} - virtual void set_item_icon(int p_idx,const Ref<Texture>& p_tex){} - virtual void set_item_checkable(int p_idx,bool p_check){} - virtual void set_item_checked(int p_idx,bool p_checked){} - virtual void set_item_accel(int p_idx,int p_accel){} - virtual void set_item_enabled(int p_idx,int p_enabled){} - virtual void set_item_id(int p_idx,int p_id){} - virtual void set_item_separator(int p_idx,bool p_separator){} - - + virtual void set_item_text(int p_idx, const String& p_text) {} virtual String get_item_text(int p_idx) const{ return ""; }; + + virtual void set_item_icon(int p_idx, const Ref<Texture>& p_tex) {} virtual Ref<Texture> get_item_icon(int p_idx) const{ return Ref<Texture>(); }; + + virtual void set_item_checkable(int p_idx, bool p_check) {} virtual bool is_item_checkable(int p_idx) const{ return false; }; + + virtual void set_item_checked(int p_idx, bool p_checked) {} virtual bool is_item_checked(int p_idx) const{ return false; }; - virtual int get_item_accel(int p_idx) const{ return 0; }; + + virtual void set_item_enabled(int p_idx, int p_enabled) {} virtual bool is_item_enabled(int p_idx) const{ return false; }; + + virtual void set_item_id(int p_idx, int p_id) {} virtual int get_item_id(int p_idx) const{ return -1; }; - virtual bool is_item_separator(int p_idx) const{ return false; }; + + virtual void set_item_separator(int p_idx, bool p_separator) {} + virtual bool is_item_separator(int p_idx) const { return false; }; virtual void add_item()=0; virtual int get_item_count() const=0; @@ -96,41 +96,107 @@ public: ItemListPlugin() {} }; -class ItemListEditor : public Control { +/////////////////////////////////////////////////////////////// - OBJ_TYPE(ItemListEditor, Control ); +class ItemListOptionButtonPlugin : public ItemListPlugin { - Node *item_list; + OBJ_TYPE(ItemListOptionButtonPlugin,ItemListPlugin); - enum { + OptionButton *ob; +public: - MENU_EDIT_ITEMS, - MENU_CLEAR - }; + virtual void set_object(Object *p_object); + virtual bool handles(Object *p_object) const; + virtual int get_flags() const; - AcceptDialog *dialog; + virtual void set_item_text(int p_idx, const String& p_text) { ob->set_item_text(p_idx,p_text); } + virtual String get_item_text(int p_idx) const { return ob->get_item_text(p_idx); } - PropertyEditor *prop_editor; + virtual void set_item_icon(int p_idx, const Ref<Texture>& p_tex) { ob->set_item_icon(p_idx, p_tex); } + virtual Ref<Texture> get_item_icon(int p_idx) const { return ob->get_item_icon(p_idx); } - MenuButton * options; - int selected_idx; + virtual void set_item_enabled(int p_idx, int p_enabled) { ob->set_item_disabled(p_idx, !p_enabled); } + virtual bool is_item_enabled(int p_idx) const { return !ob->is_item_disabled(p_idx); } + + virtual void set_item_id(int p_idx, int p_id) { ob->set_item_ID(p_idx,p_id); } + virtual int get_item_id(int p_idx) const { return ob->get_item_ID(p_idx); } + + virtual void add_item(); + virtual int get_item_count() const; + virtual void erase(int p_idx); + + ItemListOptionButtonPlugin(); +}; + +class ItemListPopupMenuPlugin : public ItemListPlugin { + + OBJ_TYPE(ItemListPopupMenuPlugin,ItemListPlugin); + + PopupMenu *pp; +public: + + virtual void set_object(Object *p_object); + virtual bool handles(Object *p_object) const; + virtual int get_flags() const; + virtual void set_item_text(int p_idx, const String& p_text) { pp->set_item_text(p_idx,p_text); } + virtual String get_item_text(int p_idx) const { return pp->get_item_text(p_idx); } + + virtual void set_item_icon(int p_idx, const Ref<Texture>& p_tex) { pp->set_item_icon(p_idx,p_tex); } + virtual Ref<Texture> get_item_icon(int p_idx) const { return pp->get_item_icon(p_idx); } + + virtual void set_item_checkable(int p_idx, bool p_check) { pp->set_item_as_checkable(p_idx,p_check); } + virtual bool is_item_checkable(int p_idx) const { return pp->is_item_checkable(p_idx); } + + virtual void set_item_checked(int p_idx, bool p_checked) { pp->set_item_checked(p_idx,p_checked); } + virtual bool is_item_checked(int p_idx) const { return pp->is_item_checked(p_idx); } + + virtual void set_item_enabled(int p_idx, int p_enabled) { pp->set_item_disabled(p_idx,!p_enabled); } + virtual bool is_item_enabled(int p_idx) const { return !pp->is_item_disabled(p_idx); } + + virtual void set_item_id(int p_idx, int p_id) { pp->set_item_ID(p_idx,p_idx); } + virtual int get_item_id(int p_idx) const { return pp->get_item_ID(p_idx); } + + virtual void set_item_separator(int p_idx, bool p_separator) { pp->set_item_as_separator(p_idx,p_separator); } + virtual bool is_item_separator(int p_idx) const { return pp->is_item_separator(p_idx); } + + virtual void add_item(); + virtual int get_item_count() const; + virtual void erase(int p_idx); + + ItemListPopupMenuPlugin(); +}; + +/////////////////////////////////////////////////////////////// + +class ItemListEditor : public HBoxContainer { + + OBJ_TYPE(ItemListEditor,HBoxContainer); + + Node *item_list; + + ToolButton *toolbar_button; + + AcceptDialog *dialog; + PropertyEditor *property_editor; + Tree *tree; Button *add_button; Button *del_button; - -// FileDialog *emission_file_dialog; - void _menu_option(int); + int selected_idx; Vector<ItemListPlugin*> item_plugins; - void _node_removed(Node *p_node); + void _edit_items(); + void _add_pressed(); void _delete_pressed(); + + void _node_removed(Node *p_node); + protected: void _notification(int p_notification); - static void _bind_methods(); public: @@ -143,7 +209,7 @@ public: class ItemListEditorPlugin : public EditorPlugin { - OBJ_TYPE( ItemListEditorPlugin, EditorPlugin ); + OBJ_TYPE(ItemListEditorPlugin,EditorPlugin); ItemListEditor *item_list_editor; EditorNode *editor; diff --git a/tools/editor/plugins/mesh_editor_plugin.cpp b/tools/editor/plugins/mesh_editor_plugin.cpp index 13d4c8db5a..5314529a23 100644 --- a/tools/editor/plugins/mesh_editor_plugin.cpp +++ b/tools/editor/plugins/mesh_editor_plugin.cpp @@ -1,13 +1,8 @@ #include "mesh_editor_plugin.h" -#include "tools/editor/editor_plugin.h" -#include "tools/editor/editor_node.h" -#include "scene/3d/mesh_instance.h" #include "scene/3d/physics_body.h" #include "scene/3d/body_shape.h" -#include "scene/gui/spin_box.h" #include "scene/gui/box_container.h" -#include "scene/3d/mesh_instance.h" #include "scene/3d/navigation_mesh.h" #include "spatial_editor_plugin.h" @@ -38,92 +33,106 @@ void MeshInstanceEditor::_menu_option(int p_option) { } switch(p_option) { - case MENU_OPTION_CREATE_STATIC_TRIMESH_BODY: { + case MENU_OPTION_CREATE_STATIC_TRIMESH_BODY: + case MENU_OPTION_CREATE_STATIC_CONVEX_BODY: { - Ref<Shape> shape = mesh->create_trimesh_shape(); - if (shape.is_null()) - return; - StaticBody *body = memnew( StaticBody ); - CollisionShape *cshape = memnew( CollisionShape ); - cshape->set_shape(shape); - body->add_child(cshape); - Node *owner = node==get_tree()->get_edited_scene_root() ? node : node->get_owner(); + bool trimesh_shape = (p_option==MENU_OPTION_CREATE_STATIC_TRIMESH_BODY); + EditorSelection *editor_selection = EditorNode::get_singleton()->get_editor_selection(); UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); - ur->create_action("Create Static Trimesh"); - ur->add_do_method(node,"add_child",body); - ur->add_do_method(body,"set_owner",owner); - ur->add_do_method(cshape,"set_owner",owner); - ur->add_do_reference(body); - ur->add_undo_method(node,"remove_child",body); - ur->commit_action(); - } break; - case MENU_OPTION_CREATE_STATIC_CONVEX_BODY: { + List<Node*> selection = editor_selection->get_selected_node_list(); - Ref<Shape> shape = mesh->create_convex_shape(); - if (shape.is_null()) - return; - StaticBody *body = memnew( StaticBody ); - CollisionShape *cshape = memnew( CollisionShape ); - cshape->set_shape(shape); - body->add_child(cshape); - Node *owner = node==get_tree()->get_edited_scene_root() ? node : node->get_owner(); + if (selection.empty()) { + Ref<Shape> shape = trimesh_shape ? mesh->create_trimesh_shape() : mesh->create_convex_shape(); + if (shape.is_null()) + return; - UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); - ur->create_action("Create Static Trimesh"); - ur->add_do_method(node,"add_child",body); - ur->add_do_method(body,"set_owner",owner); - ur->add_do_method(cshape,"set_owner",owner); - ur->add_do_reference(body); - ur->add_undo_method(node,"remove_child",body); - ur->commit_action(); + CollisionShape *cshape = memnew( CollisionShape ); + cshape->set_shape(shape); + StaticBody *body = memnew( StaticBody ); + body->add_child(cshape); - } break; - case MENU_OPTION_CREATE_TRIMESH_COLLISION_SHAPE: { + Node *owner = node==get_tree()->get_edited_scene_root() ? node : node->get_owner(); + if (trimesh_shape) + ur->create_action("Create Static Trimesh Body"); + else + ur->create_action("Create Static Convex Body"); - if (node==get_tree()->get_edited_scene_root()) { - err_dialog->set_text("This doesn't work on scene root!"); - err_dialog->popup_centered_minsize(); + ur->add_do_method(node,"add_child",body); + ur->add_do_method(body,"set_owner",owner); + ur->add_do_method(cshape,"set_owner",owner); + ur->add_do_reference(body); + ur->add_undo_method(node,"remove_child",body); + ur->commit_action(); return; } - Ref<Shape> shape = mesh->create_trimesh_shape(); - if (shape.is_null()) - return; - CollisionShape *cshape = memnew( CollisionShape ); - cshape->set_shape(shape); - Node *owner = node->get_owner(); + if (trimesh_shape) + ur->create_action("Create Static Trimesh Body"); + else + ur->create_action("Create Static Convex Body"); + + for (List<Node*>::Element *E=selection.front();E;E=E->next()) { + + MeshInstance *instance = E->get()->cast_to<MeshInstance>(); + if (!instance) + continue; + + Ref<Mesh> m = instance->get_mesh(); + if (m.is_null()) + continue; + + Ref<Shape> shape = trimesh_shape ? m->create_trimesh_shape() : m->create_convex_shape(); + if (shape.is_null()) + continue; + + CollisionShape *cshape = memnew( CollisionShape ); + cshape->set_shape(shape); + StaticBody *body = memnew( StaticBody ); + body->add_child(cshape); + + Node *owner = instance==get_tree()->get_edited_scene_root() ? instance : instance->get_owner(); + + ur->add_do_method(instance,"add_child",body); + ur->add_do_method(body,"set_owner",owner); + ur->add_do_method(cshape,"set_owner",owner); + ur->add_do_reference(body); + ur->add_undo_method(instance,"remove_child",body); + } - UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); - ur->create_action("Create Static Trimesh"); - ur->add_do_method(node->get_parent(),"add_child",cshape); - ur->add_do_method(node->get_parent(),"move_child",cshape,node->get_index()+1); - ur->add_do_method(cshape,"set_owner",owner); - ur->add_do_reference(cshape); - ur->add_undo_method(node->get_parent(),"remove_child",cshape); ur->commit_action(); } break; - case MENU_OPTION_CREATE_CONVEX_COLLISION_SHAPE: { + case MENU_OPTION_CREATE_TRIMESH_COLLISION_SHAPE: + case MENU_OPTION_CREATE_CONVEX_COLLISION_SHAPE: { if (node==get_tree()->get_edited_scene_root()) { err_dialog->set_text("This doesn't work on scene root!"); err_dialog->popup_centered_minsize(); return; } - Ref<Shape> shape = mesh->create_convex_shape(); + + bool trimesh_shape = (p_option==MENU_OPTION_CREATE_TRIMESH_COLLISION_SHAPE); + + Ref<Shape> shape = trimesh_shape ? mesh->create_trimesh_shape() : mesh->create_convex_shape(); if (shape.is_null()) return; + CollisionShape *cshape = memnew( CollisionShape ); cshape->set_shape(shape); Node *owner = node->get_owner(); UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); - ur->create_action("Create Static Trimesh"); + + if (trimesh_shape) + ur->create_action("Create Trimesh Shape"); + else + ur->create_action("Create Convex Shape"); + ur->add_do_method(node->get_parent(),"add_child",cshape); ur->add_do_method(node->get_parent(),"move_child",cshape,node->get_index()+1); ur->add_do_method(cshape,"set_owner",owner); @@ -132,10 +141,8 @@ void MeshInstanceEditor::_menu_option(int p_option) { ur->commit_action(); } break; - case MENU_OPTION_CREATE_NAVMESH: { - - + case MENU_OPTION_CREATE_NAVMESH: { Ref<NavigationMesh> nmesh = memnew( NavigationMesh ); @@ -158,9 +165,10 @@ void MeshInstanceEditor::_menu_option(int p_option) { ur->add_undo_method(node,"remove_child",nmi); ur->commit_action(); } break; + case MENU_OPTION_CREATE_OUTLINE_MESH: { - outline_dialog->popup_centered_minsize(); + outline_dialog->popup_centered(Vector2(200, 90)); } break; } @@ -212,7 +220,6 @@ MeshInstanceEditor::MeshInstanceEditor() { options = memnew( MenuButton ); - //add_child(options); SpatialEditor::get_singleton()->add_control_to_menu_panel(options); options->set_text("Mesh"); @@ -231,14 +238,20 @@ MeshInstanceEditor::MeshInstanceEditor() { options->get_popup()->connect("item_pressed", this,"_menu_option"); outline_dialog = memnew( ConfirmationDialog ); - outline_dialog->set_title("Outline Size: "); + outline_dialog->set_title("Create Outline Mesh"); + outline_dialog->get_ok()->set_text("Create"); + + VBoxContainer *outline_dialog_vbc = memnew( VBoxContainer ); + outline_dialog->add_child(outline_dialog_vbc); + outline_dialog->set_child_rect(outline_dialog_vbc); + outline_size = memnew( SpinBox ); outline_size->set_min(0.001); outline_size->set_max(1024); outline_size->set_step(0.001); outline_size->set_val(0.05); - outline_dialog->add_child(outline_size); - outline_dialog->set_child_rect(outline_size); + outline_dialog_vbc->add_margin_child("Outline Size:",outline_size); + add_child(outline_dialog); outline_dialog->connect("confirmed",this,"_create_outline_mesh"); diff --git a/tools/editor/plugins/mesh_editor_plugin.h b/tools/editor/plugins/mesh_editor_plugin.h index e502b5dc2b..6b3e23f31f 100644 --- a/tools/editor/plugins/mesh_editor_plugin.h +++ b/tools/editor/plugins/mesh_editor_plugin.h @@ -23,24 +23,19 @@ class MeshInstanceEditor : public Node { MENU_OPTION_CREATE_OUTLINE_MESH, }; + MeshInstance *node; + + MenuButton *options; + ConfirmationDialog *outline_dialog; SpinBox *outline_size; AcceptDialog *err_dialog; - - Panel *panel; - MeshInstance *node; - - LineEdit *surface_source; - LineEdit *mesh_source; - - void _menu_option(int p_option); void _create_outline_mesh(); friend class MeshInstanceEditorPlugin; - MenuButton * options; protected: void _node_removed(Node *p_node); diff --git a/tools/editor/plugins/multimesh_editor_plugin.cpp b/tools/editor/plugins/multimesh_editor_plugin.cpp index 3c88b1d3a8..3f63ef706b 100644 --- a/tools/editor/plugins/multimesh_editor_plugin.cpp +++ b/tools/editor/plugins/multimesh_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -289,7 +289,7 @@ void MultiMeshEditor::_menu_option(int p_option) { _last_pp_node=node; } - populate_dialog->popup_centered(Size2(250,395)); + populate_dialog->popup_centered(Size2(250,380)); } break; } @@ -325,10 +325,8 @@ MultiMeshEditor::MultiMeshEditor() { options = memnew( MenuButton ); - //add_child(options); SpatialEditor::get_singleton()->add_control_to_menu_panel(options); - options->set_area_as_parent_rect(); - + options->set_text("MultiMesh"); options->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("MultiMeshInstance","EditorIcons")); @@ -373,12 +371,12 @@ MultiMeshEditor::MultiMeshEditor() { populate_axis->select(2); vbc->add_margin_child("Mesh Up Axis:",populate_axis); - populate_rotate_random = memnew( HScrollBar ); + populate_rotate_random = memnew( HSlider ); populate_rotate_random->set_max(1); populate_rotate_random->set_step(0.01); vbc->add_margin_child("Random Rotation:",populate_rotate_random); - populate_tilt_random = memnew( HScrollBar ); + populate_tilt_random = memnew( HSlider ); populate_tilt_random->set_max(1); populate_tilt_random->set_step(0.01); vbc->add_margin_child("Random Tilt:",populate_tilt_random); @@ -416,8 +414,7 @@ MultiMeshEditor::MultiMeshEditor() { std->connect("selected",this,"_browsed"); _last_pp_node=NULL; - //options->set_anchor(MARGIN_LEFT,Control::ANCHOR_END); - //options->set_anchor(MARGIN_RIGHT,Control::ANCHOR_END); + err_dialog = memnew( AcceptDialog ); add_child(err_dialog); } @@ -451,13 +448,6 @@ MultiMeshEditorPlugin::MultiMeshEditorPlugin(EditorNode *p_node) { multimesh_editor = memnew( MultiMeshEditor ); editor->get_viewport()->add_child(multimesh_editor); -// multimesh_editor->set_anchor(MARGIN_LEFT,Control::ANCHOR_END); -// multimesh_editor->set_anchor(MARGIN_RIGHT,Control::ANCHOR_END); - multimesh_editor->set_margin(MARGIN_LEFT,253); - multimesh_editor->set_margin(MARGIN_RIGHT,310); - multimesh_editor->set_margin(MARGIN_TOP,0); - multimesh_editor->set_margin(MARGIN_BOTTOM,10); - multimesh_editor->options->hide(); } diff --git a/tools/editor/plugins/multimesh_editor_plugin.h b/tools/editor/plugins/multimesh_editor_plugin.h index 4f0c0d008b..245da1eeb7 100644 --- a/tools/editor/plugins/multimesh_editor_plugin.h +++ b/tools/editor/plugins/multimesh_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -42,10 +42,10 @@ class MultiMeshEditor : public Control { OBJ_TYPE(MultiMeshEditor, Control ); - friend class MultiMeshEditorPlugin; +friend class MultiMeshEditorPlugin; AcceptDialog *err_dialog; - MenuButton * options; + MenuButton * options; MultiMeshInstance *_last_pp_node; bool browsing_source; @@ -59,8 +59,8 @@ class MultiMeshEditor : public Control { ConfirmationDialog *populate_dialog; OptionButton *populate_axis; - HScrollBar *populate_rotate_random; - HScrollBar *populate_tilt_random; + HSlider *populate_rotate_random; + HSlider *populate_tilt_random; SpinBox *populate_scale_random; SpinBox *populate_scale; SpinBox *populate_amount; diff --git a/tools/editor/plugins/particles_2d_editor_plugin.cpp b/tools/editor/plugins/particles_2d_editor_plugin.cpp index dadfa8bfdc..2488c4cdd9 100644 --- a/tools/editor/plugins/particles_2d_editor_plugin.cpp +++ b/tools/editor/plugins/particles_2d_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/particles_2d_editor_plugin.h b/tools/editor/plugins/particles_2d_editor_plugin.h index dba0bb4dae..f70a0e7b76 100644 --- a/tools/editor/plugins/particles_2d_editor_plugin.h +++ b/tools/editor/plugins/particles_2d_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/particles_editor_plugin.cpp b/tools/editor/plugins/particles_editor_plugin.cpp index 5c84d9a86a..2df6d3ea90 100644 --- a/tools/editor/plugins/particles_editor_plugin.cpp +++ b/tools/editor/plugins/particles_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/particles_editor_plugin.h b/tools/editor/plugins/particles_editor_plugin.h index 92756af1f6..ff80bffc29 100644 --- a/tools/editor/plugins/particles_editor_plugin.h +++ b/tools/editor/plugins/particles_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/path_2d_editor_plugin.cpp b/tools/editor/plugins/path_2d_editor_plugin.cpp index d037adc555..509edbe5f8 100644 --- a/tools/editor/plugins/path_2d_editor_plugin.cpp +++ b/tools/editor/plugins/path_2d_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -534,6 +534,7 @@ void Path2DEditor::edit(Node *p_path2d) { if (!node->is_connected("visibility_changed", this, "_node_visibility_changed")) node->connect("visibility_changed", this, "_node_visibility_changed"); + } else { if (canvas_item_editor->get_viewport_control()->is_connected("draw",this,"_canvas_draw")) @@ -614,6 +615,7 @@ Path2DEditor::Path2DEditor(EditorNode *p_editor) { editor=p_editor; undo_redo = editor->get_undo_redo(); + mode=MODE_EDIT; action=ACTION_NONE; #if 0 diff --git a/tools/editor/plugins/path_2d_editor_plugin.h b/tools/editor/plugins/path_2d_editor_plugin.h index 9f15c0669f..973c17464e 100644 --- a/tools/editor/plugins/path_2d_editor_plugin.h +++ b/tools/editor/plugins/path_2d_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/path_editor_plugin.cpp b/tools/editor/plugins/path_editor_plugin.cpp index f4bdf50fe9..b99e632604 100644 --- a/tools/editor/plugins/path_editor_plugin.cpp +++ b/tools/editor/plugins/path_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/path_editor_plugin.h b/tools/editor/plugins/path_editor_plugin.h index fcd4241e59..18bad23bd1 100644 --- a/tools/editor/plugins/path_editor_plugin.h +++ b/tools/editor/plugins/path_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/polygon_2d_editor_plugin.cpp b/tools/editor/plugins/polygon_2d_editor_plugin.cpp index 3029dcf2ab..3e9c58d604 100644 --- a/tools/editor/plugins/polygon_2d_editor_plugin.cpp +++ b/tools/editor/plugins/polygon_2d_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -54,6 +54,8 @@ void Polygon2DEditor::_notification(int p_what) { b_snap_enable->set_icon( get_icon("Snap", "EditorIcons")); uv_icon_zoom->set_texture( get_icon("Zoom", "EditorIcons")); + get_tree()->connect("node_removed", this, "_node_removed"); + } break; case NOTIFICATION_FIXED_PROCESS: { @@ -65,8 +67,10 @@ void Polygon2DEditor::_notification(int p_what) { void Polygon2DEditor::_node_removed(Node *p_node) { if(p_node==node) { - node=NULL; + edit(NULL); hide(); + + canvas_item_editor->get_viewport_control()->update(); } } @@ -751,22 +755,18 @@ void Polygon2DEditor::edit(Node *p_collision_polygon) { canvas_item_editor=CanvasItemEditor::get_singleton(); } - if (p_collision_polygon) { node=p_collision_polygon->cast_to<Polygon2D>(); if (!canvas_item_editor->get_viewport_control()->is_connected("draw",this,"_canvas_draw")) canvas_item_editor->get_viewport_control()->connect("draw",this,"_canvas_draw"); - node->connect("exit_tree",this,"_node_removed",varray(),CONNECT_ONESHOT); + wip.clear(); wip_active=false; edited_point=-1; } else { - if (node) - node->disconnect("exit_tree",this,"_node_removed"); - node=NULL; if (canvas_item_editor->get_viewport_control()->is_connected("draw",this,"_canvas_draw")) diff --git a/tools/editor/plugins/resource_preloader_editor_plugin.cpp b/tools/editor/plugins/resource_preloader_editor_plugin.cpp index 9cd20ac53a..403a919f5d 100644 --- a/tools/editor/plugins/resource_preloader_editor_plugin.cpp +++ b/tools/editor/plugins/resource_preloader_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/resource_preloader_editor_plugin.h b/tools/editor/plugins/resource_preloader_editor_plugin.h index 88272bc603..49ef86b4c2 100644 --- a/tools/editor/plugins/resource_preloader_editor_plugin.h +++ b/tools/editor/plugins/resource_preloader_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/rich_text_editor_plugin.cpp b/tools/editor/plugins/rich_text_editor_plugin.cpp index a0daad854f..08374d6624 100644 --- a/tools/editor/plugins/rich_text_editor_plugin.cpp +++ b/tools/editor/plugins/rich_text_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/rich_text_editor_plugin.h b/tools/editor/plugins/rich_text_editor_plugin.h index 478dc0d308..ae1d04be01 100644 --- a/tools/editor/plugins/rich_text_editor_plugin.h +++ b/tools/editor/plugins/rich_text_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/sample_editor_plugin.cpp b/tools/editor/plugins/sample_editor_plugin.cpp index 31fa7246ae..ffa39bd010 100644 --- a/tools/editor/plugins/sample_editor_plugin.cpp +++ b/tools/editor/plugins/sample_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -156,8 +156,14 @@ void SampleEditor::generate_preview_texture(const Ref<Sample>& p_sample,Ref<Imag ima_adpcm.last_nibble++; const uint8_t *src_ptr=sdata; + int ofs = ima_adpcm.last_nibble>>1; + + if (stereo) + ofs*=2; + nibble = (ima_adpcm.last_nibble&1)? - (src_ptr[ima_adpcm.last_nibble>>1]>>4):(src_ptr[ima_adpcm.last_nibble>>1]&0xF); + (src_ptr[ofs]>>4):(src_ptr[ofs]&0xF); + step=_ima_adpcm_step_table[ima_adpcm.step_index]; ima_adpcm.step_index += _ima_adpcm_index_table[nibble]; diff --git a/tools/editor/plugins/sample_editor_plugin.h b/tools/editor/plugins/sample_editor_plugin.h index e615667914..22dc75b53b 100644 --- a/tools/editor/plugins/sample_editor_plugin.h +++ b/tools/editor/plugins/sample_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/sample_library_editor_plugin.cpp b/tools/editor/plugins/sample_library_editor_plugin.cpp index cf9a6c41a4..493ae405ba 100644 --- a/tools/editor/plugins/sample_library_editor_plugin.cpp +++ b/tools/editor/plugins/sample_library_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -49,9 +49,13 @@ void SampleLibraryEditor::_notification(int p_what) { if (p_what==NOTIFICATION_ENTER_TREE) { play->set_icon( get_icon("Play","EditorIcons") ); + play->set_tooltip("Play Sample"); stop->set_icon( get_icon("Stop","EditorIcons") ); + stop->set_tooltip("Stop Sample"); load->set_icon( get_icon("Folder","EditorIcons") ); + load->set_tooltip("Open Sample File(s)"); _delete->set_icon( get_icon("Del","EditorIcons") ); + _delete->set_tooltip("Remove Sample"); } if (p_what==NOTIFICATION_READY) { diff --git a/tools/editor/plugins/sample_library_editor_plugin.h b/tools/editor/plugins/sample_library_editor_plugin.h index 2770ca2d9a..6627d8d6de 100644 --- a/tools/editor/plugins/sample_library_editor_plugin.h +++ b/tools/editor/plugins/sample_library_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/sample_player_editor_plugin.cpp b/tools/editor/plugins/sample_player_editor_plugin.cpp index f1c7ca8c98..3085ad87d8 100644 --- a/tools/editor/plugins/sample_player_editor_plugin.cpp +++ b/tools/editor/plugins/sample_player_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/sample_player_editor_plugin.h b/tools/editor/plugins/sample_player_editor_plugin.h index cdd1a99c17..013b042487 100644 --- a/tools/editor/plugins/sample_player_editor_plugin.h +++ b/tools/editor/plugins/sample_player_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/script_editor_plugin.cpp b/tools/editor/plugins/script_editor_plugin.cpp index bd0f580a34..ded27d1fef 100644 --- a/tools/editor/plugins/script_editor_plugin.cpp +++ b/tools/editor/plugins/script_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -316,6 +316,8 @@ void ScriptTextEditor::_load_theme_settings() { get_text_edit()->add_keyword_color("Color",basetype_color); get_text_edit()->add_keyword_color("Image",basetype_color); get_text_edit()->add_keyword_color("InputEvent",basetype_color); + get_text_edit()->add_keyword_color("Rect2",basetype_color); + get_text_edit()->add_keyword_color("NodePath",basetype_color); //colorize engine types Color type_color= EDITOR_DEF("text_editor/engine_type_color",Color(0.0,0.2,0.4)); @@ -379,6 +381,8 @@ void ScriptTextEditor::reload_text() { te->set_h_scroll(h); te->set_v_scroll(v); + te->tag_saved_version(); + _line_col_changed(); } @@ -391,6 +395,12 @@ void ScriptTextEditor::_notification(int p_what) { } } + +bool ScriptTextEditor::is_unsaved() { + + return get_text_edit()->get_version()!=get_text_edit()->get_saved_version(); +} + String ScriptTextEditor::get_name() { String name; @@ -492,6 +502,59 @@ static Node* _find_node_for_script(Node* p_base, Node*p_current, const Ref<Scrip return NULL; } +static void _find_changed_scripts_for_external_editor(Node* p_base, Node*p_current, Set<Ref<Script> > &r_scripts) { + + if (p_current->get_owner()!=p_base && p_base!=p_current) + return; + Ref<Script> c = p_current->get_script(); + + if (c.is_valid()) + r_scripts.insert(c); + + for(int i=0;i<p_current->get_child_count();i++) { + _find_changed_scripts_for_external_editor(p_base,p_current->get_child(i),r_scripts); + } + +} + +void ScriptEditor::_update_modified_scripts_for_external_editor() { + + if (!bool(EditorSettings::get_singleton()->get("external_editor/use_external_editor"))) + return; + + Set<Ref<Script> > scripts; + + Node *base = get_tree()->get_edited_scene_root(); + if (base) { + _find_changed_scripts_for_external_editor(base,base,scripts); + } + + for (Set<Ref<Script> >::Element *E=scripts.front();E;E=E->next()) { + + Ref<Script> script = E->get(); + + if (script->get_path()=="" || script->get_path().find("local://")!=-1 || script->get_path().find("::")!=-1) { + + continue; //internal script, who cares, though weird + } + + uint64_t last_date = script->get_last_modified_time(); + uint64_t date = FileAccess::get_modified_time(script->get_path()); + + if (last_date!=date) { + + Ref<Script> rel_script = ResourceLoader::load(script->get_path(),script->get_type(),true); + ERR_CONTINUE(!rel_script.is_valid()); + script->set_source_code( rel_script->get_source_code() ); + script->set_last_modified_time( rel_script->get_last_modified_time() ); + script->update_exports(); + } + + } +} + + + void ScriptTextEditor::_code_complete_script(const String& p_code, List<String>* r_options) { Node *base = get_tree()->get_edited_scene_root(); @@ -543,7 +606,6 @@ void ScriptEditor::_breaked(bool p_breaked,bool p_can_debug) { void ScriptEditor::_show_debugger(bool p_show) { debug_menu->get_popup()->set_item_checked( debug_menu->get_popup()->get_item_index(DEBUG_SHOW), p_show); - } void ScriptEditor::_script_created(Ref<Script> p_script) { @@ -572,28 +634,119 @@ void ScriptEditor::_goto_script_line(REF p_script,int p_line) { } + +void ScriptEditor::_update_history_arrows() { + + script_back->set_disabled( history_pos<=0 ); + script_forward->set_disabled( history_pos>=history.size()-1 ); +} + + +void ScriptEditor::_go_to_tab(int p_idx) { + + Node *cn = tab_container->get_child(p_idx); + if (!cn) + return; + Control *c = cn->cast_to<Control>(); + if (!c) + return; + + if (history_pos>=0 && history_pos<history.size() && history[history_pos].control==tab_container->get_current_tab_control()) { + + Node *n = tab_container->get_current_tab_control(); + + if (n->cast_to<ScriptTextEditor>()) { + + history[history_pos].scroll_pos=n->cast_to<ScriptTextEditor>()->get_text_edit()->get_v_scroll(); + history[history_pos].cursor_column=n->cast_to<ScriptTextEditor>()->get_text_edit()->cursor_get_column(); + history[history_pos].cursor_row=n->cast_to<ScriptTextEditor>()->get_text_edit()->cursor_get_line(); + } + if (n->cast_to<EditorHelp>()) { + + history[history_pos].scroll_pos=n->cast_to<EditorHelp>()->get_scroll(); + } + } + + history.resize(history_pos+1); + ScriptHistory sh; + sh.control=c; + sh.scroll_pos=0; + + history.push_back(sh); + history_pos++; + + + tab_container->set_current_tab(p_idx); + + c = tab_container->get_current_tab_control(); + + if (c->cast_to<ScriptTextEditor>()) { + + script_name_label->set_text(c->cast_to<ScriptTextEditor>()->get_name()); + script_icon->set_texture(c->cast_to<ScriptTextEditor>()->get_icon()); + if (is_visible()) + c->cast_to<ScriptTextEditor>()->get_text_edit()->grab_focus(); + } + if (c->cast_to<EditorHelp>()) { + + script_name_label->set_text(c->cast_to<EditorHelp>()->get_class_name()); + script_icon->set_texture(get_icon("Help","EditorIcons")); + if (is_visible()) + c->cast_to<EditorHelp>()->set_focused(); + } + + + + c->set_meta("__editor_pass",++edit_pass); + _update_history_arrows(); + _update_script_colors(); +} + void ScriptEditor::_close_current_tab() { int selected = tab_container->get_current_tab(); if (selected<0 || selected>=tab_container->get_child_count()) return; + Node *tselected = tab_container->get_child(selected); ScriptTextEditor *current = tab_container->get_child(selected)->cast_to<ScriptTextEditor>(); - if (!current) - return; + if (current) { + apply_scripts(); + } - apply_scripts(); + //remove from history + history.resize(history_pos+1); + + for(int i=0;i<history.size();i++) { + if (history[i].control==tselected) { + history.remove(i); + i--; + history_pos--; + } + } + + if (history_pos>=history.size()) { + history_pos=history.size()-1; + } int idx = tab_container->get_current_tab(); - memdelete(current); + memdelete(tselected); if (idx>=tab_container->get_child_count()) idx=tab_container->get_child_count()-1; if (idx>=0) { + + if (history_pos>=0) { + idx = history[history_pos].control->get_index(); + } tab_container->set_current_tab(idx); + //script_list->select(idx); } + _update_history_arrows(); + + _update_script_names(); EditorNode::get_singleton()->save_layout(); @@ -658,6 +811,7 @@ void ScriptEditor::_reload_scripts(){ } disk_changed->hide(); + _update_script_names(); } @@ -700,46 +854,53 @@ bool ScriptEditor::_test_script_times_on_disk() { TreeItem *r = disk_changed_list->create_item(); disk_changed_list->set_hide_root(true); - bool all_ok=true; + bool need_ask=false; + bool need_reload=false; + bool use_autoreload=bool(EDITOR_DEF("text_editor/auto_reload_scripts_on_external_change",false)); + for(int i=0;i<tab_container->get_child_count();i++) { ScriptTextEditor *ste = tab_container->get_child(i)->cast_to<ScriptTextEditor>(); - if (!ste) - continue; + if (ste) { + Ref<Script> script = ste->get_edited_script(); - Ref<Script> script = ste->get_edited_script(); + if (script->get_path()=="" || script->get_path().find("local://")!=-1 || script->get_path().find("::")!=-1) + continue; //internal script, who cares - if (script->get_path()=="" || script->get_path().find("local://")!=-1 || script->get_path().find("::")!=-1) - continue; //internal script, who cares + uint64_t last_date = script->get_last_modified_time(); + uint64_t date = FileAccess::get_modified_time(script->get_path()); - uint64_t last_date = script->get_last_modified_time(); - uint64_t date = FileAccess::get_modified_time(script->get_path()); + //printf("last date: %lli vs date: %lli\n",last_date,date); + if (last_date!=date) { - //printf("last date: %lli vs date: %lli\n",last_date,date); - if (last_date!=date) { + TreeItem *ti = disk_changed_list->create_item(r); + ti->set_text(0,script->get_path().get_file()); - TreeItem *ti = disk_changed_list->create_item(r); - ti->set_text(0,script->get_path().get_file()); - all_ok=false; - //r->set_metadata(0,); + if (!use_autoreload || ste->is_unsaved()) { + need_ask=true; + } + need_reload=true; + //r->set_metadata(0,); + } } } - if (!all_ok) { - if (bool(EDITOR_DEF("text_editor/auto_reload_changed_scripts",false))) { + if (need_reload) { + if (!need_ask) { script_editor->_reload_scripts(); + need_reload=false; } else { disk_changed->call_deferred("popup_centered_ratio",0.5); } } - return all_ok; + return need_reload; } void ScriptEditor::swap_lines(TextEdit *tx, int line1, int line2) @@ -755,33 +916,15 @@ void ScriptEditor::swap_lines(TextEdit *tx, int line1, int line2) void ScriptEditor::_menu_option(int p_option) { - if (p_option==FILE_OPEN) { - editor->open_resource("Script"); - return; - } - int selected = tab_container->get_current_tab(); - if (selected<0 || selected>=tab_container->get_child_count()) - return; - - ScriptTextEditor *current = tab_container->get_child(selected)->cast_to<ScriptTextEditor>(); - if (!current) - return; - switch(p_option) { case FILE_NEW: { script_create_dialog->config("Node", ".gd"); script_create_dialog->popup_centered(Size2(300, 300)); } break; - case FILE_SAVE: { - if (!_test_script_times_on_disk()) - return; - editor->save_resource( current->get_edited_script() ); - - } break; - case FILE_SAVE_AS: { - - editor->save_resource_as( current->get_edited_script() ); + case FILE_OPEN: { + editor->open_resource("Script"); + return; } break; case FILE_SAVE_ALL: { @@ -806,330 +949,38 @@ void ScriptEditor::_menu_option(int p_option) { } break; - case EDIT_UNDO: { - current->get_text_edit()->undo(); - current->get_text_edit()->call_deferred("grab_focus"); - } break; - case EDIT_REDO: { - current->get_text_edit()->redo(); - current->get_text_edit()->call_deferred("grab_focus"); - } break; - case EDIT_CUT: { - - current->get_text_edit()->cut(); - current->get_text_edit()->call_deferred("grab_focus"); - } break; - case EDIT_COPY: { - current->get_text_edit()->copy(); - current->get_text_edit()->call_deferred("grab_focus"); - - } break; - case EDIT_PASTE: { - current->get_text_edit()->paste(); - current->get_text_edit()->call_deferred("grab_focus"); - - } break; - case EDIT_SELECT_ALL: { - - current->get_text_edit()->select_all(); - current->get_text_edit()->call_deferred("grab_focus"); + case SEARCH_HELP: { + help_search_dialog->popup(); } break; - case EDIT_MOVE_LINE_UP: { - - TextEdit *tx = current->get_text_edit(); - Ref<Script> scr = current->get_edited_script(); - if (scr.is_null()) - return; - - if (tx->is_selection_active()) - { - int from_line = tx->get_selection_from_line(); - int from_col = tx->get_selection_from_column(); - int to_line = tx->get_selection_to_line(); - int to_column = tx->get_selection_to_column(); - - for (int i = from_line; i <= to_line; i++) - { - int line_id = i; - int next_id = i - 1; - - if (line_id == 0 || next_id < 0) - return; - - swap_lines(tx, line_id, next_id); - } - int from_line_up = from_line > 0 ? from_line-1 : from_line; - int to_line_up = to_line > 0 ? to_line-1 : to_line; - tx->select(from_line_up, from_col, to_line_up, to_column); - } - else - { - int line_id = tx->cursor_get_line(); - int next_id = line_id - 1; - - if (line_id == 0 || next_id < 0) - return; - - swap_lines(tx, line_id, next_id); - } - tx->update(); - - } break; - case EDIT_MOVE_LINE_DOWN: { - - TextEdit *tx = current->get_text_edit(); - Ref<Script> scr = current->get_edited_script(); - if (scr.is_null()) - return; - - if (tx->is_selection_active()) - { - int from_line = tx->get_selection_from_line(); - int from_col = tx->get_selection_from_column(); - int to_line = tx->get_selection_to_line(); - int to_column = tx->get_selection_to_column(); - - for (int i = to_line; i >= from_line; i--) - { - int line_id = i; - int next_id = i + 1; - - if (line_id == tx->get_line_count()-1 || next_id > tx->get_line_count()) - return; - - swap_lines(tx, line_id, next_id); - } - int from_line_down = from_line < tx->get_line_count() ? from_line+1 : from_line; - int to_line_down = to_line < tx->get_line_count() ? to_line+1 : to_line; - tx->select(from_line_down, from_col, to_line_down, to_column); - } - else - { - int line_id = tx->cursor_get_line(); - int next_id = line_id + 1; - - if (line_id == tx->get_line_count()-1 || next_id > tx->get_line_count()) - return; - - swap_lines(tx, line_id, next_id); - } - tx->update(); - - } break; - case EDIT_INDENT_LEFT: { - - TextEdit *tx = current->get_text_edit(); - Ref<Script> scr = current->get_edited_script(); - if (scr.is_null()) - return; - - - if (tx->is_selection_active()) - { - int begin = tx->get_selection_from_line(); - int end = tx->get_selection_to_line(); - for (int i = begin; i <= end; i++) - { - String line_text = tx->get_line(i); - // begins with tab - if (line_text.begins_with("\t")) - { - line_text = line_text.substr(1, line_text.length()); - tx->set_line(i, line_text); - } - // begins with 4 spaces - else if (line_text.begins_with(" ")) - { - line_text = line_text.substr(4, line_text.length()); - tx->set_line(i, line_text); - } - } - } - else - { - int begin = tx->cursor_get_line(); - String line_text = tx->get_line(begin); - // begins with tab - if (line_text.begins_with("\t")) - { - line_text = line_text.substr(1, line_text.length()); - tx->set_line(begin, line_text); - } - // begins with 4 spaces - else if (line_text.begins_with(" ")) - { - line_text = line_text.substr(4, line_text.length()); - tx->set_line(begin, line_text); - } - } - tx->update(); - //tx->deselect(); - - } break; - case EDIT_INDENT_RIGHT: { - - TextEdit *tx = current->get_text_edit(); - Ref<Script> scr = current->get_edited_script(); - if (scr.is_null()) - return; - - if (tx->is_selection_active()) - { - int begin = tx->get_selection_from_line(); - int end = tx->get_selection_to_line(); - for (int i = begin; i <= end; i++) - { - String line_text = tx->get_line(i); - line_text = '\t' + line_text; - tx->set_line(i, line_text); - } - } - else - { - int begin = tx->cursor_get_line(); - String line_text = tx->get_line(begin); - line_text = '\t' + line_text; - tx->set_line(begin, line_text); - } - tx->update(); - //tx->deselect(); - - } break; - case EDIT_CLONE_DOWN: { - - TextEdit *tx = current->get_text_edit(); - Ref<Script> scr = current->get_edited_script(); - if (scr.is_null()) - return; - int line = tx->cursor_get_line(); - int next_line = line + 1; - - if (line == tx->get_line_count() || next_line > tx->get_line_count()) - return; - - String line_clone = tx->get_line(line); - tx->insert_at(line_clone, next_line); - tx->update(); - - } break; - case EDIT_TOGGLE_COMMENT: { - - TextEdit *tx = current->get_text_edit(); - Ref<Script> scr = current->get_edited_script(); - if (scr.is_null()) - return; - - - - if (tx->is_selection_active()) - { - int begin = tx->get_selection_from_line(); - int end = tx->get_selection_to_line(); - for (int i = begin; i <= end; i++) - { - String line_text = tx->get_line(i); - - if (line_text.begins_with("#")) - line_text = line_text.substr(1, line_text.length()); - else - line_text = "#" + line_text; - tx->set_line(i, line_text); - } - } - else - { - int begin = tx->cursor_get_line(); - String line_text = tx->get_line(begin); - - if (line_text.begins_with("#")) - line_text = line_text.substr(1, line_text.length()); - else - line_text = "#" + line_text; - tx->set_line(begin, line_text); - } - tx->update(); - //tx->deselect(); - - } break; - case EDIT_COMPLETE: { - - current->get_text_edit()->query_code_comple(); + case SEARCH_CLASSES: { - } break; - case EDIT_AUTO_INDENT: { + String current; - TextEdit *te = current->get_text_edit(); - String text = te->get_text(); - Ref<Script> scr = current->get_edited_script(); - if (scr.is_null()) - return; - int begin,end; - if (te->is_selection_active()) { - begin=te->get_selection_from_line(); - end=te->get_selection_to_line(); - } else { - begin=0; - end=te->get_line_count()-1; + if (tab_container->get_tab_count()>0) { + EditorHelp *eh = tab_container->get_child( tab_container->get_current_tab() )->cast_to<EditorHelp>(); + if (eh) { + current=eh->get_class_name(); + } } - scr->get_language()->auto_indent_code(text,begin,end); - te->set_text(text); - - - } break; - case SEARCH_FIND: { - - find_replace_dialog->set_text_edit(current->get_text_edit()); - find_replace_dialog->popup_search(); - } break; - case SEARCH_FIND_NEXT: { - - find_replace_dialog->set_text_edit(current->get_text_edit()); - find_replace_dialog->search_next(); - } break; - case SEARCH_REPLACE: { - - find_replace_dialog->set_text_edit(current->get_text_edit()); - find_replace_dialog->popup_replace(); - } break; - case SEARCH_LOCATE_FUNCTION: { - if (!current) - return; - quick_open->popup(current->get_functions()); - } break; - case SEARCH_GOTO_LINE: { + help_index->popup_centered_ratio(0.6); - goto_line_dialog->popup_find_line(current->get_text_edit()); - } break; - case DEBUG_TOGGLE_BREAKPOINT: { - int line=current->get_text_edit()->cursor_get_line(); - bool dobreak = !current->get_text_edit()->is_line_set_as_breakpoint(line); - current->get_text_edit()->set_line_as_breakpoint(line,dobreak); - get_debugger()->set_breakpoint(current->get_edited_script()->get_path(),line+1,dobreak); - } break; - case DEBUG_NEXT: { - - if (debugger) - debugger->debug_next(); + if (current!="") { + help_index->call_deferred("select_class",current); + } } break; - case DEBUG_STEP: { - - if (debugger) - debugger->debug_step(); + case SEARCH_WEBSITE: { + OS::get_singleton()->shell_open("http://www.godotengine.org/projects/godot-engine/wiki/Documentation#Tutorials"); } break; - case DEBUG_BREAK: { - if (debugger) - debugger->debug_break(); + case WINDOW_NEXT: { + _history_forward(); } break; - case DEBUG_CONTINUE: { - - if (debugger) - debugger->debug_continue(); - + case WINDOW_PREV: { + _history_back(); } break; case DEBUG_SHOW: { if (debugger) { @@ -1141,52 +992,433 @@ void ScriptEditor::_menu_option(int p_option) { debugger->show(); } } break; - case HELP_CONTEXTUAL: { - String text = current->get_text_edit()->get_selection_text(); - if (text == "") - text = current->get_text_edit()->get_word_under_cursor(); - if (text != "") - editor->emit_signal("request_help", text); - } break; - case FILE_CLOSE: { - if (current->get_text_edit()->get_version()!=current->get_text_edit()->get_saved_version()) { - erase_tab_confirm->set_text("Close and save changes?\n\""+current->get_name()+"\""); - erase_tab_confirm->popup_centered_minsize(); - } else { - _close_current_tab(); - } + case DEBUG_SHOW_KEEP_OPEN: { + bool visible = debug_menu->get_popup()->is_item_checked( debug_menu->get_popup()->get_item_index(DEBUG_SHOW_KEEP_OPEN) ); + if (debugger) + debugger->set_hide_on_stop(visible); + debug_menu->get_popup()->set_item_checked( debug_menu->get_popup()->get_item_index(DEBUG_SHOW_KEEP_OPEN), !visible); } break; - case WINDOW_MOVE_LEFT: { + } - if (tab_container->get_current_tab()>0) { - tab_container->call_deferred("set_current_tab",tab_container->get_current_tab()-1); - script_list->call_deferred("select",tab_container->get_current_tab()-1); - tab_container->move_child(current,tab_container->get_current_tab()-1); - _update_script_names(); - } - } break; - case WINDOW_MOVE_RIGHT: { - if (tab_container->get_current_tab()<tab_container->get_child_count()-1) { - tab_container->call_deferred("set_current_tab",tab_container->get_current_tab()+1); - script_list->call_deferred("select",tab_container->get_current_tab()+1); - tab_container->move_child(current,tab_container->get_current_tab()+1); - _update_script_names(); - } + int selected = tab_container->get_current_tab(); + if (selected<0 || selected>=tab_container->get_child_count()) + return; + + ScriptTextEditor *current = tab_container->get_child(selected)->cast_to<ScriptTextEditor>(); + if (current) { + + switch(p_option) { + case FILE_NEW: { + script_create_dialog->config("Node", ".gd"); + script_create_dialog->popup_centered(Size2(300, 300)); + } break; + case FILE_SAVE: { + if (!_test_script_times_on_disk()) + return; + editor->save_resource( current->get_edited_script() ); + + } break; + case FILE_SAVE_AS: { + + editor->save_resource_as( current->get_edited_script() ); + + } break; + case EDIT_UNDO: { + current->get_text_edit()->undo(); + current->get_text_edit()->call_deferred("grab_focus"); + } break; + case EDIT_REDO: { + current->get_text_edit()->redo(); + current->get_text_edit()->call_deferred("grab_focus"); + } break; + case EDIT_CUT: { + + current->get_text_edit()->cut(); + current->get_text_edit()->call_deferred("grab_focus"); + } break; + case EDIT_COPY: { + current->get_text_edit()->copy(); + current->get_text_edit()->call_deferred("grab_focus"); + + } break; + case EDIT_PASTE: { + current->get_text_edit()->paste(); + current->get_text_edit()->call_deferred("grab_focus"); + + } break; + case EDIT_SELECT_ALL: { + + current->get_text_edit()->select_all(); + current->get_text_edit()->call_deferred("grab_focus"); + + } break; + case EDIT_MOVE_LINE_UP: { + + TextEdit *tx = current->get_text_edit(); + Ref<Script> scr = current->get_edited_script(); + if (scr.is_null()) + return; + + if (tx->is_selection_active()) + { + int from_line = tx->get_selection_from_line(); + int from_col = tx->get_selection_from_column(); + int to_line = tx->get_selection_to_line(); + int to_column = tx->get_selection_to_column(); + + for (int i = from_line; i <= to_line; i++) + { + int line_id = i; + int next_id = i - 1; + + if (line_id == 0 || next_id < 0) + return; + + swap_lines(tx, line_id, next_id); + } + int from_line_up = from_line > 0 ? from_line-1 : from_line; + int to_line_up = to_line > 0 ? to_line-1 : to_line; + tx->select(from_line_up, from_col, to_line_up, to_column); + } + else + { + int line_id = tx->cursor_get_line(); + int next_id = line_id - 1; + if (line_id == 0 || next_id < 0) + return; - } break; - default: { + swap_lines(tx, line_id, next_id); + } + tx->update(); + + } break; + case EDIT_MOVE_LINE_DOWN: { + + TextEdit *tx = current->get_text_edit(); + Ref<Script> scr = current->get_edited_script(); + if (scr.is_null()) + return; + + if (tx->is_selection_active()) + { + int from_line = tx->get_selection_from_line(); + int from_col = tx->get_selection_from_column(); + int to_line = tx->get_selection_to_line(); + int to_column = tx->get_selection_to_column(); + + for (int i = to_line; i >= from_line; i--) + { + int line_id = i; + int next_id = i + 1; + + if (line_id == tx->get_line_count()-1 || next_id > tx->get_line_count()) + return; + + swap_lines(tx, line_id, next_id); + } + int from_line_down = from_line < tx->get_line_count() ? from_line+1 : from_line; + int to_line_down = to_line < tx->get_line_count() ? to_line+1 : to_line; + tx->select(from_line_down, from_col, to_line_down, to_column); + } + else + { + int line_id = tx->cursor_get_line(); + int next_id = line_id + 1; + + if (line_id == tx->get_line_count()-1 || next_id > tx->get_line_count()) + return; + + swap_lines(tx, line_id, next_id); + } + tx->update(); + + } break; + case EDIT_INDENT_LEFT: { + + TextEdit *tx = current->get_text_edit(); + Ref<Script> scr = current->get_edited_script(); + if (scr.is_null()) + return; + + + if (tx->is_selection_active()) + { + int begin = tx->get_selection_from_line(); + int end = tx->get_selection_to_line(); + for (int i = begin; i <= end; i++) + { + String line_text = tx->get_line(i); + // begins with tab + if (line_text.begins_with("\t")) + { + line_text = line_text.substr(1, line_text.length()); + tx->set_line(i, line_text); + } + // begins with 4 spaces + else if (line_text.begins_with(" ")) + { + line_text = line_text.substr(4, line_text.length()); + tx->set_line(i, line_text); + } + } + } + else + { + int begin = tx->cursor_get_line(); + String line_text = tx->get_line(begin); + // begins with tab + if (line_text.begins_with("\t")) + { + line_text = line_text.substr(1, line_text.length()); + tx->set_line(begin, line_text); + } + // begins with 4 spaces + else if (line_text.begins_with(" ")) + { + line_text = line_text.substr(4, line_text.length()); + tx->set_line(begin, line_text); + } + } + tx->update(); + //tx->deselect(); + + } break; + case EDIT_INDENT_RIGHT: { + + TextEdit *tx = current->get_text_edit(); + Ref<Script> scr = current->get_edited_script(); + if (scr.is_null()) + return; + + if (tx->is_selection_active()) + { + int begin = tx->get_selection_from_line(); + int end = tx->get_selection_to_line(); + for (int i = begin; i <= end; i++) + { + String line_text = tx->get_line(i); + line_text = '\t' + line_text; + tx->set_line(i, line_text); + } + } + else + { + int begin = tx->cursor_get_line(); + String line_text = tx->get_line(begin); + line_text = '\t' + line_text; + tx->set_line(begin, line_text); + } + tx->update(); + //tx->deselect(); + + } break; + case EDIT_CLONE_DOWN: { + + TextEdit *tx = current->get_text_edit(); + Ref<Script> scr = current->get_edited_script(); + if (scr.is_null()) + return; + int line = tx->cursor_get_line(); + int next_line = line + 1; + int column = tx->cursor_get_column(); + + if (line >= tx->get_line_count() - 1) + tx->set_line(line, tx->get_line(line) + "\n"); + + String line_clone = tx->get_line(line); + tx->insert_at(line_clone, next_line); + tx->cursor_set_column(column); + tx->update(); + + } break; + case EDIT_TOGGLE_COMMENT: { + + TextEdit *tx = current->get_text_edit(); + Ref<Script> scr = current->get_edited_script(); + if (scr.is_null()) + return; + + + + if (tx->is_selection_active()) + { + int begin = tx->get_selection_from_line(); + int end = tx->get_selection_to_line(); + for (int i = begin; i <= end; i++) + { + String line_text = tx->get_line(i); + + if (line_text.begins_with("#")) + line_text = line_text.substr(1, line_text.length()); + else + line_text = "#" + line_text; + tx->set_line(i, line_text); + } + } + else + { + int begin = tx->cursor_get_line(); + String line_text = tx->get_line(begin); + + if (line_text.begins_with("#")) + line_text = line_text.substr(1, line_text.length()); + else + line_text = "#" + line_text; + tx->set_line(begin, line_text); + } + tx->update(); + //tx->deselect(); + + } break; + case EDIT_COMPLETE: { + + current->get_text_edit()->query_code_comple(); + + } break; + case EDIT_AUTO_INDENT: { + + TextEdit *te = current->get_text_edit(); + String text = te->get_text(); + Ref<Script> scr = current->get_edited_script(); + if (scr.is_null()) + return; + int begin,end; + if (te->is_selection_active()) { + begin=te->get_selection_from_line(); + end=te->get_selection_to_line(); + } else { + begin=0; + end=te->get_line_count()-1; + } + scr->get_language()->auto_indent_code(text,begin,end); + te->set_text(text); + + + } break; + case SEARCH_FIND: { + + find_replace_dialog->set_text_edit(current->get_text_edit()); + find_replace_dialog->popup_search(); + } break; + case SEARCH_FIND_NEXT: { + + find_replace_dialog->set_text_edit(current->get_text_edit()); + find_replace_dialog->search_next(); + } break; + case SEARCH_REPLACE: { + + find_replace_dialog->set_text_edit(current->get_text_edit()); + find_replace_dialog->popup_replace(); + } break; + case SEARCH_LOCATE_FUNCTION: { + + if (!current) + return; + quick_open->popup(current->get_functions()); + } break; + case SEARCH_GOTO_LINE: { + + goto_line_dialog->popup_find_line(current->get_text_edit()); + } break; + case DEBUG_TOGGLE_BREAKPOINT: { + int line=current->get_text_edit()->cursor_get_line(); + bool dobreak = !current->get_text_edit()->is_line_set_as_breakpoint(line); + current->get_text_edit()->set_line_as_breakpoint(line,dobreak); + get_debugger()->set_breakpoint(current->get_edited_script()->get_path(),line+1,dobreak); + } break; + case DEBUG_NEXT: { + + if (debugger) + debugger->debug_next(); + } break; + case DEBUG_STEP: { + + if (debugger) + debugger->debug_step(); + + } break; + case DEBUG_BREAK: { + + if (debugger) + debugger->debug_break(); + + } break; + case DEBUG_CONTINUE: { + + if (debugger) + debugger->debug_continue(); + + } break; + case HELP_CONTEXTUAL: { + String text = current->get_text_edit()->get_selection_text(); + if (text == "") + text = current->get_text_edit()->get_word_under_cursor(); + if (text != "") + help_search_dialog->popup(text); + } break; + case FILE_CLOSE: { + if (current->get_text_edit()->get_version()!=current->get_text_edit()->get_saved_version()) { + erase_tab_confirm->set_text("Close and save changes?\n\""+current->get_name()+"\""); + erase_tab_confirm->popup_centered_minsize(); + } else { + _close_current_tab(); + } + } break; + case WINDOW_MOVE_LEFT: { + + if (tab_container->get_current_tab()>0) { + tab_container->call_deferred("set_current_tab",tab_container->get_current_tab()-1); + script_list->call_deferred("select",tab_container->get_current_tab()-1); + tab_container->move_child(current,tab_container->get_current_tab()-1); + _update_script_names(); + } + } break; + case WINDOW_MOVE_RIGHT: { + + if (tab_container->get_current_tab()<tab_container->get_child_count()-1) { + tab_container->call_deferred("set_current_tab",tab_container->get_current_tab()+1); + script_list->call_deferred("select",tab_container->get_current_tab()+1); + tab_container->move_child(current,tab_container->get_current_tab()+1); + _update_script_names(); + } - if (p_option>=WINDOW_SELECT_BASE) { - tab_container->set_current_tab(p_option-WINDOW_SELECT_BASE); - script_list->select(p_option-WINDOW_SELECT_BASE); + } break; + default: { + + if (p_option>=WINDOW_SELECT_BASE) { + + tab_container->set_current_tab(p_option-WINDOW_SELECT_BASE); + script_list->select(p_option-WINDOW_SELECT_BASE); + + } } } } + EditorHelp *help = tab_container->get_child(selected)->cast_to<EditorHelp>(); + if (help) { + + switch(p_option) { + + case SEARCH_FIND: { + help->popup_search(); + } break; + case SEARCH_FIND_NEXT: { + help->search_again(); + } break; + case FILE_CLOSE: { + _close_current_tab(); + } break; + + + } + } + + } void ScriptEditor::_tab_changed(int p_which) { @@ -1217,6 +1449,14 @@ void ScriptEditor::_notification(int p_what) { } EditorSettings::get_singleton()->connect("settings_changed",this,"_editor_settings_changed"); + help_search->set_icon(get_icon("Help","EditorIcons")); + site_search->set_icon(get_icon("Godot","EditorIcons")); + class_search->set_icon(get_icon("ClassList","EditorIcons")); + + script_forward->set_icon(get_icon("Forward","EditorIcons")); + script_back->set_icon(get_icon("Back","EditorIcons")); + + } @@ -1224,6 +1464,7 @@ void ScriptEditor::_notification(int p_what) { if (p_what==NOTIFICATION_READY) { get_tree()->connect("tree_changed",this,"_tree_changed"); + editor->connect("request_help",this,"_request_help"); } if (p_what==NOTIFICATION_EXIT_TREE) { @@ -1237,6 +1478,7 @@ void ScriptEditor::_notification(int p_what) { if (p_what==MainLoop::NOTIFICATION_WM_FOCUS_IN) { _test_script_times_on_disk(); + _update_modified_scripts_for_external_editor(); } if (p_what==NOTIFICATION_PROCESS) { @@ -1245,6 +1487,11 @@ void ScriptEditor::_notification(int p_what) { } +void ScriptEditor::edited_scene_changed() { + + _update_modified_scripts_for_external_editor(); + +} static const Node * _find_node_with_script(const Node* p_node, const RefPtr & p_script) { @@ -1346,7 +1593,7 @@ void ScriptEditor::set_state(const Dictionary& p_state) { } void ScriptEditor::clear() { - +#if 0 List<ScriptTextEditor*> stes; for(int i=0;i<tab_container->get_child_count();i++) { @@ -1371,7 +1618,7 @@ void ScriptEditor::clear() { script_list->select( script_list->find_metadata(idx) ); } - +#endif } @@ -1402,31 +1649,6 @@ void ScriptEditor::get_breakpoints(List<String> *p_breakpoints) { -void ScriptEditor::_bind_methods() { - - ObjectTypeDB::bind_method("_tab_changed",&ScriptEditor::_tab_changed); - ObjectTypeDB::bind_method("_menu_option",&ScriptEditor::_menu_option); - ObjectTypeDB::bind_method("_close_current_tab",&ScriptEditor::_close_current_tab); - ObjectTypeDB::bind_method("_editor_play",&ScriptEditor::_editor_play); - ObjectTypeDB::bind_method("_editor_pause",&ScriptEditor::_editor_pause); - ObjectTypeDB::bind_method("_editor_stop",&ScriptEditor::_editor_stop); - ObjectTypeDB::bind_method("_add_callback",&ScriptEditor::_add_callback); - ObjectTypeDB::bind_method("_reload_scripts",&ScriptEditor::_reload_scripts); - ObjectTypeDB::bind_method("_resave_scripts",&ScriptEditor::_resave_scripts); - ObjectTypeDB::bind_method("_res_saved_callback",&ScriptEditor::_res_saved_callback); - ObjectTypeDB::bind_method("_goto_script_line",&ScriptEditor::_goto_script_line); - ObjectTypeDB::bind_method("_goto_script_line2",&ScriptEditor::_goto_script_line2); - ObjectTypeDB::bind_method("_breaked",&ScriptEditor::_breaked); - ObjectTypeDB::bind_method("_show_debugger",&ScriptEditor::_show_debugger); - ObjectTypeDB::bind_method("_get_debug_tooltip",&ScriptEditor::_get_debug_tooltip); - ObjectTypeDB::bind_method("_autosave_scripts",&ScriptEditor::_autosave_scripts); - ObjectTypeDB::bind_method("_editor_settings_changed",&ScriptEditor::_editor_settings_changed); - ObjectTypeDB::bind_method("_update_script_names",&ScriptEditor::_update_script_names); - ObjectTypeDB::bind_method("_tree_changed",&ScriptEditor::_tree_changed); - ObjectTypeDB::bind_method("_script_selected",&ScriptEditor::_script_selected); - ObjectTypeDB::bind_method("_script_created",&ScriptEditor::_script_created); - ObjectTypeDB::bind_method("_script_split_dragged",&ScriptEditor::_script_split_dragged); -} void ScriptEditor::ensure_focus_current() { @@ -1448,7 +1670,8 @@ void ScriptEditor::ensure_focus_current() { void ScriptEditor::_script_selected(int p_idx) { grab_focus_block = !Input::get_singleton()->is_mouse_button_pressed(1); //amazing hack, simply amazing - tab_container->set_current_tab(script_list->get_item_metadata(p_idx)); + + _go_to_tab(script_list->get_item_metadata(p_idx)); grab_focus_block=false; } @@ -1457,16 +1680,38 @@ void ScriptEditor::ensure_select_current() { if (tab_container->get_child_count() && tab_container->get_current_tab()>=0) { - ScriptTextEditor *ste = tab_container->get_child(tab_container->get_current_tab())->cast_to<ScriptTextEditor>(); - if (!ste) - return; - Ref<Script> script = ste->get_edited_script(); + Node *current = tab_container->get_child(tab_container->get_current_tab()); + + + ScriptTextEditor *ste = current->cast_to<ScriptTextEditor>(); + if (ste) { + + Ref<Script> script = ste->get_edited_script(); + + if (!grab_focus_block && is_inside_tree()) + ste->get_text_edit()->grab_focus(); + + edit_menu->show(); + search_menu->show(); + script_search_menu->hide(); + + + } + + EditorHelp *eh = current->cast_to<EditorHelp>(); + + if (eh) { + edit_menu->hide(); + search_menu->hide(); + script_search_menu->show(); - if (!grab_focus_block && is_inside_tree()) - ste->get_text_edit()->grab_focus(); + } } + + + } void ScriptEditor::_find_scripts(Node* p_base, Node* p_current, Set<Ref<Script> > &used) { @@ -1485,6 +1730,57 @@ void ScriptEditor::_find_scripts(Node* p_base, Node* p_current, Set<Ref<Script> } +struct _ScriptEditorItemData { + + String name; + Ref<Texture> icon; + int index; + String tooltip; + bool used; + int category; + + + bool operator<(const _ScriptEditorItemData& id) const { + + return category==id.category?name.nocasecmp_to(id.name)<0:category<id.category; + } + +}; + + +void ScriptEditor::_update_script_colors() { + + bool enabled = EditorSettings::get_singleton()->get("text_editor/script_temperature_enabled"); + if (!enabled) + return; + + int hist_size = EditorSettings::get_singleton()->get("text_editor/script_temperature_history_size"); + Color hot_color=EditorSettings::get_singleton()->get("text_editor/script_temperature_hot_color"); + Color cold_color=EditorSettings::get_singleton()->get("text_editor/script_temperature_cold_color"); + + for(int i=0;i<script_list->get_item_count();i++) { + + int c = script_list->get_item_metadata(i); + Node *n = tab_container->get_child(c); + if (!n) + continue; + + script_list->set_item_custom_bg_color(i,Color(0,0,0,0)); + if (!n->has_meta("__editor_pass")) { + continue; + } + + int pass=n->get_meta("__editor_pass"); + int h = edit_pass - pass; + if (h>hist_size) { + continue; + } + float v = Math::ease((edit_pass-pass)/float(hist_size),0.4); + + + script_list->set_item_custom_bg_color(i,hot_color.linear_interpolate(cold_color,v)); + } +} void ScriptEditor::_update_script_names() { @@ -1496,31 +1792,75 @@ void ScriptEditor::_update_script_names() { } script_list->clear(); + bool split_script_help = EditorSettings::get_singleton()->get("text_editor/group_help_pages"); + + Vector<_ScriptEditorItemData> sedata; + for(int i=0;i<tab_container->get_child_count();i++) { + ScriptTextEditor *ste = tab_container->get_child(i)->cast_to<ScriptTextEditor>(); - if (!ste) - continue; + if (ste) { - String script = ste->get_name(); - Ref<Texture> icon = ste->get_icon(); - String path = ste->get_edited_script()->get_path(); - script_list->add_item(script,icon); + String name = ste->get_name(); + Ref<Texture> icon = ste->get_icon(); + String tooltip = ste->get_edited_script()->get_path(); - int index = script_list->get_item_count()-1; + _ScriptEditorItemData sd; + sd.icon=icon; + sd.name=name; + sd.tooltip=tooltip; + sd.index=i; + sd.used=used.has(ste->get_edited_script()); + sd.category=0; + + sedata.push_back(sd); + } + + EditorHelp *eh = tab_container->get_child(i)->cast_to<EditorHelp>(); + if (eh) { + + String name = eh->get_class_name(); + Ref<Texture> icon = get_icon("Help","EditorIcons"); + String tooltip = name+" Class Reference"; + + _ScriptEditorItemData sd; + sd.icon=icon; + sd.name=name; + sd.tooltip=tooltip; + sd.index=i; + sd.used=false; + sd.category=split_script_help?1:0; + sedata.push_back(sd); + + } + + } + + sedata.sort(); - script_list->set_item_tooltip(index,path); - script_list->set_item_metadata(index,i); - if (used.has(ste->get_edited_script())) { + for(int i=0;i<sedata.size();i++) { + + script_list->add_item(sedata[i].name,sedata[i].icon); + int index = script_list->get_item_count()-1; + script_list->set_item_tooltip(index,sedata[i].tooltip); + script_list->set_item_metadata(index,sedata[i].index); + if (sedata[i].used) { script_list->set_item_custom_bg_color(index,Color(88/255.0,88/255.0,60/255.0)); } - if (tab_container->get_current_tab()==index) { + if (tab_container->get_current_tab()==sedata[i].index) { script_list->select(index); + script_name_label->set_text(sedata[i].name); + script_icon->set_texture(sedata[i].icon); + } } - script_list->sort_items_by_text(); + _update_script_colors(); + + + } @@ -1531,6 +1871,8 @@ void ScriptEditor::edit(const Ref<Script>& p_script) { // see if already has it + bool open_dominant = EditorSettings::get_singleton()->get("text_editor/open_dominant_script_on_scene_change"); + if (p_script->get_path().is_resource_file() && bool(EditorSettings::get_singleton()->get("external_editor/use_external_editor"))) { String path = EditorSettings::get_singleton()->get("external_editor/exec_path"); @@ -1559,12 +1901,13 @@ void ScriptEditor::edit(const Ref<Script>& p_script) { if (ste->get_edited_script()==p_script) { - if (!EditorNode::get_singleton()->is_changing_scene()) { + if (open_dominant || !EditorNode::get_singleton()->is_changing_scene()) { if (tab_container->get_current_tab()!=i) { - tab_container->set_current_tab(i); + _go_to_tab(i); script_list->select( script_list->find_metadata(i) ); } - ste->get_text_edit()->grab_focus(); + if (is_visible()) + ste->get_text_edit()->grab_focus(); } return; } @@ -1575,8 +1918,10 @@ void ScriptEditor::edit(const Ref<Script>& p_script) { ScriptTextEditor *ste = memnew( ScriptTextEditor ); ste->set_edited_script(p_script); ste->get_text_edit()->set_tooltip_request_func(this,"_get_debug_tooltip",ste); + ste->get_text_edit()->set_auto_brace_completion(EditorSettings::get_singleton()->get("text_editor/auto_brace_complete")); tab_container->add_child(ste); - tab_container->set_current_tab(tab_container->get_tab_count()-1); + _go_to_tab(tab_container->get_tab_count()-1); + @@ -1675,7 +2020,7 @@ void ScriptEditor::_add_callback(Object *p_obj, const String& p_function, const ste->get_text_edit()->insert_text_at_cursor("\n\n"+func); } - tab_container->set_current_tab(i); + _go_to_tab(i); ste->get_text_edit()->cursor_set_line(pos); ste->get_text_edit()->cursor_set_column(1); @@ -1698,6 +2043,15 @@ void ScriptEditor::_editor_settings_changed() { autosave_timer->stop(); } + for(int i=0;i<tab_container->get_child_count();i++) { + + ScriptTextEditor *ste = tab_container->get_child(i)->cast_to<ScriptTextEditor>(); + if (!ste) + continue; + + ste->get_text_edit()->set_auto_brace_completion(EditorSettings::get_singleton()->get("text_editor/auto_brace_complete")); + } + } void ScriptEditor::_autosave_scripts() { @@ -1726,10 +2080,13 @@ void ScriptEditor::set_window_layout(Ref<ConfigFile> p_layout) { return; } - if (!p_layout->has_section_key("ScriptEditor","open_scripts")) + if (!p_layout->has_section_key("ScriptEditor","open_scripts") && !p_layout->has_section_key("ScriptEditor","open_help")) return; Array scripts = p_layout->get_value("ScriptEditor","open_scripts"); + Array helps; + if (p_layout->has_section_key("ScriptEditor","open_help")) + helps=p_layout->get_value("ScriptEditor","open_help"); restoring_layout=true; @@ -1742,6 +2099,18 @@ void ScriptEditor::set_window_layout(Ref<ConfigFile> p_layout) { } } + + for(int i=0;i<helps.size();i++) { + + String path = helps[i]; + _help_class_open(path); + } + + for(int i=0;i<tab_container->get_child_count();i++) { + tab_container->get_child(i)->set_meta("__editor_pass",Variant()); + } + + if (p_layout->has_section_key("ScriptEditor","split_offset")) { script_split->set_split_offset(p_layout->get_value("ScriptEditor","split_offset")); } @@ -1754,27 +2123,189 @@ void ScriptEditor::set_window_layout(Ref<ConfigFile> p_layout) { void ScriptEditor::get_window_layout(Ref<ConfigFile> p_layout) { Array scripts; + Array helps; for(int i=0;i<tab_container->get_child_count();i++) { ScriptTextEditor *ste = tab_container->get_child(i)->cast_to<ScriptTextEditor>(); - if (!ste) - continue; + if (ste) { - String path = ste->get_edited_script()->get_path(); - if (!path.is_resource_file()) - continue; + String path = ste->get_edited_script()->get_path(); + if (!path.is_resource_file()) + continue; + + scripts.push_back(path); + } + + EditorHelp *eh = tab_container->get_child(i)->cast_to<EditorHelp>(); + + if (eh) { + + helps.push_back(eh->get_class_name()); + } - scripts.push_back(path); } p_layout->set_value("ScriptEditor","open_scripts",scripts); + p_layout->set_value("ScriptEditor","open_help",helps); p_layout->set_value("ScriptEditor","split_offset",script_split->get_split_offset()); } +void ScriptEditor::_help_class_open(const String& p_class) { + + + for(int i=0;i<tab_container->get_child_count();i++) { + + EditorHelp *eh = tab_container->get_child(i)->cast_to<EditorHelp>(); + + if (eh && eh->get_class_name()==p_class) { + + _go_to_tab(i); + _update_script_names(); + return; + } + } + + EditorHelp * eh = memnew( EditorHelp ); + + + eh->set_name(p_class); + tab_container->add_child(eh); + _go_to_tab(tab_container->get_tab_count()-1); + eh->go_to_class(p_class,0); + eh->connect("go_to_help",this,"_help_class_goto"); + _update_script_names(); + +} + +void ScriptEditor::_help_class_goto(const String& p_desc) { + + + String cname=p_desc.get_slice(":",1); + + for(int i=0;i<tab_container->get_child_count();i++) { + + EditorHelp *eh = tab_container->get_child(i)->cast_to<EditorHelp>(); + + if (eh && eh->get_class_name()==cname) { + + _go_to_tab(i); + eh->go_to_help(p_desc); + _update_script_names(); + return; + } + } + + EditorHelp * eh = memnew( EditorHelp ); + + eh->set_name(cname); + tab_container->add_child(eh); + _go_to_tab(tab_container->get_tab_count()-1); + eh->go_to_help(p_desc); + eh->connect("go_to_help",this,"_help_class_goto"); + _update_script_names(); + +} + +void ScriptEditor::_update_history_pos(int p_new_pos) { + + Node *n = tab_container->get_current_tab_control(); + + if (n->cast_to<ScriptTextEditor>()) { + + history[history_pos].scroll_pos=n->cast_to<ScriptTextEditor>()->get_text_edit()->get_v_scroll(); + history[history_pos].cursor_column=n->cast_to<ScriptTextEditor>()->get_text_edit()->cursor_get_column(); + history[history_pos].cursor_row=n->cast_to<ScriptTextEditor>()->get_text_edit()->cursor_get_line(); + } + if (n->cast_to<EditorHelp>()) { + + history[history_pos].scroll_pos=n->cast_to<EditorHelp>()->get_scroll(); + } + + history_pos=p_new_pos; + tab_container->set_current_tab(history[history_pos].control->get_index()); + + n = history[history_pos].control; + + if (n->cast_to<ScriptTextEditor>()) { + + n->cast_to<ScriptTextEditor>()->get_text_edit()->set_v_scroll(history[history_pos].scroll_pos); + n->cast_to<ScriptTextEditor>()->get_text_edit()->cursor_set_column( history[history_pos].cursor_column ); + n->cast_to<ScriptTextEditor>()->get_text_edit()->cursor_set_line( history[history_pos].cursor_row ); + n->cast_to<ScriptTextEditor>()->get_text_edit()->grab_focus(); + } + + if (n->cast_to<EditorHelp>()) { + + n->cast_to<EditorHelp>()->set_scroll(history[history_pos].scroll_pos); + n->cast_to<EditorHelp>()->set_focused(); + } + + n->set_meta("__editor_pass",++edit_pass); + _update_script_names(); + _update_history_arrows(); + +} + +void ScriptEditor::_history_forward() { + + if (history_pos<history.size()-1) { + _update_history_pos(history_pos+1); + } +} + +void ScriptEditor::_history_back(){ + + if (history_pos>0) { + _update_history_pos(history_pos-1); + } + +} +void ScriptEditor::set_scene_root_script( Ref<Script> p_script ) { + + bool open_dominant = EditorSettings::get_singleton()->get("text_editor/open_dominant_script_on_scene_change"); + + if (bool(EditorSettings::get_singleton()->get("external_editor/use_external_editor"))) + return; + + if (open_dominant && p_script.is_valid()) { + edit(p_script); + } +} + +void ScriptEditor::_bind_methods() { + + ObjectTypeDB::bind_method("_tab_changed",&ScriptEditor::_tab_changed); + ObjectTypeDB::bind_method("_menu_option",&ScriptEditor::_menu_option); + ObjectTypeDB::bind_method("_close_current_tab",&ScriptEditor::_close_current_tab); + ObjectTypeDB::bind_method("_editor_play",&ScriptEditor::_editor_play); + ObjectTypeDB::bind_method("_editor_pause",&ScriptEditor::_editor_pause); + ObjectTypeDB::bind_method("_editor_stop",&ScriptEditor::_editor_stop); + ObjectTypeDB::bind_method("_add_callback",&ScriptEditor::_add_callback); + ObjectTypeDB::bind_method("_reload_scripts",&ScriptEditor::_reload_scripts); + ObjectTypeDB::bind_method("_resave_scripts",&ScriptEditor::_resave_scripts); + ObjectTypeDB::bind_method("_res_saved_callback",&ScriptEditor::_res_saved_callback); + ObjectTypeDB::bind_method("_goto_script_line",&ScriptEditor::_goto_script_line); + ObjectTypeDB::bind_method("_goto_script_line2",&ScriptEditor::_goto_script_line2); + ObjectTypeDB::bind_method("_breaked",&ScriptEditor::_breaked); + ObjectTypeDB::bind_method("_show_debugger",&ScriptEditor::_show_debugger); + ObjectTypeDB::bind_method("_get_debug_tooltip",&ScriptEditor::_get_debug_tooltip); + ObjectTypeDB::bind_method("_autosave_scripts",&ScriptEditor::_autosave_scripts); + ObjectTypeDB::bind_method("_editor_settings_changed",&ScriptEditor::_editor_settings_changed); + ObjectTypeDB::bind_method("_update_script_names",&ScriptEditor::_update_script_names); + ObjectTypeDB::bind_method("_tree_changed",&ScriptEditor::_tree_changed); + ObjectTypeDB::bind_method("_script_selected",&ScriptEditor::_script_selected); + ObjectTypeDB::bind_method("_script_created",&ScriptEditor::_script_created); + ObjectTypeDB::bind_method("_script_split_dragged",&ScriptEditor::_script_split_dragged); + ObjectTypeDB::bind_method("_help_class_open",&ScriptEditor::_help_class_open); + ObjectTypeDB::bind_method("_help_class_goto",&ScriptEditor::_help_class_goto); + ObjectTypeDB::bind_method("_request_help",&ScriptEditor::_help_class_open); + ObjectTypeDB::bind_method("_history_forward",&ScriptEditor::_history_forward); + ObjectTypeDB::bind_method("_history_back",&ScriptEditor::_history_back); +} ScriptEditor::ScriptEditor(EditorNode *p_editor) { @@ -1816,6 +2347,9 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) { file_menu->get_popup()->add_item("Save As..",FILE_SAVE_AS); file_menu->get_popup()->add_item("Save All",FILE_SAVE_ALL,KEY_MASK_CMD|KEY_MASK_SHIFT|KEY_S); file_menu->get_popup()->add_separator(); + file_menu->get_popup()->add_item("History Prev",WINDOW_PREV,KEY_MASK_CTRL|KEY_MASK_ALT|KEY_LEFT); + file_menu->get_popup()->add_item("History Next",WINDOW_NEXT,KEY_MASK_CTRL|KEY_MASK_ALT|KEY_RIGHT); + file_menu->get_popup()->add_separator(); file_menu->get_popup()->add_item("Close",FILE_CLOSE,KEY_MASK_CMD|KEY_W); file_menu->get_popup()->connect("item_pressed", this,"_menu_option"); @@ -1851,13 +2385,22 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) { menu_hb->add_child(search_menu); search_menu->set_text("Search"); search_menu->get_popup()->add_item("Find..",SEARCH_FIND,KEY_MASK_CMD|KEY_F); - search_menu->get_popup()->add_item("Find Next",SEARCH_FIND_NEXT,KEY_MASK_CMD|KEY_G); + search_menu->get_popup()->add_item("Find Next",SEARCH_FIND_NEXT,KEY_F3); search_menu->get_popup()->add_item("Replace..",SEARCH_REPLACE,KEY_MASK_CMD|KEY_R); search_menu->get_popup()->add_separator(); search_menu->get_popup()->add_item("Goto Function..",SEARCH_LOCATE_FUNCTION,KEY_MASK_SHIFT|KEY_MASK_CMD|KEY_F); search_menu->get_popup()->add_item("Goto Line..",SEARCH_GOTO_LINE,KEY_MASK_CMD|KEY_L); search_menu->get_popup()->connect("item_pressed", this,"_menu_option"); + script_search_menu = memnew( MenuButton ); + menu_hb->add_child(script_search_menu); + script_search_menu->set_text("Search"); + script_search_menu->get_popup()->add_item("Find..",SEARCH_FIND,KEY_MASK_CMD|KEY_F); + script_search_menu->get_popup()->add_item("Find Next",SEARCH_FIND_NEXT,KEY_F3); + script_search_menu->get_popup()->connect("item_pressed", this,"_menu_option"); + script_search_menu->hide(); + + debug_menu = memnew( MenuButton ); menu_hb->add_child(debug_menu); debug_menu->set_text("Debug"); @@ -1870,6 +2413,7 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) { debug_menu->get_popup()->add_item("Continue",DEBUG_CONTINUE); debug_menu->get_popup()->add_separator(); debug_menu->get_popup()->add_check_item("Show Debugger",DEBUG_SHOW); + debug_menu->get_popup()->add_check_item("Keep Debuger Open",DEBUG_SHOW_KEEP_OPEN); debug_menu->get_popup()->connect("item_pressed", this,"_menu_option"); debug_menu->get_popup()->set_item_disabled( debug_menu->get_popup()->get_item_index(DEBUG_NEXT), true); @@ -1897,6 +2441,53 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) { help_menu->get_popup()->add_item("Contextual", HELP_CONTEXTUAL, KEY_MASK_SHIFT|KEY_F1); help_menu->get_popup()->connect("item_pressed", this,"_menu_option"); + menu_hb->add_spacer(); + + + script_icon = memnew( TextureFrame ); + menu_hb->add_child(script_icon); + script_name_label = memnew( Label ); + menu_hb->add_child(script_name_label); + + script_icon->hide(); + script_name_label->hide(); + + menu_hb->add_spacer(); + + site_search = memnew( ToolButton ); + site_search->set_text("Tutorials"); + site_search->connect("pressed",this,"_menu_option",varray(SEARCH_WEBSITE)); + menu_hb->add_child(site_search); + site_search->set_tooltip("Open http://www.godotengine.org at tutorials section."); + + class_search = memnew( ToolButton ); + class_search->set_text("Classes"); + class_search->connect("pressed",this,"_menu_option",varray(SEARCH_CLASSES)); + menu_hb->add_child(class_search); + class_search->set_tooltip("Search the class hierarchy."); + + help_search = memnew( ToolButton ); + help_search->set_text("Search Help"); + help_search->connect("pressed",this,"_menu_option",varray(SEARCH_HELP)); + menu_hb->add_child(help_search); + help_search->set_tooltip("Search the reference documentation."); + + menu_hb->add_child( memnew( VSeparator) ); + + script_back = memnew( ToolButton ); + script_back->connect("pressed",this,"_history_back"); + menu_hb->add_child(script_back); + script_back->set_disabled(true); + help_search->set_tooltip("Go to previous edited document."); + + script_forward = memnew( ToolButton ); + script_forward->connect("pressed",this,"_history_forward"); + menu_hb->add_child(script_forward); + script_forward->set_disabled(true); + help_search->set_tooltip("Go to next edited document."); + + + tab_container->connect("tab_changed", this,"_tab_changed"); find_replace_dialog = memnew(FindReplaceDialog); @@ -1959,8 +2550,20 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) { grab_focus_block=false; + help_search_dialog = memnew( EditorHelpSearch ); + add_child(help_search_dialog); + help_search_dialog->connect("go_to_help",this,"_help_class_goto"); + + + help_index = memnew( EditorHelpIndex ); + add_child(help_index); + help_index->connect("open_class",this,"_help_class_open"); + + history_pos=-1; // debugger_gui->hide(); + edit_pass=0; + } @@ -2052,6 +2655,11 @@ void ScriptEditorPlugin::get_breakpoints(List<String> *p_breakpoints) { return script_editor->get_breakpoints(p_breakpoints); } +void ScriptEditorPlugin::edited_scene_changed() { + + script_editor->edited_scene_changed(); +} + ScriptEditorPlugin::ScriptEditorPlugin(EditorNode *p_node) { editor=p_node; @@ -2061,9 +2669,15 @@ ScriptEditorPlugin::ScriptEditorPlugin(EditorNode *p_node) { script_editor->hide(); - EDITOR_DEF("text_editor/auto_reload_changed_scripts",false); + EDITOR_DEF("text_editor/auto_reload_scripts_on_external_change",true); + EDITOR_DEF("text_editor/open_dominant_script_on_scene_change",true); EDITOR_DEF("external_editor/use_external_editor",false); EDITOR_DEF("external_editor/exec_path",""); + EDITOR_DEF("text_editor/script_temperature_enabled",true); + EDITOR_DEF("text_editor/script_temperature_history_size",15); + EDITOR_DEF("text_editor/script_temperature_hot_color",Color(1,0,0,0.3)); + EDITOR_DEF("text_editor/script_temperature_cold_color",Color(0,0,1,0.3)); + EDITOR_DEF("text_editor/group_help_pages",false); EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING,"external_editor/exec_path",PROPERTY_HINT_GLOBAL_FILE)); EDITOR_DEF("external_editor/exec_flags",""); diff --git a/tools/editor/plugins/script_editor_plugin.h b/tools/editor/plugins/script_editor_plugin.h index e635a1974b..b829d4e0e5 100644 --- a/tools/editor/plugins/script_editor_plugin.h +++ b/tools/editor/plugins/script_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -41,6 +41,7 @@ #include "tools/editor/code_editor.h" #include "scene/gui/split_container.h" #include "scene/gui/item_list.h" +#include "tools/editor/editor_help.h" class ScriptEditorQuickOpen : public ConfirmationDialog { @@ -102,7 +103,7 @@ public: void reload_text(); String get_name() ; Ref<Texture> get_icon() ; - + bool is_unsaved(); ScriptTextEditor(); }; @@ -141,15 +142,21 @@ class ScriptEditor : public VBoxContainer { SEARCH_REPLACE, SEARCH_LOCATE_FUNCTION, SEARCH_GOTO_LINE, + SEARCH_HELP, + SEARCH_CLASSES, + SEARCH_WEBSITE, DEBUG_TOGGLE_BREAKPOINT, DEBUG_NEXT, DEBUG_STEP, DEBUG_BREAK, DEBUG_CONTINUE, DEBUG_SHOW, - HELP_CONTEXTUAL, + DEBUG_SHOW_KEEP_OPEN, + HELP_CONTEXTUAL, WINDOW_MOVE_LEFT, WINDOW_MOVE_RIGHT, + WINDOW_NEXT, + WINDOW_PREV, WINDOW_SELECT_BASE=100 }; @@ -157,11 +164,17 @@ class ScriptEditor : public VBoxContainer { MenuButton *file_menu; MenuButton *edit_menu; MenuButton *search_menu; + MenuButton *script_search_menu; MenuButton *debug_menu; MenuButton *help_menu; Timer *autosave_timer; uint64_t idle; + Button *help_search; + Button *site_search; + Button *class_search; + EditorHelpSearch *help_search_dialog; + ItemList *script_list; HSplitContainer *script_split; TabContainer *tab_container; @@ -172,6 +185,27 @@ class ScriptEditor : public VBoxContainer { ScriptEditorDebugger* debugger; ToolButton *scripts_visible; + TextureFrame *script_icon; + Label *script_name_label; + + ToolButton *script_back; + ToolButton *script_forward; + + + struct ScriptHistory { + + Control *control; + int scroll_pos; + int cursor_column; + int cursor_row; + }; + + Vector<ScriptHistory> history; + int history_pos; + + + EditorHelpIndex *help_index; + void _tab_changed(int p_which); void _menu_option(int p_optin); @@ -201,6 +235,8 @@ class ScriptEditor : public VBoxContainer { void _editor_pause(); void _editor_stop(); + int edit_pass; + void _add_callback(Object *p_obj, const String& p_function, const StringArray& p_args); void _res_saved_callback(const Ref<Resource>& p_res); @@ -224,8 +260,21 @@ class ScriptEditor : public VBoxContainer { void _script_split_dragged(float); + + void _history_forward(); + void _history_back(); + bool waiting_update_names; + void _help_class_open(const String& p_class); + void _help_class_goto(const String& p_desc); + void _update_history_arrows(); + void _go_to_tab(int p_idx); + void _update_history_pos(int p_new_pos); + void _update_script_colors(); + void _update_modified_scripts_for_external_editor(); + + static ScriptEditor *script_editor; protected: void _notification(int p_what); @@ -253,6 +302,10 @@ public: void set_window_layout(Ref<ConfigFile> p_layout); void get_window_layout(Ref<ConfigFile> p_layout); + void set_scene_root_script( Ref<Script> p_script ); + + virtual void edited_scene_changed(); + ScriptEditorDebugger *get_debugger() { return debugger; } ScriptEditor(EditorNode *p_editor); @@ -289,6 +342,7 @@ public: virtual void get_breakpoints(List<String> *p_breakpoints); + virtual void edited_scene_changed(); ScriptEditorPlugin(EditorNode *p_node); ~ScriptEditorPlugin(); diff --git a/tools/editor/plugins/shader_editor_plugin.cpp b/tools/editor/plugins/shader_editor_plugin.cpp index a182d57742..65b5365b50 100644 --- a/tools/editor/plugins/shader_editor_plugin.cpp +++ b/tools/editor/plugins/shader_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -172,11 +172,8 @@ ShaderTextEditor::ShaderTextEditor() { void ShaderEditor::_menu_option(int p_option) { - int selected = tab_container->get_current_tab(); - if (selected<0 || selected>=tab_container->get_child_count()) - return; - ShaderTextEditor *current = tab_container->get_child(selected)->cast_to<ShaderTextEditor>(); + ShaderTextEditor *current = tab_container->get_current_tab_control()->cast_to<ShaderTextEditor>(); if (!current) return; @@ -235,6 +232,11 @@ void ShaderEditor::_menu_option(int p_option) { void ShaderEditor::_tab_changed(int p_which) { + ShaderTextEditor *shader_editor = tab_container->get_tab_control(p_which)->cast_to<ShaderTextEditor>(); + + if (shader_editor) + shader_editor->get_text_edit()->grab_focus(); + ensure_select_current(); } diff --git a/tools/editor/plugins/shader_editor_plugin.h b/tools/editor/plugins/shader_editor_plugin.h index 4ead2ba94e..26d20b80b4 100644 --- a/tools/editor/plugins/shader_editor_plugin.h +++ b/tools/editor/plugins/shader_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/shader_graph_editor_plugin.cpp b/tools/editor/plugins/shader_graph_editor_plugin.cpp index 684e7e32ef..c6677b6883 100644 --- a/tools/editor/plugins/shader_graph_editor_plugin.cpp +++ b/tools/editor/plugins/shader_graph_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -2542,7 +2542,7 @@ void ShaderGraphView::_notification(int p_what) { void ShaderGraphView::add_node(int p_type, const Vector2 &location) { - if ((p_type==ShaderGraph::NODE_INPUT||p_type==ShaderGraph::NODE_INPUT) && graph->node_count(type, p_type)>0) + if (p_type==ShaderGraph::NODE_INPUT && graph->node_count(type, p_type)>0) return; List<int> existing; diff --git a/tools/editor/plugins/shader_graph_editor_plugin.h b/tools/editor/plugins/shader_graph_editor_plugin.h index 39e9b29d45..5ac9db3650 100644 --- a/tools/editor/plugins/shader_graph_editor_plugin.h +++ b/tools/editor/plugins/shader_graph_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/spatial_editor_plugin.cpp b/tools/editor/plugins/spatial_editor_plugin.cpp index 3ab9339265..8903e12319 100644 --- a/tools/editor/plugins/spatial_editor_plugin.cpp +++ b/tools/editor/plugins/spatial_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -232,15 +232,6 @@ void SpatialEditorViewport::_select(Spatial *p_node, bool p_append,bool p_single } - -struct _RayResult { - - Spatial* item; - float depth; - int handle; - _FORCE_INLINE_ bool operator<(const _RayResult& p_rr) const { return depth<p_rr.depth; } -}; - ObjectID SpatialEditorViewport::_select_ray(const Point2& p_pos, bool p_append,bool &r_includes_current,int *r_gizmo_handle,bool p_alt_select) { if (r_gizmo_handle) @@ -379,6 +370,70 @@ ObjectID SpatialEditorViewport::_select_ray(const Point2& p_pos, bool p_append,b } +void SpatialEditorViewport::_find_items_at_pos(const Point2& p_pos,bool &r_includes_current,Vector<_RayResult> &results,bool p_alt_select) { + + Vector3 ray=_get_ray(p_pos); + Vector3 pos=_get_ray_pos(p_pos); + + Vector<RID> instances=VisualServer::get_singleton()->instances_cull_ray(pos,ray,get_tree()->get_root()->get_world()->get_scenario() ); + Set<Ref<SpatialEditorGizmo> > found_gizmos; + + r_includes_current=false; + + for (int i=0;i<instances.size();i++) { + + uint32_t id=VisualServer::get_singleton()->instance_get_object_instance_ID(instances[i]); + Object *obj=ObjectDB::get_instance(id); + if (!obj) + continue; + + Spatial *spat=obj->cast_to<Spatial>(); + + if (!spat) + continue; + + Ref<SpatialEditorGizmo> seg = spat->get_gizmo(); + + if (!seg.is_valid()) + continue; + + if (found_gizmos.has(seg)) + continue; + + found_gizmos.insert(seg); + Vector3 point; + Vector3 normal; + + int handle=-1; + bool inters = seg->intersect_ray(camera,p_pos,point,normal,NULL,p_alt_select); + + if (!inters) + continue; + + float dist = pos.distance_to(point); + + if (dist<0) + continue; + + + + if (editor_selection->is_selected(spat)) + r_includes_current=true; + + _RayResult res; + res.item=spat; + res.depth=dist; + res.handle=handle; + results.push_back(res); + } + + + if (results.empty()) + return; + + results.sort(); +} + Vector3 SpatialEditorViewport::_get_screen_to_space(const Vector3& p_pos) { @@ -681,6 +736,68 @@ void SpatialEditorViewport::_smouseenter() { surface->grab_focus(); } +void SpatialEditorViewport::_list_select(InputEventMouseButton b) { + + _find_items_at_pos(Vector2( b.x, b.y ),clicked_includes_current,selection_results,b.mod.shift); + + Node *scene=editor->get_edited_scene(); + + for(int i=0;i<selection_results.size();i++) { + Spatial *item=selection_results[i].item; + if (item!=scene && item->get_owner()!=scene && !scene->is_editable_instance(item->get_owner())) { + //invalid result + selection_results.remove(i); + i--; + } + + } + + + clicked_wants_append=b.mod.shift; + + if (selection_results.size() == 1) { + + clicked=selection_results[0].item->get_instance_ID(); + selection_results.clear(); + + if (clicked) { + _select_clicked(clicked_wants_append,true); + clicked=0; + } + + } else if (!selection_results.empty()) { + + NodePath root_path = get_tree()->get_edited_scene_root()->get_path(); + StringName root_name = root_path.get_name(root_path.get_name_count()-1); + + for (int i = 0; i < selection_results.size(); i++) { + + Spatial *spat=selection_results[i].item; + + Ref<Texture> icon; + if (spat->has_meta("_editor_icon")) + icon=spat->get_meta("_editor_icon"); + else + icon=get_icon( has_icon(spat->get_type(),"EditorIcons")?spat->get_type():String("Object"),"EditorIcons"); + + String node_path="/"+root_name+"/"+root_path.rel_path_to(spat->get_path()); + + selection_menu->add_item(spat->get_name()); + selection_menu->set_item_icon(i, icon ); + selection_menu->set_item_metadata(i, node_path); + selection_menu->set_item_tooltip(i,String(spat->get_name())+ + "\nType: "+spat->get_type()+"\nPath: "+node_path); + } + + selection_menu->set_global_pos(Vector2( b.global_x, b.global_y )); + selection_menu->popup(); + selection_menu->call_deferred("grab_click_focus"); + selection_menu->set_invalidate_click_until_motion(); + + + + } +} void SpatialEditorViewport::_sinput(const InputEvent &p_event) { if (previewing) @@ -724,6 +841,7 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) { } break; case BUTTON_RIGHT: { + NavigationScheme nav_scheme = _get_navigation_schema("3d_editor/navigation_scheme"); if (b.pressed && _edit.gizmo.is_valid()) { //restore @@ -806,6 +924,16 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) { //VisualServer::get_singleton()->instance_set_transform(cursor_instance,Transform(Matrix3(),cursor.cursor_pos)); } } + + if (b.mod.alt) { + + if (nav_scheme == NAVIGATION_MAYA) + break; + + _list_select(b); + return; + + } } if (_edit.mode!=TRANSFORM_NONE && b.pressed) { @@ -877,6 +1005,11 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) { break; } + if (spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_LIST_SELECT) { + _list_select(b); + break; + } + _edit.mouse_pos=Point2(b.x,b.y); _edit.snap=false; _edit.mode=TRANSFORM_NONE; @@ -1484,6 +1617,8 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) { case InputEvent::KEY: { const InputEventKey &k = p_event.key; + if (!k.pressed) + break; switch(k.scancode) { case KEY_S: { @@ -1544,7 +1679,8 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) { } break; case KEY_KP_5: { - orthogonal = !orthogonal; + + //orthogonal = !orthogonal; _menu_option(orthogonal?VIEW_PERSPECTIVE:VIEW_ORTHOGONAL); _update_name(); @@ -1957,11 +2093,11 @@ void SpatialEditorViewport::_menu_option(int p_option) { if (!se) continue; - Vector3 original_scale = sp->get_scale(); - sp->set_global_transform(camera_transform); - sp->set_scale(original_scale); - undo_redo->add_do_method(sp,"set_global_transform",sp->get_global_transform()); - undo_redo->add_undo_method(sp,"set_global_transform",se->original); + Transform xform = camera_transform; + xform.scale_basis(sp->get_scale()); + + undo_redo->add_do_method(sp,"set_global_transform",xform); + undo_redo->add_undo_method(sp,"set_global_transform",sp->get_global_transform()); } undo_redo->commit_action(); } break; @@ -2096,6 +2232,26 @@ void SpatialEditorViewport::_toggle_camera_preview(bool p_activate) { } } +void SpatialEditorViewport::_selection_result_pressed(int p_result) { + + if (selection_results.size() <= p_result) + return; + + clicked=selection_results[p_result].item->get_instance_ID(); + + if (clicked) { + _select_clicked(clicked_wants_append,true); + clicked=0; + } +} + +void SpatialEditorViewport::_selection_menu_hide() { + + selection_results.clear(); + selection_menu->clear(); + selection_menu->set_size(Vector2(0, 0)); +} + void SpatialEditorViewport::set_can_preview(Camera* p_preview) { preview=p_preview; @@ -2210,6 +2366,8 @@ void SpatialEditorViewport::_bind_methods(){ ObjectTypeDB::bind_method(_MD("_toggle_camera_preview"),&SpatialEditorViewport::_toggle_camera_preview); ObjectTypeDB::bind_method(_MD("_preview_exited_scene"),&SpatialEditorViewport::_preview_exited_scene); ObjectTypeDB::bind_method(_MD("update_transform_gizmo_view"),&SpatialEditorViewport::update_transform_gizmo_view); + ObjectTypeDB::bind_method(_MD("_selection_result_pressed"),&SpatialEditorViewport::_selection_result_pressed); + ObjectTypeDB::bind_method(_MD("_selection_menu_hide"),&SpatialEditorViewport::_selection_menu_hide); ADD_SIGNAL( MethodInfo("toggle_maximize_view", PropertyInfo(Variant::OBJECT, "viewport")) ); } @@ -2307,6 +2465,12 @@ SpatialEditorViewport::SpatialEditorViewport(SpatialEditor *p_spatial_editor, Ed preview=NULL; gizmo_scale=1.0; + selection_menu = memnew( PopupMenu ); + add_child(selection_menu); + selection_menu->set_custom_minimum_size(Vector2(100, 0)); + selection_menu->connect("item_pressed", this, "_selection_result_pressed"); + selection_menu->connect("popup_hide", this, "_selection_menu_hide"); + if (p_index==0) { view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER),true); viewport->set_as_audio_listener(true); @@ -2706,13 +2870,14 @@ void SpatialEditor::_menu_item_pressed(int p_option) { case MENU_TOOL_SELECT: case MENU_TOOL_MOVE: case MENU_TOOL_ROTATE: - case MENU_TOOL_SCALE: { + case MENU_TOOL_SCALE: + case MENU_TOOL_LIST_SELECT: { - for(int i=0;i<4;i++) + for(int i=0;i<TOOL_MAX;i++) tool_button[i]->set_pressed(i==p_option); tool_mode=(ToolMode)p_option; - static const char *_mode[]={"Selection Mode.","Translation Mode.","Rotation Mode.","Scale Mode."}; + static const char *_mode[]={"Selection Mode.","Translation Mode.","Rotation Mode.","Scale Mode.","List Selection Mode."}; // set_message(_mode[p_option],3); update_transform_gizmo(); @@ -2725,7 +2890,7 @@ void SpatialEditor::_menu_item_pressed(int p_option) { } break; case MENU_TRANSFORM_CONFIGURE_SNAP: { - snap_dialog->popup_centered(Size2(200,160)); + snap_dialog->popup_centered(Size2(200,180)); } break; case MENU_TRANSFORM_LOCAL_COORDS: { @@ -3395,6 +3560,7 @@ void SpatialEditor::_notification(int p_what) { tool_button[SpatialEditor::TOOL_MODE_MOVE]->set_icon( get_icon("ToolMove","EditorIcons") ); tool_button[SpatialEditor::TOOL_MODE_ROTATE]->set_icon( get_icon("ToolRotate","EditorIcons") ); tool_button[SpatialEditor::TOOL_MODE_SCALE]->set_icon( get_icon("ToolScale","EditorIcons") ); + tool_button[SpatialEditor::TOOL_MODE_LIST_SELECT]->set_icon( get_icon("ListSelect","EditorIcons") ); instance_button->set_icon( get_icon("SpatialAdd","EditorIcons") ); instance_button->hide(); @@ -3672,7 +3838,7 @@ SpatialEditor::SpatialEditor(EditorNode *p_editor) { tool_button[TOOL_MODE_SELECT]->set_pressed(true); button_binds[0]=MENU_TOOL_SELECT; tool_button[TOOL_MODE_SELECT]->connect("pressed", this,"_menu_item_pressed",button_binds); - tool_button[TOOL_MODE_SELECT]->set_tooltip("Select Mode (Q)"); + tool_button[TOOL_MODE_SELECT]->set_tooltip("Select Mode (Q)\n"+keycode_get_string(KEY_MASK_CMD)+"Drag: Rotate\nAlt+Drag: Move\nAlt+RMB: Depth list selection"); tool_button[TOOL_MODE_MOVE] = memnew( ToolButton ); @@ -3704,10 +3870,22 @@ SpatialEditor::SpatialEditor(EditorNode *p_editor) { hbc_menu->add_child( instance_button ); instance_button->set_flat(true); instance_button->connect("pressed",this,"_instance_scene"); + instance_button->hide(); VSeparator *vs = memnew( VSeparator ); hbc_menu->add_child(vs); + tool_button[TOOL_MODE_LIST_SELECT] = memnew( ToolButton ); + hbc_menu->add_child( tool_button[TOOL_MODE_LIST_SELECT] ); + tool_button[TOOL_MODE_LIST_SELECT]->set_toggle_mode(true); + tool_button[TOOL_MODE_LIST_SELECT]->set_flat(true); + button_binds[0]=MENU_TOOL_LIST_SELECT; + tool_button[TOOL_MODE_LIST_SELECT]->connect("pressed", this,"_menu_item_pressed",button_binds); + tool_button[TOOL_MODE_LIST_SELECT]->set_tooltip("Show a list of all objects at the position clicked\n(same as Alt+RMB in selet mode)."); + + vs = memnew( VSeparator ); + hbc_menu->add_child(vs); + PopupMenu *p; @@ -3793,46 +3971,24 @@ SpatialEditor::SpatialEditor(EditorNode *p_editor) { snap_dialog = memnew( ConfirmationDialog ); snap_dialog->set_title("Snap Settings"); add_child(snap_dialog); - Label *l = memnew(Label); - l->set_text("Translate Snap:"); - l->set_pos(Point2(5,5)); - snap_dialog->add_child(l); + + VBoxContainer *snap_dialog_vbc = memnew( VBoxContainer ); + snap_dialog->add_child(snap_dialog_vbc); + snap_dialog->set_child_rect(snap_dialog_vbc); snap_translate = memnew( LineEdit ); - snap_translate->set_anchor( MARGIN_RIGHT, ANCHOR_END ); - snap_translate->set_begin( Point2(15,22) ); - snap_translate->set_end( Point2(15,35) ); snap_translate->set_text("1"); - snap_dialog->add_child(snap_translate); - - l = memnew(Label); - l->set_text("Rotate Snap (deg.):"); - l->set_pos(Point2(5,45)); - snap_dialog->add_child(l); + snap_dialog_vbc->add_margin_child("Translate Snap:",snap_translate); snap_rotate = memnew( LineEdit ); - snap_rotate->set_anchor( MARGIN_RIGHT, ANCHOR_END ); - snap_rotate->set_begin( Point2(15,62) ); - snap_rotate->set_end( Point2(15,75) ); snap_rotate->set_text("5"); - snap_dialog->add_child(snap_rotate); - - - l = memnew(Label); - l->set_text("Scale Snap (%):"); - l->set_pos(Point2(5,85)); - snap_dialog->add_child(l); + snap_dialog_vbc->add_margin_child("Rotate Snap (deg.):",snap_rotate); snap_scale = memnew( LineEdit ); - snap_scale->set_anchor( MARGIN_RIGHT, ANCHOR_END ); - snap_scale->set_begin( Point2(15,102) ); - snap_scale->set_end( Point2(15,115) ); snap_scale->set_text("5"); - snap_dialog->add_child(snap_scale); + snap_dialog_vbc->add_margin_child("Scale Snap (%):",snap_scale); - //snap_dialog->get_cancel()->hide(); - - /* SNAP DIALOG */ + /* SETTINGS DIALOG */ settings_dialog = memnew( ConfirmationDialog ); settings_dialog->set_title("Viewport Settings"); @@ -3906,7 +4062,7 @@ SpatialEditor::SpatialEditor(EditorNode *p_editor) { xform_dialog = memnew( ConfirmationDialog ); xform_dialog->set_title("Transform Change"); add_child(xform_dialog); - l = memnew(Label); + Label *l = memnew(Label); l->set_text("Translate:"); l->set_pos(Point2(5,5)); xform_dialog->add_child(l); diff --git a/tools/editor/plugins/spatial_editor_plugin.h b/tools/editor/plugins/spatial_editor_plugin.h index ff8912fca8..e8856d5a8f 100644 --- a/tools/editor/plugins/spatial_editor_plugin.h +++ b/tools/editor/plugins/spatial_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -111,12 +111,21 @@ private: bool orthogonal; float gizmo_scale; + struct _RayResult { + + Spatial* item; + float depth; + int handle; + _FORCE_INLINE_ bool operator<(const _RayResult& p_rr) const { return depth<p_rr.depth; } + }; + void _update_name(); void _compute_edit(const Point2& p_point); void _clear_selected(); void _select_clicked(bool p_append,bool p_single); void _select(Spatial *p_node, bool p_append,bool p_single); ObjectID _select_ray(const Point2& p_pos, bool p_append,bool &r_includes_current,int *r_gizmo_handle=NULL,bool p_alt_select=false); + void _find_items_at_pos(const Point2& p_pos,bool &r_includes_current,Vector<_RayResult> &results,bool p_alt_select=false); Vector3 _get_ray_pos(const Vector2& p_pos) const; Vector3 _get_ray(const Vector2& p_pos); Point2 _point_to_screen(const Vector3& p_point); @@ -136,9 +145,12 @@ private: float get_fov() const; ObjectID clicked; + Vector<_RayResult> selection_results; bool clicked_includes_current; bool clicked_wants_append; + PopupMenu *selection_menu; + enum NavigationScheme { NAVIGATION_GODOT, NAVIGATION_MAYA, @@ -225,6 +237,9 @@ private: void _toggle_camera_preview(bool); void _init_gizmo_instance(int p_idx); void _finish_gizmo_instances(); + void _selection_result_pressed(int); + void _selection_menu_hide(); + void _list_select(InputEventMouseButton b); protected: @@ -273,7 +288,9 @@ public: TOOL_MODE_SELECT, TOOL_MODE_MOVE, TOOL_MODE_ROTATE, - TOOL_MODE_SCALE + TOOL_MODE_SCALE, + TOOL_MODE_LIST_SELECT, + TOOL_MAX }; @@ -355,6 +372,7 @@ private: MENU_TOOL_MOVE, MENU_TOOL_ROTATE, MENU_TOOL_SCALE, + MENU_TOOL_LIST_SELECT, MENU_TRANSFORM_USE_SNAP, MENU_TRANSFORM_CONFIGURE_SNAP, MENU_TRANSFORM_LOCAL_COORDS, @@ -378,7 +396,7 @@ private: }; - Button *tool_button[4]; + Button *tool_button[TOOL_MAX]; Button *instance_button; diff --git a/tools/editor/plugins/sprite_frames_editor_plugin.cpp b/tools/editor/plugins/sprite_frames_editor_plugin.cpp index e90087efda..048df2d682 100644 --- a/tools/editor/plugins/sprite_frames_editor_plugin.cpp +++ b/tools/editor/plugins/sprite_frames_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -338,7 +338,6 @@ void SpriteFramesEditor::_update_library() { TreeItem *ti = tree->create_item(root); ti->set_cell_mode(0,TreeItem::CELL_MODE_STRING); - ti->set_editable(0,true); ti->set_selectable(0,true); if (frames->get_frame(i).is_null()) { @@ -346,7 +345,7 @@ void SpriteFramesEditor::_update_library() { ti->set_text(0,"Frame "+itos(i)+" (empty)"); } else { - ti->set_text(0,"Frame "+itos(i)); + ti->set_text(0,"Frame "+itos(i)+" ("+frames->get_frame(i)->get_name()+")"); ti->set_icon(0,frames->get_frame(i)); } if (frames->get_frame(i).is_valid()) diff --git a/tools/editor/plugins/sprite_frames_editor_plugin.h b/tools/editor/plugins/sprite_frames_editor_plugin.h index 969d7b1ce3..e4088da297 100644 --- a/tools/editor/plugins/sprite_frames_editor_plugin.h +++ b/tools/editor/plugins/sprite_frames_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/sprite_region_editor_plugin.cpp b/tools/editor/plugins/sprite_region_editor_plugin.cpp index 35c53cf562..2653973226 100644 --- a/tools/editor/plugins/sprite_region_editor_plugin.cpp +++ b/tools/editor/plugins/sprite_region_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Author: Mariano Suligoy */ /* */ diff --git a/tools/editor/plugins/sprite_region_editor_plugin.h b/tools/editor/plugins/sprite_region_editor_plugin.h index cf69395f40..fafa2e119b 100644 --- a/tools/editor/plugins/sprite_region_editor_plugin.h +++ b/tools/editor/plugins/sprite_region_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Author: Mariano Suligoy */ /* */ diff --git a/tools/editor/plugins/stream_editor_plugin.cpp b/tools/editor/plugins/stream_editor_plugin.cpp index 81db7f2846..d896784074 100644 --- a/tools/editor/plugins/stream_editor_plugin.cpp +++ b/tools/editor/plugins/stream_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/stream_editor_plugin.h b/tools/editor/plugins/stream_editor_plugin.h index 7378bfad0c..5730612d61 100644 --- a/tools/editor/plugins/stream_editor_plugin.h +++ b/tools/editor/plugins/stream_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/style_box_editor_plugin.cpp b/tools/editor/plugins/style_box_editor_plugin.cpp index 898c69e1e0..58e9038840 100644 --- a/tools/editor/plugins/style_box_editor_plugin.cpp +++ b/tools/editor/plugins/style_box_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/style_box_editor_plugin.h b/tools/editor/plugins/style_box_editor_plugin.h index 00b0871572..3b3f8d8d0f 100644 --- a/tools/editor/plugins/style_box_editor_plugin.h +++ b/tools/editor/plugins/style_box_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/theme_editor_plugin.cpp b/tools/editor/plugins/theme_editor_plugin.cpp index 63ba57bfc0..f67f049b36 100644 --- a/tools/editor/plugins/theme_editor_plugin.cpp +++ b/tools/editor/plugins/theme_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/theme_editor_plugin.h b/tools/editor/plugins/theme_editor_plugin.h index 40c7ad8186..f5e7192a73 100644 --- a/tools/editor/plugins/theme_editor_plugin.h +++ b/tools/editor/plugins/theme_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/tile_map_editor_plugin.cpp b/tools/editor/plugins/tile_map_editor_plugin.cpp index 66c7a39096..b2562eafe1 100644 --- a/tools/editor/plugins/tile_map_editor_plugin.cpp +++ b/tools/editor/plugins/tile_map_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -218,7 +218,8 @@ struct _TileMapEditorCopyData { bool TileMapEditor::forward_input_event(const InputEvent& p_event) { - if (!node || !node->get_tileset().is_valid()) + + if (!node || !node->get_tileset().is_valid() || !node->is_visible()) return false; Matrix32 xform = CanvasItemEditor::get_singleton()->get_canvas_transform() * node->get_global_transform(); diff --git a/tools/editor/plugins/tile_map_editor_plugin.h b/tools/editor/plugins/tile_map_editor_plugin.h index 74d1573d0f..3cbf5ff68d 100644 --- a/tools/editor/plugins/tile_map_editor_plugin.h +++ b/tools/editor/plugins/tile_map_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/plugins/tile_set_editor_plugin.cpp b/tools/editor/plugins/tile_set_editor_plugin.cpp index 39b0ef3c75..06046b226a 100644 --- a/tools/editor/plugins/tile_set_editor_plugin.cpp +++ b/tools/editor/plugins/tile_set_editor_plugin.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -110,11 +110,15 @@ void TileSetEditor::_import_scene(Node *scene, Ref<TileSet> p_library, bool p_me if (!child2->cast_to<StaticBody2D>()) continue; StaticBody2D *sb = child2->cast_to<StaticBody2D>(); - if (sb->get_shape_count()==0) + int shape_count = sb->get_shape_count(); + if (shape_count==0) continue; - Ref<Shape2D> collision=sb->get_shape(0); - if (collision.is_valid()) { - collisions.push_back(collision); + for (int shape_index=0; shape_index<shape_count; ++shape_index) + { + Ref<Shape2D> collision=sb->get_shape(shape_index); + if (collision.is_valid()) { + collisions.push_back(collision); + } } } @@ -141,10 +145,6 @@ void TileSetEditor::_menu_confirm() { switch(option) { - case MENU_OPTION_REMOVE_ITEM: { - - tileset->remove_tile(to_erase); - } break; case MENU_OPTION_MERGE_FROM_SCENE: case MENU_OPTION_CREATE_FROM_SCENE: { @@ -161,6 +161,27 @@ void TileSetEditor::_menu_confirm() { } } +void TileSetEditor::_name_dialog_confirm(const String& name) { + + switch (option) { + + case MENU_OPTION_REMOVE_ITEM: { + + int id=tileset->find_tile_by_name(name); + + if (id<0 && name.is_valid_integer()) + id=name.to_int(); + + if (tileset->has_tile(id)) { + tileset->remove_tile(id); + } else { + err_dialog->set_text("Could not find tile: " + name); + err_dialog->popup_centered(Size2(300, 60)); + } + } break; + } +} + void TileSetEditor::_menu_cbk(int p_option) { option=p_option; @@ -172,13 +193,9 @@ void TileSetEditor::_menu_cbk(int p_option) { } break; case MENU_OPTION_REMOVE_ITEM: { - String p = editor->get_property_editor()->get_selected_path(); - if (p.begins_with("/TileSet") && p.get_slice_count("/")>=2) { - - to_erase = p.get_slice("/",2).to_int(); - cd->set_text("Remove Item "+itos(to_erase)+"?"); - cd->popup_centered(Size2(300,60)); - } + nd->set_title("Remove Item"); + nd->set_text("Item name or ID:"); + nd->popup_centered(Size2(300, 95)); } break; case MENU_OPTION_CREATE_FROM_SCENE: { @@ -206,6 +223,7 @@ void TileSetEditor::_bind_methods() { ObjectTypeDB::bind_method("_menu_cbk",&TileSetEditor::_menu_cbk); ObjectTypeDB::bind_method("_menu_confirm",&TileSetEditor::_menu_confirm); + ObjectTypeDB::bind_method("_name_dialog_confirm",&TileSetEditor::_name_dialog_confirm); } TileSetEditor::TileSetEditor(EditorNode *p_editor) { @@ -218,7 +236,7 @@ TileSetEditor::TileSetEditor(EditorNode *p_editor) { options->set_pos(Point2(1,1)); options->set_text("Theme"); options->get_popup()->add_item("Add Item",MENU_OPTION_ADD_ITEM); - options->get_popup()->add_item("Remove Selected Item",MENU_OPTION_REMOVE_ITEM); + options->get_popup()->add_item("Remove Item",MENU_OPTION_REMOVE_ITEM); options->get_popup()->add_separator(); options->get_popup()->add_item("Create from Scene",MENU_OPTION_CREATE_FROM_SCENE); options->get_popup()->add_item("Merge from Scene",MENU_OPTION_MERGE_FROM_SCENE); @@ -228,6 +246,15 @@ TileSetEditor::TileSetEditor(EditorNode *p_editor) { add_child(cd); cd->get_ok()->connect("pressed", this,"_menu_confirm"); + nd = memnew(EditorNameDialog); + add_child(nd); + nd->set_hide_on_ok(true); + nd->get_line_edit()->set_margin(MARGIN_TOP,28); + nd->connect("name_confirmed", this,"_name_dialog_confirm"); + + err_dialog = memnew(AcceptDialog); + add_child(err_dialog); + err_dialog->set_title("Error"); } void TileSetEditorPlugin::edit(Object *p_node) { diff --git a/tools/editor/plugins/tile_set_editor_plugin.h b/tools/editor/plugins/tile_set_editor_plugin.h index df82df6993..3f47520e2a 100644 --- a/tools/editor/plugins/tile_set_editor_plugin.h +++ b/tools/editor/plugins/tile_set_editor_plugin.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -33,6 +33,7 @@ #include "scene/resources/tile_set.h" #include "tools/editor/editor_node.h" +#include "tools/editor/editor_name_dialog.h" class TileSetEditor : public Control { @@ -44,7 +45,8 @@ class TileSetEditor : public Control { EditorNode *editor; MenuButton *menu; ConfirmationDialog *cd; - int to_erase; + EditorNameDialog *nd; + AcceptDialog *err_dialog; enum { @@ -56,7 +58,8 @@ class TileSetEditor : public Control { int option; void _menu_cbk(int p_option); - void _menu_confirm(); + void _menu_confirm(); + void _name_dialog_confirm(const String& name); static void _import_scene(Node *p_scene, Ref<TileSet> p_library, bool p_merge); diff --git a/tools/editor/progress_dialog.cpp b/tools/editor/progress_dialog.cpp index c8b87486c0..d072ce7f83 100644 --- a/tools/editor/progress_dialog.cpp +++ b/tools/editor/progress_dialog.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -29,7 +29,7 @@ #include "progress_dialog.h" #include "main/main.h" #include "message_queue.h" - +#include "os/os.h" void BackgroundProgress::_add_task(const String& p_task,const String& p_label, int p_steps) { @@ -191,10 +191,16 @@ void ProgressDialog::add_task(const String& p_task,const String& p_label,int p_s } -void ProgressDialog::task_step(const String& p_task, const String& p_state, int p_step){ +void ProgressDialog::task_step(const String& p_task, const String& p_state, int p_step,bool p_force_redraw){ ERR_FAIL_COND(!tasks.has(p_task)); + if (!p_force_redraw) { + uint64_t tus = OS::get_singleton()->get_ticks_usec(); + if (tus-last_progress_tick < 50000) //50ms + return; + } + Task &t=tasks[p_task]; if (p_step<0) t.progress->set_val(t.progress->get_val()+1); @@ -202,6 +208,7 @@ void ProgressDialog::task_step(const String& p_task, const String& p_state, int t.progress->set_val(p_step); t.state->set_text(p_state); + last_progress_tick=OS::get_singleton()->get_ticks_usec(); Main::iteration(); // this will not work on a lot of platforms, so it's only meant for the editor } @@ -229,4 +236,5 @@ ProgressDialog::ProgressDialog() { add_child(main); main->set_area_as_parent_rect(); set_exclusive(true); + last_progress_tick=0; } diff --git a/tools/editor/progress_dialog.h b/tools/editor/progress_dialog.h index 7f1cc4cb2d..539eaa8737 100644 --- a/tools/editor/progress_dialog.h +++ b/tools/editor/progress_dialog.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -84,6 +84,7 @@ class ProgressDialog : public Popup { Map<String,Task> tasks; VBoxContainer *main; + uint64_t last_progress_tick; void _popup(); protected: @@ -92,7 +93,7 @@ protected: public: void add_task(const String& p_task,const String& p_label, int p_steps); - void task_step(const String& p_task,const String& p_state, int p_step=-1); + void task_step(const String& p_task, const String& p_state, int p_step=-1, bool p_force_redraw=true); void end_task(const String& p_task); diff --git a/tools/editor/project_export.cpp b/tools/editor/project_export.cpp index 6003b976aa..d034edc80d 100644 --- a/tools/editor/project_export.cpp +++ b/tools/editor/project_export.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -193,6 +193,8 @@ void ProjectExportDialog::_prop_edited(String what) { _save_export_cfg(); + _validate_platform(); + } void ProjectExportDialog::_filters_edited(String what) { @@ -252,6 +254,13 @@ void ProjectExportDialog::_script_edited(Variant v) { } +void ProjectExportDialog::_sample_convert_edited(int what) { + EditorImportExport::get_singleton()->sample_set_action( EditorImportExport::SampleAction(sample_mode->get_selected())); + EditorImportExport::get_singleton()->sample_set_max_hz( sample_max_hz->get_val() ); + EditorImportExport::get_singleton()->sample_set_trim( sample_trim->is_pressed() ); + +} + void ProjectExportDialog::_notification(int p_what) { switch(p_what) { @@ -288,6 +297,7 @@ void ProjectExportDialog::_notification(int p_what) { // _rescan(); _update_platform(); export_mode->select( EditorImportExport::get_singleton()->get_export_filter() ); + convert_text_scenes->set_pressed( EditorImportExport::get_singleton()->get_convert_text_scenes() ); filters->set_text( EditorImportExport::get_singleton()->get_export_custom_filter() ); if (EditorImportExport::get_singleton()->get_export_filter()!=EditorImportExport::EXPORT_SELECTED) tree_vb->hide(); @@ -319,6 +329,15 @@ void ProjectExportDialog::_notification(int p_what) { _update_group(); _update_group_tree(); + sample_mode->select( EditorImportExport::get_singleton()->sample_get_action() ); + sample_max_hz->set_val( EditorImportExport::get_singleton()->sample_get_max_hz() ); + sample_trim->set_pressed( EditorImportExport::get_singleton()->sample_get_trim() ); + + sample_mode->connect("item_selected",this,"_sample_convert_edited"); + sample_max_hz->connect("value_changed",this,"_sample_convert_edited"); + sample_trim->connect("toggled",this,"_sample_convert_edited"); + + } break; case NOTIFICATION_EXIT_TREE: { @@ -402,6 +421,8 @@ void ProjectExportDialog::_export_mode_changed(int p_idx) { else tree_vb->show(); + EditorImportExport::get_singleton()->set_convert_text_scenes( convert_text_scenes->is_pressed() ); + _save_export_cfg(); } @@ -450,20 +471,32 @@ void ProjectExportDialog::_export_action_pck(const String& p_file) { ERR_PRINT("Invalid platform for export of PCK"); return; } - FileAccess *f = FileAccess::open(p_file,FileAccess::WRITE); - if (!f) { - error->set_text("Error exporting project PCK! Can't write"); - error->popup_centered_minsize(); - } - ERR_FAIL_COND(!f); - Error err = exporter->save_pack(f,false); - memdelete(f); + if (p_file.ends_with(".pck")) { + FileAccess *f = FileAccess::open(p_file,FileAccess::WRITE); + if (!f) { + error->set_text("Error exporting project PCK! Can't write"); + error->popup_centered_minsize(); + } + ERR_FAIL_COND(!f); - if (err!=OK) { - error->set_text("Error exporting project!"); - error->popup_centered_minsize(); - return; + Error err = exporter->save_pack(f,false); + memdelete(f); + + if (err!=OK) { + error->set_text("Error exporting project!"); + error->popup_centered_minsize(); + return; + } + } else if (p_file.ends_with(".zip")) { + + Error err = exporter->save_zip(p_file,false); + + if (err!=OK) { + error->set_text("Error exporting project!"); + error->popup_centered_minsize(); + return; + } } } @@ -473,6 +506,18 @@ Error ProjectExportDialog::export_platform(const String& p_platform, const Strin Ref<EditorExportPlatform> exporter = EditorImportExport::get_singleton()->get_export_platform(p_platform); if (exporter.is_null()) { ERR_PRINT("Invalid platform for export"); + + List<StringName> platforms; + EditorImportExport::get_singleton()->get_export_platforms(&platforms); + print_line("Valid export plaftorms are:"); + for (List<StringName>::Element *E=platforms.front();E;E=E->next()) + print_line(" \""+E->get()+"\""); + + if (p_quit_after) { + OS::get_singleton()->set_exit_code(255); + get_tree()->quit(); + } + return ERR_INVALID_PARAMETER; } Error err = exporter->export_project(p_path,p_debug); @@ -1045,6 +1090,7 @@ void ProjectExportDialog::_bind_methods() { ObjectTypeDB::bind_method(_MD("_group_select_none"),&ProjectExportDialog::_group_select_none); ObjectTypeDB::bind_method(_MD("_script_edited"),&ProjectExportDialog::_script_edited); ObjectTypeDB::bind_method(_MD("_update_script"),&ProjectExportDialog::_update_script); + ObjectTypeDB::bind_method(_MD("_sample_convert_edited"),&ProjectExportDialog::_sample_convert_edited); ObjectTypeDB::bind_method(_MD("export_platform"),&ProjectExportDialog::export_platform); @@ -1106,6 +1152,7 @@ ProjectExportDialog::ProjectExportDialog(EditorNode *p_editor) { vb = memnew( VBoxContainer ); vb->set_name("Resources"); sections->add_child(vb); + export_mode = memnew( OptionButton ); export_mode->add_item("Export selected resources (including dependencies)."); export_mode->add_item("Export all resources in the project."); @@ -1114,6 +1161,8 @@ ProjectExportDialog::ProjectExportDialog(EditorNode *p_editor) { vb->add_margin_child("Export Mode:",export_mode); + + tree_vb = memnew( VBoxContainer ); vb->add_child(tree_vb); tree_vb->set_v_size_flags(SIZE_EXPAND_FILL); @@ -1134,6 +1183,10 @@ ProjectExportDialog::ProjectExportDialog(EditorNode *p_editor) { vb->add_margin_child("Filters to export non-resource files (Comma Separated, ie: *.json, *.txt):",filters); filters->connect("text_changed",this,"_filters_edited"); + convert_text_scenes = memnew( CheckButton ); + convert_text_scenes->set_text("Convert text scenes to binary on export"); + vb->add_child(convert_text_scenes); + convert_text_scenes->connect("toggled",this,"_export_mode_changed"); image_vb = memnew( VBoxContainer ); image_vb->set_name("Images"); @@ -1316,6 +1369,22 @@ ProjectExportDialog::ProjectExportDialog(EditorNode *p_editor) { hbc->add_child(button_reload); */ + + sample_vbox = memnew( VBoxContainer ); + sample_vbox->set_name("Samples"); + sections->add_child(sample_vbox); + sample_mode = memnew( OptionButton ); + sample_vbox->add_margin_child("Sample Conversion Mode: (.wav files):",sample_mode); + sample_mode->add_item("Keep"); + sample_mode->add_item("Compress (RAM - IMA-ADPCM)"); + sample_max_hz = memnew( SpinBox ); + sample_max_hz->set_max(192000); + sample_max_hz->set_min(8000); + sample_vbox->add_margin_child("Sampling Rate Limit: (hz)",sample_max_hz); + sample_trim = memnew( CheckButton ); + sample_trim->set_text("Trim"); + sample_vbox->add_margin_child("Trailing Silence:",sample_trim); + script_vbox = memnew( VBoxContainer ); script_vbox->set_name("Script"); sections->add_child(script_vbox); @@ -1338,7 +1407,7 @@ ProjectExportDialog::ProjectExportDialog(EditorNode *p_editor) { add_child(confirm); confirm->connect("confirmed",this,"_confirmed"); - get_ok()->set_text("Export PCK"); + get_ok()->set_text("Export PCK/Zip"); expopt="--,Export,Bundle"; @@ -1368,6 +1437,7 @@ ProjectExportDialog::ProjectExportDialog(EditorNode *p_editor) { pck_export->set_title("Export Project PCK"); pck_export->connect("file_selected", this,"_export_action_pck"); pck_export->add_filter("*.pck ; Data Pack"); + pck_export->add_filter("*.zip ; Zip"); add_child(pck_export); button_export = add_button("Export..",!OS::get_singleton()->get_swap_ok_cancel(),"export_pck"); diff --git a/tools/editor/project_export.h b/tools/editor/project_export.h index d85e688e58..5a42a58e58 100644 --- a/tools/editor/project_export.h +++ b/tools/editor/project_export.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -108,6 +108,7 @@ private: PropertyEditor *platform_options; OptionButton *export_mode; + CheckButton *convert_text_scenes; VBoxContainer *tree_vb; VBoxContainer *image_vb; @@ -139,6 +140,10 @@ private: OptionButton *script_mode; LineEdit *script_key; + VBoxContainer *sample_vbox; + OptionButton *sample_mode; + SpinBox *sample_max_hz; + CheckButton *sample_trim; void _export_mode_changed(int p_idx); @@ -162,6 +167,8 @@ private: void _image_export_edited(int what); void _shrink_edited(float what); + void _sample_convert_edited(int what); + void _update_group_list(); void _select_group(const String& p_by_name); diff --git a/tools/editor/project_manager.cpp b/tools/editor/project_manager.cpp index 9f47291433..5fd9118a32 100644 --- a/tools/editor/project_manager.cpp +++ b/tools/editor/project_manager.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -144,7 +144,7 @@ class NewProjectDialog : public ConfirmationDialog { fdialog->set_mode(FileDialog::MODE_OPEN_FILE); fdialog->clear_filters(); - fdialog->add_filter("engine.cfg ; "_MKSTR(VERSION_NAME)" Project"); + fdialog->add_filter("engine.cfg ; " _MKSTR(VERSION_NAME) " Project"); } else { fdialog->set_mode(FileDialog::MODE_OPEN_DIR); } @@ -193,7 +193,7 @@ class NewProjectDialog : public ConfirmationDialog { f->store_line("\n"); f->store_line("[application]"); f->store_line("name=\""+project_name->get_text()+"\""); - f->store_line("icon=\"icon.png\""); + f->store_line("icon=\"res://icon.png\""); memdelete(f); @@ -348,6 +348,13 @@ struct ProjectItem { _FORCE_INLINE_ bool operator ==(const ProjectItem& l) const { return project==l.project; } }; +void ProjectManager::_notification(int p_what) { + + if (p_what==NOTIFICATION_ENTER_TREE) { + + get_tree()->set_editor_hint(true); + } +} void ProjectManager::_panel_draw(Node *p_hb) { @@ -480,20 +487,25 @@ void ProjectManager::_load_recent_projects() { bool favorite = (_name.begins_with("favorite_projects/"))?true:false; uint64_t last_modified = 0; - if (FileAccess::exists(conf)) + if (FileAccess::exists(conf)) { last_modified = FileAccess::get_modified_time(conf); - String fscache = path.plus_file(".fscache"); - if (FileAccess::exists(fscache)) { - uint64_t cache_modified = FileAccess::get_modified_time(fscache); - if ( cache_modified > last_modified ) - last_modified = cache_modified; - } - ProjectItem item(project, path, conf, last_modified, favorite); - if (favorite) - favorite_projects.push_back(item); - else - projects.push_back(item); + String fscache = path.plus_file(".fscache"); + if (FileAccess::exists(fscache)) { + uint64_t cache_modified = FileAccess::get_modified_time(fscache); + if ( cache_modified > last_modified ) + last_modified = cache_modified; + } + + ProjectItem item(project, path, conf, last_modified, favorite); + if (favorite) + favorite_projects.push_back(item); + else + projects.push_back(item); + } else { + //project doesn't exist on disk but it's in the XML settings file + EditorSettings::get_singleton()->erase(_name); //remove it + } } projects.sort(); @@ -601,6 +613,8 @@ void ProjectManager::_load_recent_projects() { erase_btn->set_disabled(selected_list.size()<1); open_btn->set_disabled(selected_list.size()<1); run_btn->set_disabled(selected_list.size()<1 || (selected_list.size()==1 && single_selected_main=="")); + + EditorSettings::get_singleton()->save(); } void ProjectManager::_open_project_confirm() { @@ -617,11 +631,6 @@ void ProjectManager::_open_project_confirm() { args.push_back("-editor"); - const String &selected_main = E->get(); - if (selected_main!="") { - args.push_back(selected_main); - } - String exec = OS::get_singleton()->get_executable_path(); OS::ProcessID pid=0; @@ -823,6 +832,19 @@ ProjectManager::ProjectManager() { FileDialog::set_default_show_hidden_files(EditorSettings::get_singleton()->get("file_dialog/show_hidden_files")); set_area_as_parent_rect(); + + Ref<Theme> theme = Ref<Theme>( memnew( Theme ) ); + set_theme(theme); + editor_register_icons(theme); + + String global_font = EditorSettings::get_singleton()->get("global/font"); + if (global_font!="") { + Ref<Font> fnt = ResourceLoader::load(global_font); + if (fnt.is_valid()) { + theme->set_default_theme_font(fnt); + } + } + Panel *panel = memnew( Panel ); add_child(panel); panel->set_area_as_parent_rect(); @@ -839,7 +861,7 @@ ProjectManager::ProjectManager() { l->set_align(Label::ALIGN_CENTER); vb->add_child(l); l = memnew( Label ); - l->set_text("v"VERSION_MKSTRING); + l->set_text("v" VERSION_MKSTRING); //l->add_font_override("font",get_font("bold","Fonts")); l->set_align(Label::ALIGN_CENTER); vb->add_child(l); @@ -970,10 +992,6 @@ ProjectManager::ProjectManager() { npdialog = memnew( NewProjectDialog ); add_child(npdialog); - Ref<Theme> theme = memnew( Theme ); - editor_register_icons(theme); - set_theme(theme); - npdialog->connect("project_created", this,"_load_recent_projects"); _load_recent_projects(); diff --git a/tools/editor/project_manager.h b/tools/editor/project_manager.h index 1e6ea9c1c9..80c34690f8 100644 --- a/tools/editor/project_manager.h +++ b/tools/editor/project_manager.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -85,6 +85,7 @@ class ProjectManager : public Control { protected: + void _notification(int p_what); static void _bind_methods(); public: ProjectManager(); diff --git a/tools/editor/project_settings.cpp b/tools/editor/project_settings.cpp index 25a2750166..b61fcfa780 100644 --- a/tools/editor/project_settings.cpp +++ b/tools/editor/project_settings.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -33,6 +33,7 @@ #include "editor_node.h" #include "scene/gui/margin_container.h" #include "translation.h" +#include "global_constants.h" ProjectSettings *ProjectSettings::singleton=NULL; @@ -59,6 +60,9 @@ void ProjectSettings::_notification(int p_what) { if (p_what==NOTIFICATION_ENTER_TREE) { + search_button->set_icon(get_icon("Zoom","EditorIcons")); + clear_button->set_icon(get_icon("Close","EditorIcons")); + translation_list->connect("button_pressed",this,"_translation_delete"); _update_actions(); popup_add->add_icon_item(get_icon("Keyboard","EditorIcons"),"Key",InputEvent::KEY); @@ -103,6 +107,8 @@ void ProjectSettings::_action_persist_toggle() { String name="input/"+ti->get_text(0); bool prev = Globals::get_singleton()->is_persisting(name); + print_line("prev persist: "+itos(prev)); + print_line("new persist: "+itos(ti->is_checked(0))); if (prev==ti->is_checked(0)) return; @@ -152,12 +158,14 @@ void ProjectSettings::_device_input_add() { } break; case InputEvent::JOYSTICK_MOTION: { - ie.joy_motion.axis = device_index->get_selected(); + ie.joy_motion.axis = device_index->get_selected()>>1; + ie.joy_motion.axis_value = device_index->get_selected()&1?1:-1; + for(int i=0;i<arr.size();i++) { InputEvent aie=arr[i]; - if (aie.device == ie.device && aie.type==InputEvent::JOYSTICK_MOTION && aie.joy_motion.axis==ie.joy_motion.axis) { + if (aie.device == ie.device && aie.type==InputEvent::JOYSTICK_MOTION && aie.joy_motion.axis==ie.joy_motion.axis && aie.joy_motion.axis_value==ie.joy_motion.axis_value) { return; } } @@ -291,9 +299,10 @@ void ProjectSettings::_add_item(int p_item){ device_id->set_val(0); device_index_label->set_text("Joy Button Axis:"); device_index->clear(); - for(int i=0;i<8;i++) { + for(int i=0;i<24;i++) { + - device_index->add_item("Axis "+itos(i)); + device_index->add_item("Axis "+itos(i/2)+" "+(i&1?"+":"-")); } device_input->popup_centered(Size2(350,95)); @@ -335,6 +344,15 @@ void ProjectSettings::_action_button_pressed(Object* p_obj, int p_column,int p_i add_at="input/"+ti->get_text(0); } else if (p_id==2) { + //rename + + add_at="input/"+ti->get_text(0); + rename_action->popup_centered(); + rename_action->get_line_edit()->set_text(ti->get_text(0)); + rename_action->get_line_edit()->set_cursor_pos(ti->get_text(0).length()); + rename_action->get_line_edit()->select_all(); + + } else if (p_id==3) { //remove if (ti->get_parent()==input_editor->get_root()) { @@ -412,13 +430,16 @@ void ProjectSettings::_update_actions() { continue; TreeItem *item=input_editor->create_item(root); - item->set_cell_mode(0,TreeItem::CELL_MODE_CHECK); + //item->set_cell_mode(0,TreeItem::CELL_MODE_CHECK); item->set_text(0,name); item->add_button(0,get_icon("Add","EditorIcons"),1); - item->add_button(0,get_icon("Remove","EditorIcons"),2); + if (!Globals::get_singleton()->get_input_presets().find(pi.name)) { + item->add_button(0,get_icon("Rename","EditorIcons"),2); + item->add_button(0,get_icon("Remove","EditorIcons"),3); + } item->set_custom_bg_color(0,get_color("prop_subsection","Editor")); item->set_editable(0,true); - item->set_checked(0,pi.usage&PROPERTY_USAGE_CHECKED); + //item->set_checked(0,pi.usage&PROPERTY_USAGE_CHECKED); @@ -478,12 +499,12 @@ void ProjectSettings::_update_actions() { } break; case InputEvent::JOYSTICK_MOTION: { - String str = "Device "+itos(ie.device)+", Axis "+itos(ie.joy_motion.axis)+"."; + String str = "Device "+itos(ie.device)+", Axis "+itos(ie.joy_motion.axis)+" "+(ie.joy_motion.axis_value<0?"-.":"+."); action->set_text(0,str); action->set_icon(0,get_icon("JoyAxis","EditorIcons")); } break; } - action->add_button(0,get_icon("Remove","EditorIcons"),2); + action->add_button(0,get_icon("Remove","EditorIcons"),3); action->set_metadata(0,i); } } @@ -504,7 +525,7 @@ void ProjectSettings::popup_project_settings() { void ProjectSettings::_item_selected() { - TreeItem *ti = globals_editor->get_scene_tree()->get_selected(); + TreeItem *ti = globals_editor->get_property_editor()->get_scene_tree()->get_selected(); if (!ti) return; if (!ti->get_parent()) @@ -548,7 +569,7 @@ void ProjectSettings::_item_add() { String name = catname+"/"+propname; Globals::get_singleton()->set(name,value); - globals_editor->update_tree(); + globals_editor->get_property_editor()->update_tree(); } void ProjectSettings::_item_del() { @@ -560,7 +581,7 @@ void ProjectSettings::_item_del() { String name = catname+"/"+propname; Globals::get_singleton()->set(name,Variant()); - globals_editor->update_tree(); + globals_editor->get_property_editor()->update_tree(); } @@ -613,14 +634,57 @@ void ProjectSettings::_action_add() { } +void ProjectSettings::_action_rename(const String &p_name) { + + + if (p_name.find("/")!=-1 || p_name.find(":")!=-1 || p_name=="") { + message->set_text("Invalid Action (Anything goes but / or :)."); + message->popup_centered(Size2(300,100)); + return; + } + + String new_name = "input/"+p_name; + + if (Globals::get_singleton()->has(new_name)) { + message->set_text("Action '"+p_name+"' already exists!."); + message->popup_centered(Size2(300,100)); + return; + } + + int order = Globals::get_singleton()->get_order(add_at); + Array va = Globals::get_singleton()->get(add_at); + bool persisting = Globals::get_singleton()->is_persisting(add_at); + + undo_redo->create_action("Rename Input Action Event"); + undo_redo->add_do_method(Globals::get_singleton(),"clear",add_at); + undo_redo->add_do_method(Globals::get_singleton(),"set",new_name,va); + undo_redo->add_do_method(Globals::get_singleton(),"set_persisting",new_name,persisting); + undo_redo->add_do_method(Globals::get_singleton(),"set_order",new_name,order); + undo_redo->add_undo_method(Globals::get_singleton(),"clear",new_name); + undo_redo->add_undo_method(Globals::get_singleton(),"set",add_at,va); + undo_redo->add_undo_method(Globals::get_singleton(),"set_persisting",add_at,persisting); + undo_redo->add_undo_method(Globals::get_singleton(),"set_order",add_at,order); + undo_redo->add_do_method(this,"_update_actions"); + undo_redo->add_undo_method(this,"_update_actions"); + undo_redo->add_do_method(this,"_settings_changed"); + undo_redo->add_undo_method(this,"_settings_changed"); + undo_redo->commit_action(); + + rename_action->hide(); +} + void ProjectSettings::_item_checked(const String& p_item, bool p_check) { undo_redo->create_action("Toggle Persisting"); - undo_redo->add_do_method(Globals::get_singleton(),"set_persisting",p_item,p_check); - undo_redo->add_undo_method(Globals::get_singleton(),"set_persisting",p_item,!p_check); + String full_item = globals_editor->get_full_item_path(p_item); + + undo_redo->add_do_method(Globals::get_singleton(),"set_persisting",full_item,p_check); + undo_redo->add_undo_method(Globals::get_singleton(),"set_persisting",full_item,!p_check); undo_redo->add_do_method(this,"_settings_changed"); undo_redo->add_undo_method(this,"_settings_changed"); + undo_redo->add_do_method(globals_editor->get_property_editor(),"update_tree"); + undo_redo->add_undo_method(globals_editor->get_property_editor(),"update_tree"); undo_redo->commit_action(); } @@ -637,11 +701,22 @@ void ProjectSettings::_save() { void ProjectSettings::_settings_prop_edited(const String& p_name) { - if (!Globals::get_singleton()->is_persisting(p_name)) { + String full_item = globals_editor->get_full_item_path(p_name); + + if (!Globals::get_singleton()->is_persisting(full_item)) { + Globals::get_singleton()->set_persisting(full_item,true); + + { + //small usability workaround, if anything related to resolution scaling or size is modified, change all of them together + if (full_item=="display/width" || full_item=="display/height" || full_item=="display/stretch_mode") { + Globals::get_singleton()->set_persisting("display/height",true); + Globals::get_singleton()->set_persisting("display/width",true); + } + } + - Globals::get_singleton()->set_persisting(p_name,true); // globals_editor->update_property(p_name); - globals_editor->update_tree(); + globals_editor->get_property_editor()->update_tree(); } _settings_changed(); } @@ -676,7 +751,7 @@ void ProjectSettings::_copy_to_platform(int p_which) { name = catname+"/"+propname; Globals::get_singleton()->set(name,value); - globals_editor->update_tree(); + globals_editor->get_property_editor()->update_tree(); } @@ -719,6 +794,11 @@ void ProjectSettings::_translation_file_open() { void ProjectSettings::_autoload_file_callback(const String& p_path) { autoload_add_path->set_text(p_path); + //if (autoload_add_name->get_text().strip_edges()==String()) { + + autoload_add_name->set_text( p_path.get_file().basename() ); + //} + //_translation_add(p_translation); } @@ -727,6 +807,40 @@ void ProjectSettings::_autoload_file_open() { autoload_file_open->popup_centered_ratio(); } +void ProjectSettings::_autoload_edited() { + + if (updating_autoload) + return; + + TreeItem *ti = autoload_list->get_edited(); + if (!ti || autoload_list->get_edited_column()!=2) + return; + + updating_autoload=true; + bool checked=ti->is_checked(2); + + String base="autoload/"+ti->get_text(0); + + String path = Globals::get_singleton()->get(base); + + if (path.begins_with("*")) + path=path.substr(1,path.length()); + + if (checked) + path="*"+path; + + undo_redo->create_action("Toggle Autoload GlobalVar"); + undo_redo->add_do_property(Globals::get_singleton(),base,path); + undo_redo->add_undo_property(Globals::get_singleton(),base,Globals::get_singleton()->get(base)); + undo_redo->add_do_method(this,"_update_autoload"); + undo_redo->add_undo_method(this,"_update_autoload"); + undo_redo->add_do_method(this,"_settings_changed"); + undo_redo->add_undo_method(this,"_settings_changed"); + undo_redo->commit_action(); + updating_autoload=false; + +} + void ProjectSettings::_autoload_add() { String name = autoload_add_name->get_text(); @@ -737,6 +851,35 @@ void ProjectSettings::_autoload_add() { } + if (ObjectTypeDB::type_exists(name)) { + + message->set_text("Invalid Name.Must not collide with an existing engine class name."); + message->popup_centered(Size2(300,100)); + return; + + } + + for(int i=0;i<Variant::VARIANT_MAX;i++) { + if (Variant::get_type_name(Variant::Type(i))==name) { + + message->set_text("Invalid Name.Must not collide with an existing buit-in type name."); + message->popup_centered(Size2(300,100)); + return; + + } + } + + for(int i=0;i<GlobalConstants::get_global_constant_count();i++) { + + if (GlobalConstants::get_global_constant_name(i)==name) { + + message->set_text("Invalid Name.Must not collide with an existing global constant name."); + message->popup_centered(Size2(300,100)); + return; + } + + } + String path = autoload_add_path->get_text(); if (!FileAccess::exists(path)) { message->set_text("Invalid Path.\nFile does not exist."); @@ -753,7 +896,7 @@ void ProjectSettings::_autoload_add() { undo_redo->create_action("Add Autoload"); name = "autoload/"+name; - undo_redo->add_do_property(Globals::get_singleton(),name,path); + undo_redo->add_do_property(Globals::get_singleton(),name,"*"+path); if (Globals::get_singleton()->has(name)) undo_redo->add_undo_property(Globals::get_singleton(),name,Globals::get_singleton()->get(name)); else @@ -766,6 +909,9 @@ void ProjectSettings::_autoload_add() { undo_redo->add_undo_method(this,"_settings_changed"); undo_redo->commit_action(); + autoload_add_path->set_text(""); + autoload_add_name->set_text(""); + //autoload_file_open->popup_centered_ratio(); } @@ -800,11 +946,14 @@ void ProjectSettings::_autoload_delete(Object *p_item,int p_column, int p_button String swap_name= "autoload/"+swap->get_text(0); + int order = Globals::get_singleton()->get_order(name); + int swap_order = Globals::get_singleton()->get_order(swap_name); + undo_redo->create_action("Move Autoload"); - undo_redo->add_do_method(Globals::get_singleton(),"set_order",swap_name,Globals::get_singleton()->get_order(name)); - undo_redo->add_do_method(Globals::get_singleton(),"set_order",name,Globals::get_singleton()->get_order(swap_name)); - undo_redo->add_undo_method(Globals::get_singleton(),"set_order",swap_name,Globals::get_singleton()->get_order(swap_name)); - undo_redo->add_undo_method(Globals::get_singleton(),"set_order",name,Globals::get_singleton()->get_order(name)); + undo_redo->add_do_method(Globals::get_singleton(),"set_order",swap_name,order); + undo_redo->add_do_method(Globals::get_singleton(),"set_order",name,swap_order); + undo_redo->add_undo_method(Globals::get_singleton(),"set_order",swap_name,swap_order); + undo_redo->add_undo_method(Globals::get_singleton(),"set_order",name,order); undo_redo->add_do_method(this,"_update_autoload"); undo_redo->add_undo_method(this,"_update_autoload"); undo_redo->add_do_method(this,"_settings_changed"); @@ -1143,6 +1292,11 @@ void ProjectSettings::_update_translations() { void ProjectSettings::_update_autoload() { + if (updating_autoload) + return; + + updating_autoload=true; + autoload_list->clear(); TreeItem *root = autoload_list->create_item(); autoload_list->set_hide_root(true); @@ -1157,20 +1311,58 @@ void ProjectSettings::_update_autoload() { continue; String name = pi.name.get_slice("/",1); + String path = Globals::get_singleton()->get(pi.name); + if (name=="") continue; - + bool global=false; + if (path.begins_with("*")) { + path=path.substr(1,path.length()); + global=true; + } TreeItem *t = autoload_list->create_item(root); t->set_text(0,name); - t->set_text(1,Globals::get_singleton()->get(pi.name)); - t->add_button(1,get_icon("MoveUp","EditorIcons"),1); - t->add_button(1,get_icon("MoveDown","EditorIcons"),2); - t->add_button(1,get_icon("Del","EditorIcons"),0); + t->set_text(1,path); + t->set_cell_mode(2,TreeItem::CELL_MODE_CHECK); + t->set_editable(2,true); + t->set_text(2,"Enable"); + t->set_checked(2,global); + t->add_button(3,get_icon("MoveUp","EditorIcons"),1); + t->add_button(3,get_icon("MoveDown","EditorIcons"),2); + t->add_button(3,get_icon("Del","EditorIcons"),0); + } + updating_autoload=false; + } +void ProjectSettings::_toggle_search_bar(bool p_pressed) { + + globals_editor->get_property_editor()->set_use_filter(p_pressed); + + if (p_pressed) { + + search_bar->show(); + add_prop_bar->hide(); + search_box->grab_focus(); + search_box->select_all(); + } else { + + search_bar->hide(); + add_prop_bar->show(); + } +} + +void ProjectSettings::_clear_search_box() { + + if (search_box->get_text()=="") + return; + + search_box->clear(); + globals_editor->get_property_editor()->update_tree(); +} void ProjectSettings::_bind_methods() { @@ -1184,6 +1376,7 @@ void ProjectSettings::_bind_methods() { ObjectTypeDB::bind_method(_MD("_action_adds"),&ProjectSettings::_action_adds); ObjectTypeDB::bind_method(_MD("_action_persist_toggle"),&ProjectSettings::_action_persist_toggle); ObjectTypeDB::bind_method(_MD("_action_button_pressed"),&ProjectSettings::_action_button_pressed); + ObjectTypeDB::bind_method(_MD("_action_rename"),&ProjectSettings::_action_rename); ObjectTypeDB::bind_method(_MD("_update_actions"),&ProjectSettings::_update_actions); ObjectTypeDB::bind_method(_MD("_wait_for_key"),&ProjectSettings::_wait_for_key); ObjectTypeDB::bind_method(_MD("_add_item"),&ProjectSettings::_add_item); @@ -1211,6 +1404,10 @@ void ProjectSettings::_bind_methods() { ObjectTypeDB::bind_method(_MD("_autoload_file_callback"),&ProjectSettings::_autoload_file_callback); ObjectTypeDB::bind_method(_MD("_update_autoload"),&ProjectSettings::_update_autoload); ObjectTypeDB::bind_method(_MD("_autoload_delete"),&ProjectSettings::_autoload_delete); + ObjectTypeDB::bind_method(_MD("_autoload_edited"),&ProjectSettings::_autoload_edited); + + ObjectTypeDB::bind_method(_MD("_clear_search_box"),&ProjectSettings::_clear_search_box); + ObjectTypeDB::bind_method(_MD("_toggle_search_bar"),&ProjectSettings::_toggle_search_bar); } @@ -1232,87 +1429,93 @@ ProjectSettings::ProjectSettings(EditorData *p_data) { //tab_container->set_anchor_and_margin(MARGIN_TOP,ANCHOR_BEGIN, 15 ); //tab_container->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_END, 35 ); - Control *props_base = memnew( Control ); + VBoxContainer *props_base = memnew( VBoxContainer ); + props_base->set_alignment(BoxContainer::ALIGN_BEGIN); + props_base->set_v_size_flags(Control::SIZE_EXPAND_FILL); tab_container->add_child(props_base); props_base->set_name("General"); - globals_editor = memnew( PropertyEditor ); - props_base->add_child(globals_editor); - globals_editor->set_area_as_parent_rect(); - globals_editor->hide_top_label(); - globals_editor->set_anchor_and_margin(MARGIN_TOP,ANCHOR_BEGIN, 55 ); - globals_editor->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_END, 35 ); - globals_editor->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_BEGIN, 5 ); - globals_editor->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END, 5 ); - globals_editor->set_capitalize_paths(false); - globals_editor->get_scene_tree()->connect("cell_selected",this,"_item_selected"); - globals_editor->connect("property_toggled",this,"_item_checked"); - globals_editor->connect("property_edited",this,"_settings_prop_edited"); + HBoxContainer *hbc = memnew( HBoxContainer ); + hbc->set_h_size_flags(Control::SIZE_EXPAND_FILL); + props_base->add_child(hbc); - Label *l = memnew( Label ); - props_base->add_child(l); - l->set_pos(Point2(6,5)); - l->set_text("Category:"); + search_button = memnew( ToolButton ); + search_button->set_toggle_mode(true); + search_button->set_pressed(false); + search_button->set_text("Search"); + hbc->add_child(search_button); + search_button->connect("toggled",this,"_toggle_search_bar"); + hbc->add_child( memnew( VSeparator ) ); - l = memnew( Label ); - l->set_anchor(MARGIN_LEFT,ANCHOR_RATIO); - props_base->add_child(l); - l->set_begin(Point2(0.21,5)); - l->set_text("Property:"); + add_prop_bar = memnew( HBoxContainer ); + add_prop_bar->set_h_size_flags(Control::SIZE_EXPAND_FILL); + hbc->add_child(add_prop_bar); - l = memnew( Label ); - l->set_anchor(MARGIN_LEFT,ANCHOR_RATIO); - props_base->add_child(l); - l->set_begin(Point2(0.51,5)); - l->set_text("Type:"); + Label *l = memnew( Label ); + add_prop_bar->add_child(l); + l->set_text("Category:"); category = memnew( LineEdit ); - props_base->add_child(category); - category->set_anchor(MARGIN_RIGHT,ANCHOR_RATIO); - category->set_begin( Point2(5,25) ); - category->set_end( Point2(0.20,26) ); + category->set_h_size_flags(Control::SIZE_EXPAND_FILL); + add_prop_bar->add_child(category); category->connect("text_entered",this,"_item_adds"); + l = memnew( Label ); + add_prop_bar->add_child(l); + l->set_text("Property:"); + property = memnew( LineEdit ); - props_base->add_child(property); - property->set_anchor(MARGIN_LEFT,ANCHOR_RATIO); - property->set_anchor(MARGIN_RIGHT,ANCHOR_RATIO); - property->set_begin( Point2(0.21,25) ); - property->set_end( Point2(0.50,26) ); + property->set_h_size_flags(Control::SIZE_EXPAND_FILL); + add_prop_bar->add_child(property); property->connect("text_entered",this,"_item_adds"); + l = memnew( Label ); + add_prop_bar->add_child(l); + l->set_text("Type:"); type = memnew( OptionButton ); - props_base->add_child(type); - type->set_anchor(MARGIN_LEFT,ANCHOR_RATIO); - type->set_anchor(MARGIN_RIGHT,ANCHOR_RATIO); - type->set_begin( Point2(0.51,25) ); - type->set_end( Point2(0.70,26) ); + type->set_h_size_flags(Control::SIZE_EXPAND_FILL); + add_prop_bar->add_child(type); type->add_item("bool"); type->add_item("int"); type->add_item("float"); type->add_item("string"); Button *add = memnew( Button ); - props_base->add_child(add); - add->set_anchor(MARGIN_LEFT,ANCHOR_RATIO); - add->set_anchor(MARGIN_RIGHT,ANCHOR_RATIO); - add->set_begin( Point2(0.71,25) ); - add->set_end( Point2(0.85,26) ); + add_prop_bar->add_child(add); add->set_text("Add"); add->connect("pressed",this,"_item_add"); Button *del = memnew( Button ); - props_base->add_child(del); - del->set_anchor(MARGIN_LEFT,ANCHOR_RATIO); - del->set_anchor(MARGIN_RIGHT,ANCHOR_END); - del->set_begin( Point2(0.86,25) ); - del->set_end( Point2(5,26) ); + add_prop_bar->add_child(del); del->set_text("Del"); del->connect("pressed",this,"_item_del"); - /* + search_bar = memnew( HBoxContainer ); + search_bar->set_h_size_flags(Control::SIZE_EXPAND_FILL); + hbc->add_child(search_bar); + search_bar->hide(); + + search_box = memnew( LineEdit ); + search_box->set_h_size_flags(Control::SIZE_EXPAND_FILL); + search_bar->add_child(search_box); + + clear_button = memnew( ToolButton ); + search_bar->add_child(clear_button); + clear_button->connect("pressed",this,"_clear_search_box"); + + globals_editor = memnew( SectionedPropertyEditor ); + props_base->add_child(globals_editor); + //globals_editor->hide_top_label(); + globals_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL); + globals_editor->get_property_editor()->register_text_enter(search_box); + globals_editor->get_property_editor()->set_capitalize_paths(false); + globals_editor->get_property_editor()->get_scene_tree()->connect("cell_selected",this,"_item_selected"); + globals_editor->get_property_editor()->connect("property_toggled",this,"_item_checked",varray(),CONNECT_DEFERRED); + globals_editor->get_property_editor()->connect("property_edited",this,"_settings_prop_edited"); + +/* Button *save = memnew( Button ); props_base->add_child(save); @@ -1325,17 +1528,16 @@ ProjectSettings::ProjectSettings(EditorData *p_data) { save->set_text("Save"); save->connect("pressed",this,"_save"); */ + + hbc = memnew( HBoxContainer ); + props_base->add_child(hbc); + popup_platform = memnew( MenuButton ); popup_platform->set_text("Copy To Platform.."); popup_platform->set_disabled(true); - props_base->add_child(popup_platform); + hbc->add_child(popup_platform); - popup_platform->set_anchor(MARGIN_LEFT,ANCHOR_BEGIN); - popup_platform->set_anchor(MARGIN_RIGHT,ANCHOR_BEGIN); - popup_platform->set_anchor(MARGIN_TOP,ANCHOR_END); - popup_platform->set_anchor(MARGIN_BOTTOM,ANCHOR_END); - popup_platform->set_begin( Point2(10,28) ); - popup_platform->set_end( Point2(150,20) ); + hbc->add_spacer(); List<StringName> ep; EditorImportExport::get_singleton()->get_export_platforms(&ep); @@ -1395,12 +1597,17 @@ ProjectSettings::ProjectSettings(EditorData *p_data) { add_child(popup_add); popup_add->connect("item_pressed",this,"_add_item"); + rename_action = memnew( EditorNameDialog ); + add_child(rename_action); + rename_action->set_hide_on_ok(false); + rename_action->set_size(Size2(200, 70)); + rename_action->set_title("Rename Input Action"); + rename_action->connect("name_confirmed", this,"_action_rename"); + press_a_key = memnew( ConfirmationDialog ); press_a_key->set_focus_mode(FOCUS_ALL); add_child(press_a_key); - - l = memnew( Label ); l->set_text("Press a Key.."); l->set_area_as_parent_rect(); @@ -1553,11 +1760,6 @@ ProjectSettings::ProjectSettings(EditorData *p_data) { HBoxContainer *ahb = memnew( HBoxContainer); avb->add_child(ahb); - VBoxContainer *avb_name = memnew( VBoxContainer ); - avb_name->set_h_size_flags(SIZE_EXPAND_FILL); - autoload_add_name = memnew(LineEdit); - avb_name->add_margin_child("Node Name:",autoload_add_name); - ahb->add_child(avb_name); VBoxContainer *avb_path = memnew( VBoxContainer ); avb_path->set_h_size_flags(SIZE_EXPAND_FILL); @@ -1568,13 +1770,24 @@ ProjectSettings::ProjectSettings(EditorData *p_data) { Button *browseaa = memnew( Button("..") ); ahb_path->add_child(browseaa); browseaa->connect("pressed",this,"_autoload_file_open"); - Button *addaa = memnew( Button("Add") ); - ahb_path->add_child(addaa); - addaa->connect("pressed",this,"_autoload_add"); avb_path->add_margin_child("Path:",ahb_path); ahb->add_child(avb_path); + VBoxContainer *avb_name = memnew( VBoxContainer ); + avb_name->set_h_size_flags(SIZE_EXPAND_FILL); + + HBoxContainer *ahb_name = memnew( HBoxContainer ); + autoload_add_name = memnew(LineEdit); + autoload_add_name->set_h_size_flags(SIZE_EXPAND_FILL); + ahb_name->add_child(autoload_add_name); + avb_name->add_margin_child("Node Name:",ahb_name); + Button *addaa = memnew( Button("Add") ); + ahb_name->add_child(addaa); + addaa->connect("pressed",this,"_autoload_add"); + + ahb->add_child(avb_name); + autoload_list = memnew( Tree ); autoload_list->set_v_size_flags(SIZE_EXPAND_FILL); avb->add_margin_child("List:",autoload_list,true); @@ -1584,11 +1797,24 @@ ProjectSettings::ProjectSettings(EditorData *p_data) { autoload_file_open->set_mode(EditorFileDialog::MODE_OPEN_FILE); autoload_file_open->connect("file_selected",this,"_autoload_file_callback"); - autoload_list->set_columns(2); + autoload_list->set_columns(4); autoload_list->set_column_titles_visible(true); - autoload_list->set_column_title(0,"name"); - autoload_list->set_column_title(1,"path"); + autoload_list->set_column_title(0,"Name"); + autoload_list->set_column_expand(0,true); + autoload_list->set_column_min_width(0,100); + autoload_list->set_column_title(1,"Path"); + autoload_list->set_column_expand(1,true); + autoload_list->set_column_min_width(1,100); + autoload_list->set_column_title(2,"Singleton"); + autoload_list->set_column_expand(2,false); + autoload_list->set_column_min_width(2,80); + autoload_list->set_column_expand(3,false); + autoload_list->set_column_min_width(3,80); + autoload_list->connect("button_pressed",this,"_autoload_delete"); + autoload_list->connect("item_edited",this,"_autoload_edited"); + + updating_autoload=false; } diff --git a/tools/editor/project_settings.h b/tools/editor/project_settings.h index 7c91254764..b689340fdf 100644 --- a/tools/editor/project_settings.h +++ b/tools/editor/project_settings.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -34,6 +34,7 @@ #include "optimized_save_dialog.h" #include "undo_redo.h" #include "editor_data.h" +#include "editor_name_dialog.h" //#include "project_export_settings.h" class ProjectSettings : public AcceptDialog { @@ -45,8 +46,14 @@ class ProjectSettings : public AcceptDialog { EditorData *data; UndoRedo *undo_redo; - PropertyEditor *globals_editor; + SectionedPropertyEditor *globals_editor; + HBoxContainer *search_bar; + ToolButton *search_button; + LineEdit *search_box; + ToolButton *clear_button; + + HBoxContainer *add_prop_bar; ConfirmationDialog *message; LineEdit *category; LineEdit *property; @@ -60,6 +67,8 @@ class ProjectSettings : public AcceptDialog { Label *device_index_label; MenuButton *popup_platform; + EditorNameDialog *rename_action; + LineEdit *action_name; Tree *input_editor; bool setting; @@ -86,8 +95,10 @@ class ProjectSettings : public AcceptDialog { void _update_autoload(); void _autoload_file_callback(const String& p_path); void _autoload_add(); + void _autoload_edited(); void _autoload_file_open(); void _autoload_delete(Object *p_item,int p_column, int p_button); + bool updating_autoload; void _item_selected(); @@ -100,6 +111,7 @@ class ProjectSettings : public AcceptDialog { void _action_adds(String); void _action_add(); + void _action_rename(const String& p_name); void _device_input_add(); void _item_checked(const String& p_item, bool p_check); @@ -130,6 +142,9 @@ class ProjectSettings : public AcceptDialog { void _translation_res_option_changed(); void _translation_res_option_delete(Object *p_item,int p_column, int p_button); + void _toggle_search_bar(bool p_pressed); + void _clear_search_box(); + ProjectSettings(); diff --git a/tools/editor/property_editor.cpp b/tools/editor/property_editor.cpp index 549a3f7ffb..fc5fce1d47 100644 --- a/tools/editor/property_editor.cpp +++ b/tools/editor/property_editor.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -89,13 +89,23 @@ void CustomPropertyEditor::_menu_option(int p_which) { case OBJ_MENU_LOAD: { file->set_mode(EditorFileDialog::MODE_OPEN_FILE); - List<String> extensions; String type=(hint==PROPERTY_HINT_RESOURCE_TYPE)?hint_text:String(); - ResourceLoader::get_recognized_extensions_for_type(type,&extensions); - file->clear_filters(); + List<String> extensions; + for (int i=0;i<type.get_slice_count(",");i++) { + + ResourceLoader::get_recognized_extensions_for_type(type.get_slice(",",i),&extensions); + } + + Set<String> valid_extensions; for (List<String>::Element *E=extensions.front();E;E=E->next()) { + valid_extensions.insert(E->get()); + } + + file->clear_filters(); + for (Set<String>::Element *E=valid_extensions.front();E;E=E->next()) { + file->add_filter("*."+E->get()+" ; "+E->get().to_upper() ); } @@ -905,19 +915,31 @@ void CustomPropertyEditor::_color_changed(const Color& p_color) { void CustomPropertyEditor::_node_path_selected(NodePath p_path) { - if (owner && owner->is_type("Node")) { + if (owner) { + + Node *node=NULL; + + if (owner->is_type("Node")) + node = owner->cast_to<Node>(); + else if (owner->is_type("ArrayPropertyEdit")) + node = owner->cast_to<ArrayPropertyEdit>()->get_node(); + + if (!node) { + v=p_path; + emit_signal("variant_changed"); + call_deferred("hide"); //to not mess with dialogs + return; + } - Node *node = owner->cast_to<Node>(); Node *tonode=node->get_node(p_path); if (tonode) { - p_path=node->get_path_to(tonode); } - } v=p_path; emit_signal("variant_changed"); + call_deferred("hide"); //to not mess with dialogs } @@ -1020,6 +1042,7 @@ void CustomPropertyEditor::_action_pressed(int p_which) { v=NodePath(); emit_signal("variant_changed"); + hide(); } } break; case Variant::OBJECT: { @@ -1361,7 +1384,7 @@ void CustomPropertyEditor::_modified(String p_string) { } break; case Variant::MATRIX32: { - Matrix3 m; + Matrix32 m; for(int i=0;i<6;i++) { m.elements[i/2][i%2]=value_editor[i]->get_text().to_double(); @@ -2090,6 +2113,65 @@ void PropertyEditor::set_item_text(TreeItem *p_item, int p_type, const String& p } +void PropertyEditor::_check_reload_status(const String&p_name, TreeItem* item) { + + bool has_reload=false; + int found=-1; + + for(int i=0;i<item->get_button_count(1);i++) { + + if (item->get_button_id(1,i)==3) { + found=i; + break; + } + } + + if (_might_be_in_instance()) { + + + Variant vorig; + Dictionary d=item->get_metadata(0); + int usage = d.has("usage")?int(int(d["usage"])&(PROPERTY_USAGE_STORE_IF_NONONE|PROPERTY_USAGE_STORE_IF_NONZERO)):0; + + + if (_get_instanced_node_original_property(p_name,vorig) || usage) { + Variant v = obj->get(p_name); + + bool changed = _is_property_different(v,vorig,usage); + + if ((found!=-1)!=changed) { + + if (changed) { + + has_reload=true; + } else { + + } + + } + + } + + + + } + + if (!has_reload && !obj->get_script().is_null()) { + Ref<Script> scr = obj->get_script(); + Variant orig_value; + if (scr->get_property_default_value(p_name,orig_value)) { + if (orig_value!=obj->get(p_name)) { + has_reload=true; + } + } + } + + if (found!=-1 && !has_reload) { + item->erase_button(1,found); + } else if (found==-1 && has_reload) { + item->add_button(1,get_icon("Reload","EditorIcons"),3); + } +} void PropertyEditor::_notification(int p_what) { @@ -2131,43 +2213,8 @@ void PropertyEditor::_notification(int p_what) { if (!item) continue; - if (_might_be_in_instance()) { + _check_reload_status(*k,item); - - Variant vorig; - Dictionary d=item->get_metadata(0); - int usage = d.has("usage")?int(int(d["usage"])&(PROPERTY_USAGE_STORE_IF_NONONE|PROPERTY_USAGE_STORE_IF_NONZERO)):0; - - - if (_get_instanced_node_original_property(*k,vorig) || usage) { - Variant v = obj->get(*k); - - int found=-1; - for(int i=0;i<item->get_button_count(1);i++) { - - if (item->get_button_id(1,i)==3) { - found=i; - break; - } - } - - bool changed = _is_property_different(v,vorig,usage); - - if ((found!=-1)!=changed) { - - if (changed) { - - item->add_button(1,get_icon("Reload","EditorIcons"),3); - } else { - - item->erase_button(1,found); - } - - } - - } - - } Dictionary d=item->get_metadata(0); set_item_text(item,d["type"],d["name"],d["hint"],d["hint_text"]); } @@ -2207,9 +2254,9 @@ TreeItem *PropertyEditor::get_parent_node(String p_path,HashMap<String,TreeItem* } item->set_editable(0,false); - item->set_selectable(0,false); + item->set_selectable(0,subsection_selectable); item->set_editable(1,false); - item->set_selectable(1,false); + item->set_selectable(1,subsection_selectable); if (item->get_parent()==root) { @@ -2234,23 +2281,30 @@ void PropertyEditor::_refresh_item(TreeItem *p_item) { if (name!=String()) { + + _check_reload_status(name,p_item); +#if 0 + bool has_reload=false; + + int found=-1; + for(int i=0;i<p_item->get_button_count(1);i++) { + + if (p_item->get_button_id(1,i)==3) { + found=i; + break; + } + } + if (_might_be_in_instance()) { Variant vorig; Dictionary d=p_item->get_metadata(0); int usage = d.has("usage")?int(int(d["usage"])&(PROPERTY_USAGE_STORE_IF_NONONE|PROPERTY_USAGE_STORE_IF_NONZERO)):0; + if (_get_instanced_node_original_property(name,vorig) || usage) { Variant v = obj->get(name); - int found=-1; - for(int i=0;i<p_item->get_button_count(1);i++) { - - if (p_item->get_button_id(1,i)==3) { - found=i; - break; - } - } bool changed = _is_property_different(v,vorig,usage); @@ -2258,10 +2312,11 @@ void PropertyEditor::_refresh_item(TreeItem *p_item) { if (changed) { - p_item->add_button(1,get_icon("Reload","EditorIcons"),3); + has_reload=true; + } else { - p_item->erase_button(1,found); + //p_item->erase_button(1,found); } } @@ -2270,6 +2325,22 @@ void PropertyEditor::_refresh_item(TreeItem *p_item) { } + if (!has_reload && !obj->get_script().is_null()) { + Ref<Script> scr = obj->get_script(); + Variant orig_value; + if (scr->get_property_default_value(name,orig_value)) { + if (orig_value!=obj->get(name)) { + has_reload=true; + } + } + } + + if (!has_reload && found!=-1) { + p_item->erase_button(1,found); + } else if (has_reload && found==-1) { + p_item->add_button(1,get_icon("Reload","EditorIcons"),3); + } +#endif Dictionary d=p_item->get_metadata(0); set_item_text(p_item,d["type"],d["name"],d["hint"],d["hint_text"]); } @@ -2363,6 +2434,8 @@ void PropertyEditor::update_tree() { TreeItem * current_category=NULL; + String filter = search_box ? search_box->get_text() : ""; + for (List<PropertyInfo>::Element *I=plist.front() ; I ; I=I->next()) { PropertyInfo& p = I->get(); @@ -2426,7 +2499,24 @@ void PropertyEditor::update_tree() { } else if ( ! (p.usage&PROPERTY_USAGE_EDITOR ) ) continue; + String name = (p.name.find("/")!=-1)?p.name.right( p.name.find_last("/")+1 ):p.name; + + if (capitalize_paths) + name = name.camelcase_to_underscore().capitalize(); + String path=p.name.left( p.name.find_last("/") ) ; + + if (use_filter && filter!="") { + + String cat = path; + + if (capitalize_paths) + cat = cat.capitalize(); + + if (cat.findn(filter)==-1 && name.findn(filter)==-1) + continue; + } + //printf("property %s\n",p.name.ascii().get_data()); TreeItem * parent = get_parent_node(path,item_path,current_category?current_category:root ); //if (parent->get_parent()==root) @@ -2448,8 +2538,6 @@ void PropertyEditor::update_tree() { TreeItem * item = tree->create_item( parent ); - String name = (p.name.find("/")!=-1)?p.name.right( p.name.find_last("/")+1 ):p.name; - if (level>0) { item->set_custom_bg_color(0,col); //item->set_custom_bg_color(1,col); @@ -2465,11 +2553,7 @@ void PropertyEditor::update_tree() { item->set_checked(0,p.usage&PROPERTY_USAGE_CHECKED); } - if (capitalize_paths) - item->set_text( 0, name.camelcase_to_underscore().capitalize() ); - else - item->set_text( 0, name ); - + item->set_text(0, name); item->set_tooltip(0, p.name); if (use_doc_hints) { @@ -2536,7 +2620,8 @@ void PropertyEditor::update_tree() { item->set_cell_mode( 1, TreeItem::CELL_MODE_CHECK ); item->set_text(1,"On"); item->set_checked( 1, obj->get( p.name ) ); - item->set_icon( 0, get_icon("Bool","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0, get_icon("Bool","EditorIcons") ); item->set_editable(1,!read_only); } break; @@ -2548,7 +2633,8 @@ void PropertyEditor::update_tree() { item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM ); item->set_text(1, String::num(obj->get( p.name ),2) ); item->set_editable(1,!read_only); - item->set_icon( 0, get_icon("Curve","EditorIcons")); + if (show_type_icons) + item->set_icon( 0, get_icon("Curve","EditorIcons")); break; @@ -2618,7 +2704,8 @@ void PropertyEditor::update_tree() { // int c = p.hint_string.get_slice_count(","); item->set_text(1,p.hint_string); - item->set_icon( 0,get_icon("Enum","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0,get_icon("Enum","EditorIcons") ); item->set_range(1, obj->get( p.name ) ); item->set_editable(1,!read_only); break; @@ -2634,11 +2721,13 @@ void PropertyEditor::update_tree() { }; if (p.type==Variant::REAL) { - item->set_icon( 0, get_icon("Real","EditorIcons")); + if (show_type_icons) + item->set_icon( 0, get_icon("Real","EditorIcons")); item->set_range(1, obj->get( p.name ) ); } else { - item->set_icon( 0,get_icon("Integer","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0,get_icon("Integer","EditorIcons") ); item->set_range(1, obj->get( p.name ) ); } @@ -2658,7 +2747,8 @@ void PropertyEditor::update_tree() { item->set_cell_mode( 1, TreeItem::CELL_MODE_STRING ); item->set_editable(1,!read_only); - item->set_icon( 0, get_icon("File","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0, get_icon("File","EditorIcons") ); item->set_text(1,obj->get(p.name)); item->add_button(1,get_icon("Folder","EditorIcons")); @@ -2678,7 +2768,8 @@ void PropertyEditor::update_tree() { item->set_text(1, p.hint_string); item->set_range(1,idx); item->set_editable( 1, !read_only ); - item->set_icon( 0,get_icon("Enum","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0,get_icon("Enum","EditorIcons") ); } break; @@ -2686,7 +2777,8 @@ void PropertyEditor::update_tree() { item->set_cell_mode( 1, TreeItem::CELL_MODE_STRING ); item->set_editable(1,!read_only); - item->set_icon( 0, get_icon("String","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0, get_icon("String","EditorIcons") ); item->set_text(1,obj->get(p.name)); if (p.hint==PROPERTY_HINT_MULTILINE_TEXT) item->add_button(1,get_icon("MultiLine","EditorIcons") ); @@ -2706,7 +2798,8 @@ void PropertyEditor::update_tree() { item->set_text(1,"Array["+itos(v.call("size"))+"]"); else item->set_text(1,"Array[]"); - item->set_icon( 0, get_icon("ArrayData","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0, get_icon("ArrayData","EditorIcons") ); } break; @@ -2721,7 +2814,8 @@ void PropertyEditor::update_tree() { item->set_text(1,"IntArray["+itos(v.call("size"))+"]"); else item->set_text(1,"IntArray[]"); - item->set_icon( 0, get_icon("ArrayInt","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0, get_icon("ArrayInt","EditorIcons") ); } break; @@ -2735,7 +2829,8 @@ void PropertyEditor::update_tree() { item->set_text(1,"FloatArray["+itos(v.call("size"))+"]"); else item->set_text(1,"FloatArray[]"); - item->set_icon( 0, get_icon("ArrayReal","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0, get_icon("ArrayReal","EditorIcons") ); } break; @@ -2749,7 +2844,8 @@ void PropertyEditor::update_tree() { item->set_text(1,"String["+itos(v.call("size"))+"]"); else item->set_text(1,"String[]"); - item->set_icon( 0, get_icon("ArrayString","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0, get_icon("ArrayString","EditorIcons") ); } break; @@ -2763,7 +2859,8 @@ void PropertyEditor::update_tree() { item->set_text(1,"Byte["+itos(v.call("size"))+"]"); else item->set_text(1,"Byte[]"); - item->set_icon( 0, get_icon("ArrayData","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0, get_icon("ArrayData","EditorIcons") ); } break; @@ -2777,7 +2874,8 @@ void PropertyEditor::update_tree() { item->set_text(1,"Vector2["+itos(v.call("size"))+"]"); else item->set_text(1,"Vector2[]"); - item->set_icon( 0, get_icon("Vector2","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0, get_icon("Vector2","EditorIcons") ); } break; @@ -2791,7 +2889,8 @@ void PropertyEditor::update_tree() { item->set_text(1,"Vector3["+itos(v.call("size"))+"]"); else item->set_text(1,"Vector3[]"); - item->set_icon( 0, get_icon("Vector","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0, get_icon("Vector","EditorIcons") ); } break; @@ -2805,7 +2904,8 @@ void PropertyEditor::update_tree() { item->set_text(1,"Color["+itos(v.call("size"))+"]"); else item->set_text(1,"Color[]"); - item->set_icon( 0, get_icon("Color","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0, get_icon("Color","EditorIcons") ); } break; @@ -2814,7 +2914,8 @@ void PropertyEditor::update_tree() { item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM ); item->set_editable( 1, true ); item->set_text(1,obj->get(p.name)); - item->set_icon( 0,get_icon("Vector2","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0,get_icon("Vector2","EditorIcons") ); } break; case Variant::RECT2: { @@ -2822,7 +2923,8 @@ void PropertyEditor::update_tree() { item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM ); item->set_editable( 1, true ); item->set_text(1,obj->get(p.name)); - item->set_icon( 0,get_icon("Rect2","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0,get_icon("Rect2","EditorIcons") ); } break; case Variant::VECTOR3: { @@ -2830,15 +2932,24 @@ void PropertyEditor::update_tree() { item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM ); item->set_editable( 1, true ); item->set_text(1,obj->get(p.name)); - item->set_icon( 0,get_icon("Vector","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0,get_icon("Vector","EditorIcons") ); } break; + case Variant::MATRIX32: + case Variant::MATRIX3: { + + item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM ); + item->set_editable( 1, true ); + item->set_text(1, obj->get(p.name)); + } break; case Variant::TRANSFORM: { item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM ); item->set_editable( 1, true ); item->set_text(1,obj->get(p.name)); - item->set_icon( 0,get_icon("Matrix","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0,get_icon("Matrix","EditorIcons") ); } break; case Variant::PLANE: { @@ -2846,7 +2957,8 @@ void PropertyEditor::update_tree() { item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM ); item->set_editable( 1, true ); item->set_text(1,obj->get(p.name)); - item->set_icon( 0,get_icon("Plane","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0,get_icon("Plane","EditorIcons") ); } break; case Variant::_AABB: { @@ -2854,7 +2966,8 @@ void PropertyEditor::update_tree() { item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM ); item->set_editable( 1, true ); item->set_text(1,"AABB"); - item->set_icon( 0,get_icon("Rect3","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0,get_icon("Rect3","EditorIcons") ); } break; case Variant::QUAT: { @@ -2862,7 +2975,8 @@ void PropertyEditor::update_tree() { item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM ); item->set_editable( 1, true ); item->set_text(1,obj->get(p.name)); - item->set_icon( 0,get_icon("Quat","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0,get_icon("Quat","EditorIcons") ); } break; case Variant::COLOR: { @@ -2871,7 +2985,8 @@ void PropertyEditor::update_tree() { item->set_editable( 1, !read_only ); // item->set_text(1,obj->get(p.name)); item->set_custom_bg_color(1,obj->get(p.name)); - item->set_icon( 0,get_icon("Color","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0,get_icon("Color","EditorIcons") ); } break; case Variant::IMAGE: { @@ -2883,7 +2998,8 @@ void PropertyEditor::update_tree() { item->set_text(1,"[Image (empty)]"); else item->set_text(1,"[Image "+itos(img.get_width())+"x"+itos(img.get_height())+"]"); - item->set_icon( 0,get_icon("Image","EditorIcons") ); + if (show_type_icons) + item->set_icon( 0,get_icon("Image","EditorIcons") ); } break; case Variant::NODE_PATH: { @@ -2965,6 +3081,7 @@ void PropertyEditor::update_tree() { } } + bool has_reload=false; if (_might_be_in_instance()) { Variant vorig; @@ -2977,11 +3094,24 @@ void PropertyEditor::update_tree() { if (_is_property_different(v,vorig,usage)) { //print_line("FOR "+String(p.name)+" RELOAD WITH: "+String(v)+"("+Variant::get_type_name(v.get_type())+")=="+String(vorig)+"("+Variant::get_type_name(vorig.get_type())+")"); item->add_button(1,get_icon("Reload","EditorIcons"),3); + has_reload=true; } } } + if (!has_reload && !obj->get_script().is_null()) { + Ref<Script> scr = obj->get_script(); + Variant orig_value; + if (scr->get_property_default_value(p.name,orig_value)) { + if (orig_value!=obj->get(p.name)) { + item->add_button(1,get_icon("Reload","EditorIcons"),3); + } + } + } + + + } } @@ -3272,8 +3402,6 @@ void PropertyEditor::_edit_button(Object *p_item, int p_column, int p_button) { call_deferred("_set_range_def",ti,prop,ti->get_range(p_column)+1.0); } else if (p_button==3) { - if (!_might_be_in_instance()) - return; if (!d.has("name")) return; @@ -3281,11 +3409,21 @@ void PropertyEditor::_edit_button(Object *p_item, int p_column, int p_button) { Variant vorig; - if (_get_instanced_node_original_property(prop,vorig)) { + if (_might_be_in_instance() && _get_instanced_node_original_property(prop,vorig)) { _edit_set(prop,vorig); + return; } + if (!obj->get_script().is_null()) { + Ref<Script> scr = obj->get_script(); + Variant orig_value; + if (scr->get_property_default_value(prop,orig_value)) { + _edit_set(prop,orig_value); + } + } + + } else { Dictionary d = ti->get_metadata(0); @@ -3403,6 +3541,11 @@ void PropertyEditor::_draw_flags(Object *t,const Rect2& p_rect) { } +void PropertyEditor::_filter_changed(const String& p_text) { + + update_tree(); +} + void PropertyEditor::_bind_methods() { ObjectTypeDB::bind_method( "_item_edited",&PropertyEditor::_item_edited); @@ -3415,6 +3558,8 @@ void PropertyEditor::_bind_methods() { ObjectTypeDB::bind_method( "_changed_callback",&PropertyEditor::_changed_callbacks); ObjectTypeDB::bind_method( "_draw_flags",&PropertyEditor::_draw_flags); ObjectTypeDB::bind_method( "_set_range_def",&PropertyEditor::_set_range_def); + ObjectTypeDB::bind_method( "_filter_changed",&PropertyEditor::_filter_changed); + ObjectTypeDB::bind_method( "update_tree",&PropertyEditor::update_tree); ADD_SIGNAL( MethodInfo("property_toggled",PropertyInfo( Variant::STRING, "property"),PropertyInfo( Variant::BOOL, "value"))); ADD_SIGNAL( MethodInfo("resource_selected", PropertyInfo( Variant::OBJECT, "res"),PropertyInfo( Variant::STRING, "prop") ) ); @@ -3469,12 +3614,40 @@ void PropertyEditor::set_show_categories(bool p_show) { update_tree(); } +void PropertyEditor::set_use_filter(bool p_use) { + + if (p_use==use_filter) + return; + + use_filter=p_use; + update_tree(); +} + +void PropertyEditor::register_text_enter(Node* p_line_edit) { + + ERR_FAIL_NULL(p_line_edit); + search_box=p_line_edit->cast_to<LineEdit>(); + + if (search_box) + search_box->connect("text_changed",this,"_filter_changed"); +} + +void PropertyEditor::set_subsection_selectable(bool p_selectable) { + + if (p_selectable==subsection_selectable) + return; + + subsection_selectable=p_selectable; + update_tree(); +} + PropertyEditor::PropertyEditor() { _prop_edited="property_edited"; _prop_edited_name.push_back(String()); undo_redo=NULL; obj=NULL; + search_box=NULL; changing=false; update_tree_pending=false; @@ -3514,6 +3687,7 @@ PropertyEditor::PropertyEditor() { tree->connect("button_pressed", this,"_edit_button"); custom_editor->connect("variant_changed", this,"_custom_editor_edited"); custom_editor->connect("resource_edit_request", this,"_resource_edit_request",make_binds(),CONNECT_DEFERRED); + tree->set_hide_folding(true); capitalize_paths=true; autoclear=false; @@ -3526,7 +3700,10 @@ PropertyEditor::PropertyEditor() { show_categories=false; refresh_countdown=0; use_doc_hints=false; - + use_filter=false; + subsection_selectable=false; + show_type_icons=EDITOR_DEF("inspector/show_type_icons",false); + } @@ -3535,3 +3712,196 @@ PropertyEditor::~PropertyEditor() } +///////////////////////////// + + + + + +class SectionedPropertyEditorFilter : public Object { + + OBJ_TYPE( SectionedPropertyEditorFilter, Object ); + + Object *edited; + String section; + + bool _set(const StringName& p_name, const Variant& p_value) { + + if (!edited) + return false; + + String name=p_name; + if (section!="") { + name=section+"/"+name; + } + + bool valid; + edited->set(name,p_value,&valid); + return valid; + } + + bool _get(const StringName& p_name,Variant &r_ret) const{ + + if (!edited) + return false; + + String name=p_name; + if (section!="") { + name=section+"/"+name; + } + + bool valid=false; + + r_ret=edited->get(name,&valid); + return valid; + + + } + void _get_property_list(List<PropertyInfo> *p_list) const{ + + if (!edited) + return; + + List<PropertyInfo> pinfo; + edited->get_property_list(&pinfo); + for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) { + + PropertyInfo pi=E->get(); + int sp = pi.name.find("/"); + if (sp!=-1) { + String ss = pi.name.substr(0,sp); + + if (ss==section) { + pi.name=pi.name.substr(sp+1,pi.name.length()); + p_list->push_back(pi); + } + } else { + if (section=="") + p_list->push_back(pi); + } + } + + } +public: + + void set_section(const String& p_section) { + + section=p_section; + _change_notify(); + } + + void set_edited(Object* p_edited) { + edited=p_edited; + _change_notify(); + } + + SectionedPropertyEditorFilter() { + edited=NULL; + } + +}; + + +void SectionedPropertyEditor::_bind_methods() { + + ObjectTypeDB::bind_method("_section_selected",&SectionedPropertyEditor::_section_selected); +} + +void SectionedPropertyEditor::_section_selected(int p_which) { + + filter->set_section( sections->get_item_metadata(p_which) ); +} + +String SectionedPropertyEditor::get_full_item_path(const String& p_item) { + + String base = sections->get_item_metadata( sections->get_current() ); + if (base!="") + return base+"/"+p_item; + else + return p_item; +} + +void SectionedPropertyEditor::edit(Object* p_object) { + + List<PropertyInfo> pinfo; + if (p_object) + p_object->get_property_list(&pinfo); + sections->clear(); + + Set<String> existing_sections; + for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) { + + PropertyInfo pi=E->get(); + if (pi.usage&PROPERTY_USAGE_CATEGORY) + continue; + if (pi.name.find(":")!=-1 || pi.name=="script/script") + continue; + int sp = pi.name.find("/"); + if (sp!=-1) { + String sname=pi.name.substr(0,sp); + if (!existing_sections.has(sname)) { + existing_sections.insert(sname); + sections->add_item(sname.capitalize()); + sections->set_item_metadata(sections->get_item_count()-1,sname); + } + + } else { + if (!existing_sections.has("")) { + existing_sections.insert(""); + sections->add_item("Global"); + sections->set_item_metadata(sections->get_item_count()-1,""); + } + } + + + } + + //sections->sort_items_by_text(); + + + filter->set_edited(p_object); + editor->edit(filter); + + sections->select(0); + _section_selected(0); + +} + +PropertyEditor *SectionedPropertyEditor::get_property_editor() { + + return editor; +} + +SectionedPropertyEditor::SectionedPropertyEditor() { + + VBoxContainer *left_vb = memnew( VBoxContainer); + left_vb->set_custom_minimum_size(Size2(160,0)); + add_child(left_vb); + + sections = memnew( ItemList ); + sections->set_v_size_flags(SIZE_EXPAND_FILL); + + left_vb->add_margin_child("Sections:",sections,true); + + VBoxContainer *right_vb = memnew( VBoxContainer); + right_vb->set_h_size_flags(SIZE_EXPAND_FILL); + add_child(right_vb); + + filter = memnew( SectionedPropertyEditorFilter ); + editor = memnew( PropertyEditor ); + editor->set_v_size_flags(SIZE_EXPAND_FILL); + right_vb->add_margin_child("Properties:",editor,true); + + editor->get_scene_tree()->set_column_titles_visible(false); + add_child(editor); + + editor->hide_top_label(); + + sections->connect("item_selected",this,"_section_selected"); + +} + +SectionedPropertyEditor::~SectionedPropertyEditor() { + + memdelete(filter); +} diff --git a/tools/editor/property_editor.h b/tools/editor/property_editor.h index dcb7b66abd..4f03c0381f 100644 --- a/tools/editor/property_editor.h +++ b/tools/editor/property_editor.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -39,6 +39,7 @@ #include "scene/gui/texture_frame.h" #include "scene/gui/text_edit.h" #include "scene/gui/check_button.h" +#include "scene/gui/split_container.h" #include "scene_tree_editor.h" /** @@ -113,6 +114,7 @@ class CustomPropertyEditor : public Popup { void _action_pressed(int p_which); void _type_create_selected(int p_idx); + void _color_changed(const Color& p_color); void _draw_easing(); void _menu_option(int p_which); @@ -147,6 +149,7 @@ class PropertyEditor : public Control { Tree *tree; Label *top_label; //Object *object; + LineEdit *search_box; Object* obj; @@ -160,8 +163,11 @@ class PropertyEditor : public Control { bool keying; bool read_only; bool show_categories; + bool show_type_icons; float refresh_countdown; bool use_doc_hints; + bool use_filter; + bool subsection_selectable; HashMap<String,String> pending; String selected_property; @@ -187,6 +193,7 @@ class PropertyEditor : public Control { virtual void _changed_callback(Object *p_changed,const char * p_what); virtual void _changed_callbacks(Object *p_changed,const String& p_callback); + void _check_reload_status(const String&p_name,TreeItem* item); void _edit_button(Object *p_item, int p_column, int p_button); @@ -201,6 +208,8 @@ class PropertyEditor : public Control { void _refresh_item(TreeItem *p_item); void _set_range_def(Object *p_item, String prop, float p_frame); + void _filter_changed(const String& p_text); + UndoRedo *undo_redo; protected: @@ -230,10 +239,40 @@ public: void set_show_categories(bool p_show); void set_use_doc_hints(bool p_enable) { use_doc_hints=p_enable; } - + + void set_use_filter(bool p_use); + void register_text_enter(Node *p_line_edit); + + void set_subsection_selectable(bool p_selectable); + PropertyEditor(); ~PropertyEditor(); }; + +class SectionedPropertyEditorFilter; + +class SectionedPropertyEditor : public HBoxContainer { + + + OBJ_TYPE(SectionedPropertyEditor,HBoxContainer); + ItemList *sections; + SectionedPropertyEditorFilter *filter; + PropertyEditor *editor; + + + static void _bind_methods(); + void _section_selected(int p_which); + +public: + + PropertyEditor *get_property_editor(); + void edit(Object* p_object); + String get_full_item_path(const String& p_item); + + SectionedPropertyEditor(); + ~SectionedPropertyEditor(); +}; + #endif diff --git a/tools/editor/pvrtc_compress.cpp b/tools/editor/pvrtc_compress.cpp index a2f98adbe0..c30aedc1dc 100644 --- a/tools/editor/pvrtc_compress.cpp +++ b/tools/editor/pvrtc_compress.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/pvrtc_compress.h b/tools/editor/pvrtc_compress.h index c4fb0bacb5..129faee080 100644 --- a/tools/editor/pvrtc_compress.h +++ b/tools/editor/pvrtc_compress.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/quick_open.cpp b/tools/editor/quick_open.cpp index 6135a4ab64..bfbcb739ac 100644 --- a/tools/editor/quick_open.cpp +++ b/tools/editor/quick_open.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/quick_open.h b/tools/editor/quick_open.h index 8b38256d39..7f2091e5d1 100644 --- a/tools/editor/quick_open.h +++ b/tools/editor/quick_open.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/register_exporters.h b/tools/editor/register_exporters.h index 0e1ad2ca46..364ad5efc9 100644 --- a/tools/editor/register_exporters.h +++ b/tools/editor/register_exporters.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/reparent_dialog.cpp b/tools/editor/reparent_dialog.cpp index 78ba47d54b..97b27603b2 100644 --- a/tools/editor/reparent_dialog.cpp +++ b/tools/editor/reparent_dialog.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -36,12 +36,12 @@ void ReparentDialog::_notification(int p_what) { - if (p_what==NOTIFICATION_ENTER_TREE) { + if (p_what==NOTIFICATION_ENTER_TREE) { connect("confirmed", this,"_reparent"); } - if (p_what==NOTIFICATION_EXIT_TREE) { + if (p_what==NOTIFICATION_EXIT_TREE) { disconnect("confirmed", this,"_reparent"); } @@ -62,7 +62,7 @@ void ReparentDialog::_reparent() { if (tree->get_selected()) { - emit_signal("reparent",tree->get_selected()->get_path(),node_only->is_pressed()); + emit_signal("reparent",tree->get_selected()->get_path(),keep_transform->is_pressed()); hide(); } } @@ -78,38 +78,41 @@ void ReparentDialog::_bind_methods() { ObjectTypeDB::bind_method("_reparent",&ReparentDialog::_reparent); ObjectTypeDB::bind_method("_cancel",&ReparentDialog::_cancel); - ADD_SIGNAL( MethodInfo("reparent",PropertyInfo(Variant::NODE_PATH,"path"),PropertyInfo(Variant::BOOL,"only_node"))); + ADD_SIGNAL( MethodInfo("reparent",PropertyInfo(Variant::NODE_PATH,"path"),PropertyInfo(Variant::BOOL,"keep_global_xform"))); } ReparentDialog::ReparentDialog() { - set_title("Reparent Node"); + VBoxContainer *vbc = memnew( VBoxContainer ); add_child(vbc); set_child_rect(vbc); tree = memnew( SceneTreeEditor(false) ); - + tree->set_show_enabled_subscene(true); vbc->add_margin_child("Reparent Location (Select new Parent):",tree,true); - + + tree->get_scene_tree()->connect("item_activated",this,"_reparent"); + //Label *label = memnew( Label ); //label->set_pos( Point2( 15,8) ); //label->set_text("Reparent Location (Select new Parent):"); - - node_only = memnew( CheckButton ); - add_child(node_only); - node_only->hide(); - tree->set_show_enabled_subscene(true); + keep_transform = memnew( CheckBox ); + keep_transform->set_text("Keep Global Transform"); + keep_transform->set_pressed(true); + vbc->add_child(keep_transform); + + //vbc->add_margin_child("Options:",node_only);; - //cancel->connect("pressed", this,"_cancel"); get_ok()->set_text("Reparent"); + } diff --git a/tools/editor/reparent_dialog.h b/tools/editor/reparent_dialog.h index 78c0df9285..296102e4b9 100644 --- a/tools/editor/reparent_dialog.h +++ b/tools/editor/reparent_dialog.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -32,6 +32,7 @@ #include "scene/gui/dialogs.h" #include "scene/gui/button.h" #include "scene/gui/check_button.h" +#include "scene/gui/check_box.h" #include "tools/editor/scene_tree_editor.h" #include "scene/gui/line_edit.h" /** @@ -42,12 +43,14 @@ class ReparentDialog : public ConfirmationDialog { OBJ_TYPE( ReparentDialog, ConfirmationDialog ); SceneTreeEditor *tree; - CheckButton *node_only; + CheckBox *keep_transform; + void update_tree(); void _reparent(); void _cancel(); - + + protected: void _notification(int p_what); diff --git a/tools/editor/resources_dock.cpp b/tools/editor/resources_dock.cpp index b69eec4a51..5e44162c93 100644 --- a/tools/editor/resources_dock.cpp +++ b/tools/editor/resources_dock.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/resources_dock.h b/tools/editor/resources_dock.h index 933b457b29..978291fc3f 100644 --- a/tools/editor/resources_dock.h +++ b/tools/editor/resources_dock.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/run_settings_dialog.cpp b/tools/editor/run_settings_dialog.cpp index e883c69939..e8c509d79d 100644 --- a/tools/editor/run_settings_dialog.cpp +++ b/tools/editor/run_settings_dialog.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/run_settings_dialog.h b/tools/editor/run_settings_dialog.h index fdb8857f6b..09319702f3 100644 --- a/tools/editor/run_settings_dialog.h +++ b/tools/editor/run_settings_dialog.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/scene_tree_dock.cpp b/tools/editor/scene_tree_dock.cpp index 08aa68d792..75f1597b20 100644 --- a/tools/editor/scene_tree_dock.cpp +++ b/tools/editor/scene_tree_dock.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -889,7 +889,7 @@ bool SceneTreeDock::_validate_no_foreign() { return true; } -void SceneTreeDock::_node_reparent(NodePath p_path,bool p_node_only) { +void SceneTreeDock::_node_reparent(NodePath p_path,bool p_keep_global_xform) { Node *node = scene_tree->get_selected(); @@ -948,6 +948,23 @@ void SceneTreeDock::_node_reparent(NodePath p_path,bool p_node_only) { editor_data->get_undo_redo().add_do_method(sed,"live_debug_reparent_node",edited_scene->get_path_to(node),edited_scene->get_path_to(new_parent),new_name,-1); editor_data->get_undo_redo().add_undo_method(sed,"live_debug_reparent_node",NodePath(String(edited_scene->get_path_to(new_parent))+"/"+new_name),edited_scene->get_path_to(node->get_parent()),node->get_name(),node->get_index()); + if (p_keep_global_xform) { + if (node->cast_to<Node2D>()) + editor_data->get_undo_redo().add_do_method(node,"set_global_transform",node->cast_to<Node2D>()->get_global_transform()); + if (node->cast_to<Spatial>()) + editor_data->get_undo_redo().add_do_method(node,"set_global_transform",node->cast_to<Spatial>()->get_global_transform()); + if (node->cast_to<Control>()) { + bool can_do_it=false; + Control *c=node->cast_to<Control>(); + if (c->get_parent()->cast_to<Container>()) + can_do_it=false; + for(int i=0;i<4;i++) { + if (c->get_anchor(Margin(i))!=ANCHOR_BEGIN) + can_do_it=false; + } + editor_data->get_undo_redo().add_do_method(node,"set_global_pos",node->cast_to<Control>()->get_global_pos()); + } + } editor_data->get_undo_redo().add_do_method(this,"_set_owners",edited_scene,owners); @@ -982,6 +999,26 @@ void SceneTreeDock::_node_reparent(NodePath p_path,bool p_node_only) { if (editor->get_animation_editor()->get_root()==node) editor_data->get_undo_redo().add_undo_method(editor->get_animation_editor(),"set_root",node); + if (p_keep_global_xform) { + if (node->cast_to<Node2D>()) + editor_data->get_undo_redo().add_undo_method(node,"set_transform",node->cast_to<Node2D>()->get_transform()); + if (node->cast_to<Spatial>()) + editor_data->get_undo_redo().add_undo_method(node,"set_transform",node->cast_to<Spatial>()->get_transform()); + if (node->cast_to<Control>()) { + bool can_do_it=false; + Control *c=node->cast_to<Control>(); + if (c->get_parent()->cast_to<Container>()) + can_do_it=false; + for(int i=0;i<4;i++) { + if (c->get_anchor(Margin(i))!=ANCHOR_BEGIN) + can_do_it=false; + } + editor_data->get_undo_redo().add_undo_method(node,"set_pos",node->cast_to<Control>()->get_pos()); + } + } + + + } perform_node_renames(NULL,&path_renames); @@ -1223,24 +1260,21 @@ void SceneTreeDock::_create() { } - String newname=n->get_name(); n->replace_by(newnode,true); - if (n==edited_scene) { edited_scene=newnode; editor->set_edited_scene(newnode); } - - - editor_data->get_undo_redo().clear_history(); - memdelete(n); newnode->set_name(newname); + editor->push_item(newnode); + memdelete(n); + _update_tool_buttons(); } @@ -1267,7 +1301,10 @@ void SceneTreeDock::import_subscene() { void SceneTreeDock::_import_subscene() { Node* parent = scene_tree->get_selected(); - ERR_FAIL_COND(!parent); + if (!parent) { + parent = editor_data->get_edited_scene_root(); + ERR_FAIL_COND(!parent); + } import_subscene_dialog->move(parent,edited_scene); editor_data->get_undo_redo().clear_history(); //no undo for now.. diff --git a/tools/editor/scene_tree_dock.h b/tools/editor/scene_tree_dock.h index b1c53d2ff9..aad12a2340 100644 --- a/tools/editor/scene_tree_dock.h +++ b/tools/editor/scene_tree_dock.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -99,7 +99,7 @@ class SceneTreeDock : public VBoxContainer { EditorNode *editor; Node *_duplicate(Node *p_node, Map<Node*,Node*> &duplimap); - void _node_reparent(NodePath p_path,bool p_node_only); + void _node_reparent(NodePath p_path, bool p_keep_global_xform); void _set_owners(Node *p_owner, const Array& p_nodes); void _load_request(const String& p_path); void _script_open_request(const Ref<Script>& p_script); diff --git a/tools/editor/scene_tree_editor.cpp b/tools/editor/scene_tree_editor.cpp index 60395d5ff5..531fe83bc3 100644 --- a/tools/editor/scene_tree_editor.cpp +++ b/tools/editor/scene_tree_editor.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -565,7 +565,6 @@ void SceneTreeEditor::_notification(int p_what) { get_tree()->disconnect("node_removed",this,"_node_removed"); tree->disconnect("item_collapsed",this,"_cell_collapsed"); clear_inherit_confirm->disconnect("confirmed",this,"_subscene_option"); - _update_tree(); } } @@ -649,20 +648,28 @@ void SceneTreeEditor::_rename_node(ObjectID p_node,const String& p_name) { void SceneTreeEditor::_renamed() { TreeItem *which=tree->get_edited(); - + ERR_FAIL_COND(!which); NodePath np = which->get_metadata(0); Node *n=get_node(np); ERR_FAIL_COND(!n); + String new_name=which->get_text(0); + if (new_name.find(".") != -1 || new_name.find("/") != -1) { + + error->set_text("Invalid node name, the following characters are not allowed:\n \".\", \"/\""); + error->popup_centered_minsize(); + new_name=n->get_name(); + } + if (!undo_redo) { - n->set_name( which->get_text(0) ); + n->set_name( new_name ); which->set_metadata(0,n->get_path()); emit_signal("node_renamed"); } else { undo_redo->create_action("Rename Node"); - emit_signal("node_prerename",n,which->get_text(0)); - undo_redo->add_do_method(this,"_rename_node",n->get_instance_ID(),which->get_text(0)); + emit_signal("node_prerename",n,new_name); + undo_redo->add_do_method(this,"_rename_node",n->get_instance_ID(),new_name); undo_redo->add_undo_method(this,"_rename_node",n->get_instance_ID(),n->get_name()); undo_redo->commit_action(); } @@ -921,7 +928,7 @@ void SceneTreeDialog::_cancel() { void SceneTreeDialog::_select() { if (tree->get_selected()) { - emit_signal("selected",tree->get_selected()->get_path()); + emit_signal("selected",tree->get_selected()->get_path()); hide(); } } @@ -932,7 +939,6 @@ void SceneTreeDialog::_bind_methods() { ObjectTypeDB::bind_method("_cancel",&SceneTreeDialog::_cancel); ADD_SIGNAL( MethodInfo("selected",PropertyInfo(Variant::NODE_PATH,"path"))); - } @@ -944,7 +950,7 @@ SceneTreeDialog::SceneTreeDialog() { add_child(tree); set_child_rect(tree); - + tree->get_scene_tree()->connect("item_activated",this,"_select"); } diff --git a/tools/editor/scene_tree_editor.h b/tools/editor/scene_tree_editor.h index 50cca4e24b..334debc148 100644 --- a/tools/editor/scene_tree_editor.h +++ b/tools/editor/scene_tree_editor.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/scenes.cpp b/tools/editor/scenes.cpp index ada5751b5a..e6569c98a9 100644 --- a/tools/editor/scenes.cpp +++ b/tools/editor/scenes.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/scenes.h b/tools/editor/scenes.h index 463c3b5e18..bae9ef65f0 100644 --- a/tools/editor/scenes.h +++ b/tools/editor/scenes.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/scenes_dock.cpp b/tools/editor/scenes_dock.cpp index 7d9c5b24b2..cdc0bf0d25 100644 --- a/tools/editor/scenes_dock.cpp +++ b/tools/editor/scenes_dock.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -155,7 +155,7 @@ void ScenesDock::_notification(int p_what) { if (initialized) return; - initialized=false; + initialized=true; EditorFileSystem::get_singleton()->connect("filesystem_changed",this,"_fs_changed"); @@ -195,7 +195,12 @@ void ScenesDock::_notification(int p_what) { case NOTIFICATION_EXIT_TREE: { } break; + case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { + display_mode->set_pressed(int(EditorSettings::get_singleton()->get("file_dialog/display_mode"))==EditorFileDialog::DISPLAY_LIST); + + _change_file_display(); + } break; } } @@ -352,10 +357,30 @@ String ScenesDock::get_selected_path() const { void ScenesDock::_instance_pressed() { - TreeItem *sel = tree->get_selected(); - if (!sel) - return; - String path = sel->get_metadata(0); + if (tree_mode) + { + TreeItem *sel = tree->get_selected(); + if (!sel) + return; + String path = sel->get_metadata(0); + } + else + { + int idx = -1; + for (int i = 0; i<files->get_item_count(); i++) { + if (files->is_selected(i)) + { + idx = i; + break; + } + } + + if (idx<0) + return; + + path = files->get_item_metadata(idx); + } + emit_signal("instance",path); } @@ -1043,6 +1068,11 @@ void ScenesDock::open(const String& p_path) { } +void ScenesDock::set_use_thumbnails(bool p_use) { + + display_mode->set_pressed(!p_use); +} + void ScenesDock::_bind_methods() { ObjectTypeDB::bind_method(_MD("_update_tree"),&ScenesDock::_update_tree); diff --git a/tools/editor/scenes_dock.h b/tools/editor/scenes_dock.h index d045124bf7..a1978a3ca4 100644 --- a/tools/editor/scenes_dock.h +++ b/tools/editor/scenes_dock.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -153,6 +153,7 @@ public: void fix_dependencies(const String& p_for_file); + void set_use_thumbnails(bool p_use); ScenesDock(EditorNode *p_editor); ~ScenesDock(); diff --git a/tools/editor/script_create_dialog.cpp b/tools/editor/script_create_dialog.cpp index 622150ab68..409e8be870 100644 --- a/tools/editor/script_create_dialog.cpp +++ b/tools/editor/script_create_dialog.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/script_create_dialog.h b/tools/editor/script_create_dialog.h index 59fde8fbd5..181989402e 100644 --- a/tools/editor/script_create_dialog.h +++ b/tools/editor/script_create_dialog.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/editor/script_editor_debugger.cpp b/tools/editor/script_editor_debugger.cpp index 8e0e7ddb49..fb821573f9 100644 --- a/tools/editor/script_editor_debugger.cpp +++ b/tools/editor/script_editor_debugger.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -571,10 +571,10 @@ void ScriptEditorDebugger::_notification(int p_what) { show(); + dobreak->set_disabled(false); tabs->set_current_tab(0); - emit_signal("show_debugger",true); reason->set_text("Child Process Connected"); reason->set_tooltip("Child Process Connected"); scene_tree->clear(); @@ -737,8 +737,10 @@ void ScriptEditorDebugger::stop(){ le_set->set_disabled(true); - hide(); - emit_signal("show_debugger",false); + if (hide_on_stop) { + hide(); + emit_signal("show_debugger",false); + } } @@ -768,9 +770,7 @@ void ScriptEditorDebugger::_stack_dump_frame_selected() { void ScriptEditorDebugger::_hide_request() { - hide(); emit_signal("show_debugger",false); - } void ScriptEditorDebugger::_output_clear() { @@ -1160,6 +1160,10 @@ void ScriptEditorDebugger:: _error_stack_selected(int p_idx){ } +void ScriptEditorDebugger::set_hide_on_stop(bool p_hide) { + + hide_on_stop=p_hide; +} void ScriptEditorDebugger::_bind_methods() { @@ -1376,7 +1380,6 @@ ScriptEditorDebugger::ScriptEditorDebugger(EditorNode *p_editor){ vmem_refresh->connect("pressed",this,"_video_mem_request"); MarginContainer *vmmc = memnew( MarginContainer ); - vmmc = memnew( MarginContainer ); vmem_tree = memnew( Tree ); vmem_tree->set_v_size_flags(SIZE_EXPAND_FILL); vmem_tree->set_h_size_flags(SIZE_EXPAND_FILL); @@ -1463,6 +1466,7 @@ ScriptEditorDebugger::ScriptEditorDebugger(EditorNode *p_editor){ live_debug=false; last_path_id=false; error_count=0; + hide_on_stop=true; last_error_count=0; diff --git a/tools/editor/script_editor_debugger.h b/tools/editor/script_editor_debugger.h index 6b66a62dd5..55c79ca3b3 100644 --- a/tools/editor/script_editor_debugger.h +++ b/tools/editor/script_editor_debugger.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -71,6 +71,8 @@ class ScriptEditorDebugger : public Control { int error_count; int last_error_count; + bool hide_on_stop; + TextureButton *tb; @@ -182,6 +184,7 @@ public: void update_live_edit_root(); + void set_hide_on_stop(bool p_hide); virtual Size2 get_minimum_size() const; ScriptEditorDebugger(EditorNode *p_editor=NULL); diff --git a/tools/editor/settings_config_dialog.cpp b/tools/editor/settings_config_dialog.cpp index f73de26eec..ebbc488ff2 100644 --- a/tools/editor/settings_config_dialog.cpp +++ b/tools/editor/settings_config_dialog.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -71,7 +71,11 @@ void EditorSettingsDialog::popup_edit_settings() { return; property_editor->edit(EditorSettings::get_singleton()); - property_editor->update_tree(); + property_editor->get_property_editor()->update_tree(); + + search_box->select_all(); + search_box->grab_focus(); + popup_centered_ratio(0.7); } @@ -244,11 +248,21 @@ void EditorSettingsDialog::_update_plugins() { } +void EditorSettingsDialog::_clear_search_box() { + + if (search_box->get_text()=="") + return; + + search_box->clear(); + property_editor->get_property_editor()->update_tree(); +} + void EditorSettingsDialog::_notification(int p_what) { if (p_what==NOTIFICATION_ENTER_TREE) { rescan_plugins->set_icon(get_icon("Reload","EditorIcons")); + clear_button->set_icon(get_icon("Close","EditorIcons")); _update_plugins(); } } @@ -261,6 +275,7 @@ void EditorSettingsDialog::_bind_methods() { ObjectTypeDB::bind_method(_MD("_plugin_settings"),&EditorSettingsDialog::_plugin_settings); ObjectTypeDB::bind_method(_MD("_plugin_edited"),&EditorSettingsDialog::_plugin_edited); ObjectTypeDB::bind_method(_MD("_plugin_install"),&EditorSettingsDialog::_plugin_install); + ObjectTypeDB::bind_method(_MD("_clear_search_box"),&EditorSettingsDialog::_clear_search_box); } EditorSettingsDialog::EditorSettingsDialog() { @@ -271,16 +286,38 @@ EditorSettingsDialog::EditorSettingsDialog() { add_child(tabs); set_child_rect(tabs); - property_editor = memnew( PropertyEditor ); - property_editor->hide_top_label(); - tabs->add_child(property_editor); - property_editor->set_name("General"); - VBoxContainer *vbc = memnew( VBoxContainer ); tabs->add_child(vbc); - vbc->set_name("Plugins"); + vbc->set_name("General"); HBoxContainer *hbc = memnew( HBoxContainer ); + hbc->set_h_size_flags(Control::SIZE_EXPAND_FILL); + vbc->add_child(hbc); + + Label *l = memnew( Label ); + l->set_text("Search: "); + hbc->add_child(l); + + search_box = memnew( LineEdit ); + search_box->set_h_size_flags(Control::SIZE_EXPAND_FILL); + hbc->add_child(search_box); + + clear_button = memnew( ToolButton ); + hbc->add_child(clear_button); + clear_button->connect("pressed",this,"_clear_search_box"); + + property_editor = memnew( SectionedPropertyEditor ); + //property_editor->hide_top_label(); + property_editor->get_property_editor()->set_use_filter(true); + property_editor->get_property_editor()->register_text_enter(search_box); + property_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL); + vbc->add_child(property_editor); + + vbc = memnew( VBoxContainer ); + tabs->add_child(vbc); + vbc->set_name("Plugins"); + + hbc = memnew( HBoxContainer ); vbc->add_child(hbc); hbc->add_child( memnew( Label("Plugin List: "))); hbc->add_spacer(); diff --git a/tools/editor/settings_config_dialog.h b/tools/editor/settings_config_dialog.h index cca1ef33d5..e1c3238a64 100644 --- a/tools/editor/settings_config_dialog.h +++ b/tools/editor/settings_config_dialog.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -51,7 +51,9 @@ class EditorSettingsDialog : public AcceptDialog { Button *rescan_plugins; Tree *plugins; - PropertyEditor *property_editor; + LineEdit *search_box; + ToolButton *clear_button; + SectionedPropertyEditor *property_editor; Timer *timer; @@ -71,6 +73,8 @@ class EditorSettingsDialog : public AcceptDialog { void _rescan_plugins(); void _update_plugins(); + void _clear_search_box(); + protected: static void _bind_methods(); diff --git a/tools/editor/spatial_editor_gizmos.cpp b/tools/editor/spatial_editor_gizmos.cpp index 4dc9c4f43e..320b0c3a70 100644 --- a/tools/editor/spatial_editor_gizmos.cpp +++ b/tools/editor/spatial_editor_gizmos.cpp @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -745,7 +745,7 @@ static float _find_closest_angle_to_half_pi_arc(const Vector3& p_from, const Vec } //min_p = p_arc_xform.affine_inverse().xform(min_p); - float a = Vector2(min_p.x,-min_p.z).atan2(); + float a = Vector2(min_p.x,-min_p.z).angle(); return a*180.0/Math_PI; } @@ -2283,6 +2283,8 @@ void NavigationMeshSpatialGizmo::redraw() { } } + if (faces.empty()) + return; Map<_EdgeKey,bool> edge_map; DVector<Vector3> tmeshfaces; @@ -2330,7 +2332,7 @@ void NavigationMeshSpatialGizmo::redraw() { } } - Ref<TriangleMesh> tmesh = memnew( TriangleMesh); + Ref<TriangleMesh> tmesh = memnew( TriangleMesh ); tmesh->create(tmeshfaces); if (lines.size()) diff --git a/tools/editor/spatial_editor_gizmos.h b/tools/editor/spatial_editor_gizmos.h index bc7e8ad21d..669d3e2380 100644 --- a/tools/editor/spatial_editor_gizmos.h +++ b/tools/editor/spatial_editor_gizmos.h @@ -5,7 +5,7 @@ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/tools/export/blender25/godot_export_manager.py b/tools/export/blender25/godot_export_manager.py index e390ae6ce3..582d76f94f 100644 --- a/tools/export/blender25/godot_export_manager.py +++ b/tools/export/blender25/godot_export_manager.py @@ -107,7 +107,6 @@ class godot_export_manager(bpy.types.Panel): col.prop(group,"use_triangles") col.prop(group,"use_copy_images") col.prop(group,"use_active_layers") - col.prop(group,"use_exclude_ctrl_bones") col.prop(group,"use_anim") col.prop(group,"use_anim_action_all") col.prop(group,"use_anim_skip_noexp") @@ -351,7 +350,7 @@ class export_group(bpy.types.Operator): bpy.data.objects[object.name].select = True bpy.ops.object.transform_apply(location=group[self.idx].apply_loc, rotation=group[self.idx].apply_rot, scale=group[self.idx].apply_scale) - bpy.ops.export_scene.dae(check_existing=True, filepath=path, filter_glob="*.dae", object_types=group[self.idx].object_types, use_export_selected=group[self.idx].use_export_selected, use_mesh_modifiers=group[self.idx].use_mesh_modifiers, use_tangent_arrays=group[self.idx].use_tangent_arrays, use_triangles=group[self.idx].use_triangles, use_copy_images=group[self.idx].use_copy_images, use_active_layers=group[self.idx].use_active_layers, use_exclude_ctrl_bones=group[self.idx].use_exclude_ctrl_bones, use_anim=group[self.idx].use_anim, use_anim_action_all=group[self.idx].use_anim_action_all, use_anim_skip_noexp=group[self.idx].use_anim_skip_noexp, use_anim_optimize=group[self.idx].use_anim_optimize, anim_optimize_precision=group[self.idx].anim_optimize_precision, use_metadata=group[self.idx].use_metadata) + bpy.ops.export_scene.dae(check_existing=True, filepath=path, filter_glob="*.dae", object_types=group[self.idx].object_types, use_export_selected=group[self.idx].use_export_selected, use_mesh_modifiers=group[self.idx].use_mesh_modifiers, use_tangent_arrays=group[self.idx].use_tangent_arrays, use_triangles=group[self.idx].use_triangles, use_copy_images=group[self.idx].use_copy_images, use_active_layers=group[self.idx].use_active_layers, use_anim=group[self.idx].use_anim, use_anim_action_all=group[self.idx].use_anim_action_all, use_anim_skip_noexp=group[self.idx].use_anim_skip_noexp, use_anim_optimize=group[self.idx].use_anim_optimize, anim_optimize_precision=group[self.idx].anim_optimize_precision, use_metadata=group[self.idx].use_metadata) self.report({'INFO'}, '"'+group[self.idx].name+'"' + " Group exported." ) msg = "Export Group "+group[self.idx].name @@ -422,7 +421,6 @@ class godot_export_groups(bpy.types.PropertyGroup): use_copy_images = BoolProperty(name="Copy Images",description="Copy Images (create images/ subfolder)",default=False) use_active_layers = BoolProperty(name="Active Layers",description="Export only objects on the active layers.",default=True) - use_exclude_ctrl_bones = BoolProperty(name="Exclude Control Bones",description="Exclude skeleton bones with names that begin with 'ctrl'.",default=True) use_anim = BoolProperty(name="Export Animation",description="Export keyframe animation",default=False) use_anim_action_all = BoolProperty(name="All Actions",description=("Export all actions for the first armature found in separate DAE files"),default=False) use_anim_skip_noexp = BoolProperty(name="Skip (-noexp) Actions",description="Skip exporting of actions whose name end in (-noexp). Useful to skip control animations.",default=True) diff --git a/tools/export/blender25/io_scene_dae/export_dae.py b/tools/export/blender25/io_scene_dae/export_dae.py index b846f0e2d8..7ee0e179b8 100644 --- a/tools/export/blender25/io_scene_dae/export_dae.py +++ b/tools/export/blender25/io_scene_dae/export_dae.py @@ -921,7 +921,7 @@ class DaeExporter: if (node.parent.type=="ARMATURE"): armature=node.parent if (armcount>1): - self.operator.report({'WARNING'},'Object "'+node.name+'" refers to more than one armature! This is unsopported.') + self.operator.report({'WARNING'},'Object "'+node.name+'" refers to more than one armature! This is unsupported.') if (armcount==0): self.operator.report({'WARNING'},'Object "'+node.name+'" is child of an armature, but has no armature modifier.') diff --git a/tools/freetype/SCsub b/tools/freetype/SCsub index a31b8c4602..65b4827f9c 100644 --- a/tools/freetype/SCsub +++ b/tools/freetype/SCsub @@ -65,7 +65,5 @@ if (env["freetype"]=="builtin"): # lib = env.Library("freetype_builtin",ft_sources) # env.Prepend(LIBS=[lib]) - -Export('env') - +Export('env') diff --git a/tools/ios_xcode_template/godot_ios.xcodeproj/project.pbxproj b/tools/ios_xcode_template/godot_ios.xcodeproj/project.pbxproj index 7cd4da0f4a..4ae1ec8a53 100644 --- a/tools/ios_xcode_template/godot_ios.xcodeproj/project.pbxproj +++ b/tools/ios_xcode_template/godot_ios.xcodeproj/project.pbxproj @@ -192,7 +192,7 @@ isa = PBXProject; attributes = { LastUpgradeCheck = 0500; - ORGANIZATIONNAME = Okam; + ORGANIZATIONNAME = GodotEngine; TargetAttributes = { D0BCFE5F18AEBDA3004A7AAE = { TestTargetID = D0BCFE3318AEBDA2004A7AAE; diff --git a/tools/ios_xcode_template/godot_ios/godot_ios-Info.plist b/tools/ios_xcode_template/godot_ios/godot_ios-Info.plist index f34ebb97f0..357970920a 100644 --- a/tools/ios_xcode_template/godot_ios/godot_ios-Info.plist +++ b/tools/ios_xcode_template/godot_ios/godot_ios-Info.plist @@ -9,7 +9,7 @@ <key>CFBundleExecutable</key> <string>godot_opt.iphone</string> <key>CFBundleIdentifier</key> - <string>com.okamstudios.${PRODUCT_NAME:rfc1034identifier}</string> + <string>org.godotengine.${PRODUCT_NAME:rfc1034identifier}</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> diff --git a/tools/ios_xcode_template/godot_ios/main.m b/tools/ios_xcode_template/godot_ios/main.m index dca55f40ce..3e4ea5e129 100644 --- a/tools/ios_xcode_template/godot_ios/main.m +++ b/tools/ios_xcode_template/godot_ios/main.m @@ -1,10 +1,31 @@ -// -// main.m -// godot_ios -// -// Created by Ariel m on 2/14/14. -// Copyright (c) 2014 Okam. All rights reserved. -// +/*************************************************************************/ +/* main.m */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ #import <UIKit/UIKit.h> diff --git a/tools/ios_xcode_template/godot_iosTests/godot_iosTests-Info.plist b/tools/ios_xcode_template/godot_iosTests/godot_iosTests-Info.plist index 3b3eec9a51..0f69aa80eb 100644 --- a/tools/ios_xcode_template/godot_iosTests/godot_iosTests-Info.plist +++ b/tools/ios_xcode_template/godot_iosTests/godot_iosTests-Info.plist @@ -7,7 +7,7 @@ <key>CFBundleExecutable</key> <string>${EXECUTABLE_NAME}</string> <key>CFBundleIdentifier</key> - <string>com.okamstudios.${PRODUCT_NAME:rfc1034identifier}</string> + <string>org.godotengine.${PRODUCT_NAME:rfc1034identifier}</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundlePackageType</key> diff --git a/tools/ios_xcode_template/godot_iosTests/godot_iosTests.m b/tools/ios_xcode_template/godot_iosTests/godot_iosTests.m index fce6288670..d9fac0a250 100644 --- a/tools/ios_xcode_template/godot_iosTests/godot_iosTests.m +++ b/tools/ios_xcode_template/godot_iosTests/godot_iosTests.m @@ -1,10 +1,31 @@ -// -// godot_iosTests.m -// godot_iosTests -// -// Created by Ariel m on 2/14/14. -// Copyright (c) 2014 Okam. All rights reserved. -// +/*************************************************************************/ +/* godot_iosTests.m */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ #import <XCTest/XCTest.h> diff --git a/tools/osx_template.app/Contents/Resources/icon.icns b/tools/osx_template.app/Contents/Resources/icon.icns Binary files differindex 18bc68d6ea..4a3dc0415a 100644 --- a/tools/osx_template.app/Contents/Resources/icon.icns +++ b/tools/osx_template.app/Contents/Resources/icon.icns diff --git a/tools/pck/SCsub b/tools/pck/SCsub index b1fed9a472..cf98ae145d 100644 --- a/tools/pck/SCsub +++ b/tools/pck/SCsub @@ -2,4 +2,3 @@ Import('env') if env["tools"] == "yes": env.add_source_files(env.tool_sources, "*.cpp") - diff --git a/tools/pck/pck_packer.cpp b/tools/pck/pck_packer.cpp index d398fefb5f..228d37df7c 100644 --- a/tools/pck/pck_packer.cpp +++ b/tools/pck/pck_packer.cpp @@ -26,7 +26,7 @@ void PCKPacker::_bind_methods() { ObjectTypeDB::bind_method(_MD("pck_start","pck_name","alignment"),&PCKPacker::pck_start); ObjectTypeDB::bind_method(_MD("add_file","pck_path","source_path"),&PCKPacker::add_file); - ObjectTypeDB::bind_method(_MD("flush"),&PCKPacker::flush); + ObjectTypeDB::bind_method(_MD("flush","verbose"),&PCKPacker::flush); }; diff --git a/tools/pe_bliss/README b/tools/pe_bliss/README new file mode 100644 index 0000000000..d5d1355444 --- /dev/null +++ b/tools/pe_bliss/README @@ -0,0 +1,84 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + + +Открытая бесплатная библиотека для работы с PE-файлами PE Bliss. +Бесплатна к использованию, модификации и распространению. +Автор: DX +(c) DX 2011-2012, kaimi.ru + +Совместимость: Windows, Linux + +Возможности: +[+] Создание PE или PE+ файла с нуля +[+] Чтение 32-разрядных и 64-разрядных PE-файлов (PE, PE+) и единообразная работа с ними +[+] Пересборка 32-разрядных и 64-разрядных PE-файлов +[+] Работа с директориями и заголовками +[+] Конвертирование адресов +[+] Чтение и редактирование секций PE-файла +[+] Чтение и редактирование таблицы импортов +[+] Чтение и редактирование таблицы экспортов +[+] Чтение и редактирование таблиц релокаций +[+] Чтение и редактирование ресурсов +[+] Чтение и редактирование TLS +[+] Чтение и редактирование конфигурации образа (image config) +[+] Чтение базовой информации .NET +[+] Чтение и редактирование информации о привязанном импорте +[+] Чтение директории исключений (только PE+) +[+] Чтение отладочной директории с расширенной информацией +[+] Вычисление энтропии +[+] Изменение файлового выравнивания +[+] Изменение базового адреса загрузки +[+] Работа с DOS Stub'ом и Rich overlay +[+] Высокоуровневое чтение ресурсов: картинки, иконки, курсоры, информация о версии, строковые таблицы, таблицы сообщений +[+] Высокоуровневое редактирование ресурсов: картинки, иконки, курсоры, информация о версии + +[English] +Open a free library for working with PE-file PE Bliss. +Free to use, modify, and distribute. +Author: DX +(c) DX 2011-2012, kaimi.ru +Compatibility: Windows, Linux + +### Capabilities: +[+] Creation of PE or PE + file from scratch +[+] Reading the 32-bit and 64-bit PE-file (PE, PE +) and uniform working with them +[+] Rebuild 32-bit and 64-bit PE-files +[+] Working with the directors and titles +[+] Converting addresses +[+] Reading and editing sections of PE-file +[+] Reading and editing the import table +[+] Reading and editing tables exports +[+] Reading and editing tables relocations +[+] Reading and editing resources +[+] Reading and editing TLS +[+] Reading and editing the configuration of the image (image config) +[+] Reading data base .NET +[+] Reading and editing information about tethered import +[+] Read the directory exceptions (only PE +) +[+] Read debug directories with extended information +[+] The calculation of entropy +[+] Changing file alignment +[+] Change the base load address +[+] Support of DOS Stub'om and Rich overlay +[+] High-level reading resources: images, icons, cursors, version information, string tables, message table +[+] High-level editing resources: images, icons, cursors, version information
\ No newline at end of file diff --git a/tools/pe_bliss/SCsub b/tools/pe_bliss/SCsub new file mode 100644 index 0000000000..34524f10ef --- /dev/null +++ b/tools/pe_bliss/SCsub @@ -0,0 +1,5 @@ +Import('env') + +env.add_source_files(env.tool_sources,"*.cpp") + +Export('env') diff --git a/tools/pe_bliss/entropy.cpp b/tools/pe_bliss/entropy.cpp new file mode 100644 index 0000000000..acefa63e83 --- /dev/null +++ b/tools/pe_bliss/entropy.cpp @@ -0,0 +1,111 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <cmath> +#include "entropy.h" +#include "utils.h" + +namespace pe_bliss +{ +//Calculates entropy for PE image section +double entropy_calculator::calculate_entropy(const section& s) +{ + if(s.get_raw_data().empty()) //Don't count entropy for empty sections + throw pe_exception("Section is empty", pe_exception::section_is_empty); + + return calculate_entropy(s.get_raw_data().data(), s.get_raw_data().length()); +} + +//Calculates entropy for istream (from current position of stream) +double entropy_calculator::calculate_entropy(std::istream& file) +{ + uint32_t byte_count[256] = {0}; //Byte count for each of 255 bytes + + if(file.bad()) + throw pe_exception("Stream is bad", pe_exception::stream_is_bad); + + std::streamoff pos = file.tellg(); + + std::streamoff length = pe_utils::get_file_size(file); + length -= file.tellg(); + + if(!length) //Don't calculate entropy for empty buffers + throw pe_exception("Data length is zero", pe_exception::data_is_empty); + + //Count bytes + for(std::streamoff i = 0; i != length; ++i) + ++byte_count[static_cast<unsigned char>(file.get())]; + + file.seekg(pos); + + return calculate_entropy(byte_count, length); +} + +//Calculates entropy for data block +double entropy_calculator::calculate_entropy(const char* data, size_t length) +{ + uint32_t byte_count[256] = {0}; //Byte count for each of 255 bytes + + if(!length) //Don't calculate entropy for empty buffers + throw pe_exception("Data length is zero", pe_exception::data_is_empty); + + //Count bytes + for(size_t i = 0; i != length; ++i) + ++byte_count[static_cast<unsigned char>(data[i])]; + + return calculate_entropy(byte_count, length); +} + +//Calculates entropy for this PE file (only section data) +double entropy_calculator::calculate_entropy(const pe_base& pe) +{ + uint32_t byte_count[256] = {0}; //Byte count for each of 255 bytes + + size_t total_data_length = 0; + + //Count bytes for each section + for(section_list::const_iterator it = pe.get_image_sections().begin(); it != pe.get_image_sections().end(); ++it) + { + const std::string& data = (*it).get_raw_data(); + size_t length = data.length(); + total_data_length += length; + for(size_t i = 0; i != length; ++i) + ++byte_count[static_cast<unsigned char>(data[i])]; + } + + return calculate_entropy(byte_count, total_data_length); +} + +//Calculates entropy from bytes count +double entropy_calculator::calculate_entropy(const uint32_t byte_count[256], std::streamoff total_length) +{ + double entropy = 0.; //Entropy result value + //Calculate entropy + for(uint32_t i = 0; i < 256; ++i) + { + double temp = static_cast<double>(byte_count[i]) / total_length; + if(temp > 0.) + entropy += std::abs(temp * (std::log(temp) * pe_utils::log_2)); + } + + return entropy; +} +} diff --git a/tools/pe_bliss/entropy.h b/tools/pe_bliss/entropy.h new file mode 100644 index 0000000000..7d225a3e32 --- /dev/null +++ b/tools/pe_bliss/entropy.h @@ -0,0 +1,51 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <istream> +#include "pe_base.h" + +namespace pe_bliss +{ +class entropy_calculator +{ +public: + //Calculates entropy for PE image section + static double calculate_entropy(const section& s); + + //Calculates entropy for istream (from current position of stream) + static double calculate_entropy(std::istream& file); + + //Calculates entropy for data block + static double calculate_entropy(const char* data, size_t length); + + //Calculates entropy for this PE file (only section data) + static double calculate_entropy(const pe_base& pe); + +private: + entropy_calculator(); + entropy_calculator(const entropy_calculator&); + entropy_calculator& operator=(const entropy_calculator&); + + //Calculates entropy from bytes count + static double calculate_entropy(const uint32_t byte_count[256], std::streamoff total_length); +}; +} diff --git a/tools/pe_bliss/file_version_info.cpp b/tools/pe_bliss/file_version_info.cpp new file mode 100644 index 0000000000..3f2ba454b4 --- /dev/null +++ b/tools/pe_bliss/file_version_info.cpp @@ -0,0 +1,440 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include "file_version_info.h" +#include "pe_structures.h" + +namespace pe_bliss +{ +using namespace pe_win; + +//Default constructor +file_version_info::file_version_info() + :file_version_ms_(0), file_version_ls_(0), + product_version_ms_(0), product_version_ls_(0), + file_flags_(0), + file_os_(0), + file_type_(0), file_subtype_(0), + file_date_ms_(0), file_date_ls_(0) +{} + +//Constructor from Windows fixed version info structure +file_version_info::file_version_info(const vs_fixedfileinfo& info) + :file_version_ms_(info.dwFileVersionMS), file_version_ls_(info.dwFileVersionLS), + product_version_ms_(info.dwProductVersionMS), product_version_ls_(info.dwProductVersionLS), + file_flags_(info.dwFileFlags), + file_os_(info.dwFileOS), + file_type_(info.dwFileType), file_subtype_(info.dwFileSubtype), + file_date_ms_(info.dwFileDateMS), file_date_ls_(info.dwFileDateLS) +{} + +//Returns true if file is debug-built +bool file_version_info::is_debug() const +{ + return file_flags_ & vs_ff_debug ? true : false; +} + +//Returns true if file is release-built +bool file_version_info::is_prerelease() const +{ + return file_flags_ & vs_ff_prerelease ? true : false; +} + +//Returns true if file is patched +bool file_version_info::is_patched() const +{ + return file_flags_ & vs_ff_patched ? true : false; +} + +//Returns true if private build +bool file_version_info::is_private_build() const +{ + return file_flags_ & vs_ff_privatebuild ? true : false; +} + +//Returns true if special build +bool file_version_info::is_special_build() const +{ + return file_flags_ & vs_ff_specialbuild ? true : false; +} + +//Returns true if info inferred +bool file_version_info::is_info_inferred() const +{ + return file_flags_ & vs_ff_infoinferred ? true : false; +} + +//Retuens file flags (raw DWORD) +uint32_t file_version_info::get_file_flags() const +{ + return file_flags_; +} + +//Returns file version most significant DWORD +uint32_t file_version_info::get_file_version_ms() const +{ + return file_version_ms_; +} + +//Returns file version least significant DWORD +uint32_t file_version_info::get_file_version_ls() const +{ + return file_version_ls_; +} + +//Returns product version most significant DWORD +uint32_t file_version_info::get_product_version_ms() const +{ + return product_version_ms_; +} + +//Returns product version least significant DWORD +uint32_t file_version_info::get_product_version_ls() const +{ + return product_version_ls_; +} + +//Returns file OS type (raw DWORD) +uint32_t file_version_info::get_file_os_raw() const +{ + return file_os_; +} + +//Returns file OS type +file_version_info::file_os_type file_version_info::get_file_os() const +{ + //Determine file operation system type + switch(file_os_) + { + case vos_dos: + return file_os_dos; + + case vos_os216: + return file_os_os216; + + case vos_os232: + return file_os_os232; + + case vos_nt: + return file_os_nt; + + case vos_wince: + return file_os_wince; + + case vos__windows16: + return file_os_win16; + + case vos__pm16: + return file_os_pm16; + + case vos__pm32: + return file_os_pm32; + + case vos__windows32: + return file_os_win32; + + case vos_dos_windows16: + return file_os_dos_win16; + + case vos_dos_windows32: + return file_os_dos_win32; + + case vos_os216_pm16: + return file_os_os216_pm16; + + case vos_os232_pm32: + return file_os_os232_pm32; + + case vos_nt_windows32: + return file_os_nt_win32; + } + + return file_os_unknown; +} + +//Returns file type (raw DWORD) +uint32_t file_version_info::get_file_type_raw() const +{ + return file_type_; +} + +//Returns file type +file_version_info::file_type file_version_info::get_file_type() const +{ + //Determine file type + switch(file_type_) + { + case vft_app: + return file_type_application; + + case vft_dll: + return file_type_dll; + + case vft_drv: + return file_type_driver; + + case vft_font: + return file_type_font; + + case vft_vxd: + return file_type_vxd; + + case vft_static_lib: + return file_type_static_lib; + } + + return file_type_unknown; +} + +//Returns file subtype (usually non-zero for drivers and fonts) +uint32_t file_version_info::get_file_subtype() const +{ + return file_subtype_; +} + +//Returns file date most significant DWORD +uint32_t file_version_info::get_file_date_ms() const +{ + return file_date_ms_; +} + +//Returns file date least significant DWORD +uint32_t file_version_info::get_file_date_ls() const +{ + return file_date_ls_; +} + +//Helper to set file flag +void file_version_info::set_file_flag(uint32_t flag) +{ + file_flags_ |= flag; +} + +//Helper to clear file flag +void file_version_info::clear_file_flag(uint32_t flag) +{ + file_flags_ &= ~flag; +} + +//Helper to set or clear file flag +void file_version_info::set_file_flag(uint32_t flag, bool set_flag) +{ + set_flag ? set_file_flag(flag) : clear_file_flag(flag); +} + +//Sets if file is debug-built +void file_version_info::set_debug(bool debug) +{ + set_file_flag(vs_ff_debug, debug); +} + +//Sets if file is prerelease +void file_version_info::set_prerelease(bool prerelease) +{ + set_file_flag(vs_ff_prerelease, prerelease); +} + +//Sets if file is patched +void file_version_info::set_patched(bool patched) +{ + set_file_flag(vs_ff_patched, patched); +} + +//Sets if private build +void file_version_info::set_private_build(bool private_build) +{ + set_file_flag(vs_ff_privatebuild, private_build); +} + +//Sets if special build +void file_version_info::set_special_build(bool special_build) +{ + set_file_flag(vs_ff_specialbuild, special_build); +} + +//Sets if info inferred +void file_version_info::set_info_inferred(bool info_inferred) +{ + set_file_flag(vs_ff_infoinferred, info_inferred); +} + +//Sets flags (raw DWORD) +void file_version_info::set_file_flags(uint32_t file_flags) +{ + file_flags_ = file_flags; +} + +//Sets file version most significant DWORD +void file_version_info::set_file_version_ms(uint32_t file_version_ms) +{ + file_version_ms_ = file_version_ms; +} + +//Sets file version least significant DWORD +void file_version_info::set_file_version_ls(uint32_t file_version_ls) +{ + file_version_ls_ = file_version_ls; +} + +//Sets product version most significant DWORD +void file_version_info::set_product_version_ms(uint32_t product_version_ms) +{ + product_version_ms_ = product_version_ms; +} + +//Sets product version least significant DWORD +void file_version_info::set_product_version_ls(uint32_t product_version_ls) +{ + product_version_ls_ = product_version_ls; +} + +//Sets file OS type (raw DWORD) +void file_version_info::set_file_os_raw(uint32_t file_os) +{ + file_os_ = file_os; +} + +//Sets file OS type +void file_version_info::set_file_os(file_os_type file_os) +{ + //Determine file operation system type + switch(file_os) + { + case file_os_dos: + file_os_ = vos_dos; + return; + + case file_os_os216: + file_os_ = vos_os216; + return; + + case file_os_os232: + file_os_ = vos_os232; + return; + + case file_os_nt: + file_os_ = vos_nt; + return; + + case file_os_wince: + file_os_ = vos_wince; + return; + + case file_os_win16: + file_os_ = vos__windows16; + return; + + case file_os_pm16: + file_os_ = vos__pm16; + return; + + case file_os_pm32: + file_os_ = vos__pm32; + return; + + case file_os_win32: + file_os_ = vos__windows32; + return; + + case file_os_dos_win16: + file_os_ = vos_dos_windows16; + return; + + case file_os_dos_win32: + file_os_ = vos_dos_windows32; + return; + + case file_os_os216_pm16: + file_os_ = vos_os216_pm16; + return; + + case file_os_os232_pm32: + file_os_ = vos_os232_pm32; + return; + + case file_os_nt_win32: + file_os_ = vos_nt_windows32; + return; + + default: + return; + } +} + +//Sets file type (raw DWORD) +void file_version_info::set_file_type_raw(uint32_t file_type) +{ + file_type_ = file_type; +} + +//Sets file type +void file_version_info::set_file_type(file_type file_type) +{ + //Determine file type + switch(file_type) + { + case file_type_application: + file_type_ = vft_app; + return; + + case file_type_dll: + file_type_ = vft_dll; + return; + + case file_type_driver: + file_type_ = vft_drv; + return; + + case file_type_font: + file_type_ = vft_font; + return; + + case file_type_vxd: + file_type_ = vft_vxd; + return; + + case file_type_static_lib: + file_type_ = vft_static_lib; + return; + + default: + return; + } +} + +//Sets file subtype (usually non-zero for drivers and fonts) +void file_version_info::set_file_subtype(uint32_t file_subtype) +{ + file_subtype_ = file_subtype; +} + +//Sets file date most significant DWORD +void file_version_info::set_file_date_ms(uint32_t file_date_ms) +{ + file_date_ms_ = file_date_ms; +} + +//Sets file date least significant DWORD +void file_version_info::set_file_date_ls(uint32_t file_date_ls) +{ + file_date_ls_ = file_date_ls; +} +} diff --git a/tools/pe_bliss/file_version_info.h b/tools/pe_bliss/file_version_info.h new file mode 100644 index 0000000000..d898351ba1 --- /dev/null +++ b/tools/pe_bliss/file_version_info.h @@ -0,0 +1,199 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <string> +#include <map> +#include "stdint_defs.h" +#include "pe_structures.h" + +namespace pe_bliss +{ +//Structure representing fixed file version info +class file_version_info +{ +public: + //Enumeration of file operating system types + enum file_os_type + { + file_os_unknown, + file_os_dos, + file_os_os216, + file_os_os232, + file_os_nt, + file_os_wince, + file_os_win16, + file_os_pm16, + file_os_pm32, + file_os_win32, + file_os_dos_win16, + file_os_dos_win32, + file_os_os216_pm16, + file_os_os232_pm32, + file_os_nt_win32 + }; + + //Enumeration of file types + enum file_type + { + file_type_unknown, + file_type_application, + file_type_dll, + file_type_driver, + file_type_font, + file_type_vxd, + file_type_static_lib + }; + +public: + //Default constructor + file_version_info(); + //Constructor from Windows fixed version info structure + explicit file_version_info(const pe_win::vs_fixedfileinfo& info); + +public: //Getters + //Returns true if file is debug-built + bool is_debug() const; + //Returns true if file is prerelease + bool is_prerelease() const; + //Returns true if file is patched + bool is_patched() const; + //Returns true if private build + bool is_private_build() const; + //Returns true if special build + bool is_special_build() const; + //Returns true if info inferred + bool is_info_inferred() const; + //Retuens file flags (raw DWORD) + uint32_t get_file_flags() const; + + //Returns file version most significant DWORD + uint32_t get_file_version_ms() const; + //Returns file version least significant DWORD + uint32_t get_file_version_ls() const; + //Returns product version most significant DWORD + uint32_t get_product_version_ms() const; + //Returns product version least significant DWORD + uint32_t get_product_version_ls() const; + + //Returns file OS type (raw DWORD) + uint32_t get_file_os_raw() const; + //Returns file OS type + file_os_type get_file_os() const; + + //Returns file type (raw DWORD) + uint32_t get_file_type_raw() const; + //Returns file type + file_type get_file_type() const; + + //Returns file subtype (usually non-zero for drivers and fonts) + uint32_t get_file_subtype() const; + + //Returns file date most significant DWORD + uint32_t get_file_date_ms() const; + //Returns file date least significant DWORD + uint32_t get_file_date_ls() const; + + //Returns file version string + template<typename T> + const std::basic_string<T> get_file_version_string() const + { + return get_version_string<T>(file_version_ms_, file_version_ls_); + } + + //Returns product version string + template<typename T> + const std::basic_string<T> get_product_version_string() const + { + return get_version_string<T>(product_version_ms_, product_version_ls_); + } + +public: //Setters + //Sets if file is debug-built + void set_debug(bool debug); + //Sets if file is prerelease + void set_prerelease(bool prerelease); + //Sets if file is patched + void set_patched(bool patched); + //Sets if private build + void set_private_build(bool private_build); + //Sets if special build + void set_special_build(bool special_build); + //Sets if info inferred + void set_info_inferred(bool info_inferred); + //Sets flags (raw DWORD) + void set_file_flags(uint32_t file_flags); + + //Sets file version most significant DWORD + void set_file_version_ms(uint32_t file_version_ms); + //Sets file version least significant DWORD + void set_file_version_ls(uint32_t file_version_ls); + //Sets product version most significant DWORD + void set_product_version_ms(uint32_t product_version_ms); + //Sets product version least significant DWORD + void set_product_version_ls(uint32_t product_version_ls); + + //Sets file OS type (raw DWORD) + void set_file_os_raw(uint32_t file_os); + //Sets file OS type + void set_file_os(file_os_type file_os); + + //Sets file type (raw DWORD) + void set_file_type_raw(uint32_t file_type); + //Sets file type + void set_file_type(file_type file_type); + + //Sets file subtype (usually non-zero for drivers and fonts) + void set_file_subtype(uint32_t file_subtype); + + //Sets file date most significant DWORD + void set_file_date_ms(uint32_t file_date_ms); + //Sets file date least significant DWORD + void set_file_date_ls(uint32_t file_date_ls); + +private: + //Helper to convert version DWORDs to string + template<typename T> + static const std::basic_string<T> get_version_string(uint32_t ms, uint32_t ls) + { + std::basic_stringstream<T> ss; + ss << (ms >> 16) << static_cast<T>(L'.') + << (ms & 0xFFFF) << static_cast<T>(L'.') + << (ls >> 16) << static_cast<T>(L'.') + << (ls & 0xFFFF); + return ss.str(); + } + + //Helper to set file flag + void set_file_flag(uint32_t flag); + //Helper to clear file flag + void clear_file_flag(uint32_t flag); + //Helper to set or clear file flag + void set_file_flag(uint32_t flag, bool set_flag); + + uint32_t file_version_ms_, file_version_ls_, + product_version_ms_, product_version_ls_; + uint32_t file_flags_; + uint32_t file_os_; + uint32_t file_type_, file_subtype_; + uint32_t file_date_ms_, file_date_ls_; +}; +} diff --git a/tools/pe_bliss/message_table.cpp b/tools/pe_bliss/message_table.cpp new file mode 100644 index 0000000000..909be5d494 --- /dev/null +++ b/tools/pe_bliss/message_table.cpp @@ -0,0 +1,81 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include "message_table.h" +#include "utils.h" + +namespace pe_bliss +{ +//Default constructor +message_table_item::message_table_item() + :unicode_(false) +{} + +//Constructor from ANSI string +message_table_item::message_table_item(const std::string& str) + :unicode_(false), ansi_str_(str) +{ + pe_utils::strip_nullbytes(ansi_str_); +} + +//Constructor from UNICODE string +message_table_item::message_table_item(const std::wstring& str) + :unicode_(true), unicode_str_(str) +{ + pe_utils::strip_nullbytes(unicode_str_); +} + +//Returns true if contained string is unicode +bool message_table_item::is_unicode() const +{ + return unicode_; +} + +//Returns ANSI string +const std::string& message_table_item::get_ansi_string() const +{ + return ansi_str_; +} + +//Returns UNICODE string +const std::wstring& message_table_item::get_unicode_string() const +{ + return unicode_str_; +} + +//Sets ANSI string (clears UNICODE one) +void message_table_item::set_string(const std::string& str) +{ + ansi_str_ = str; + pe_utils::strip_nullbytes(ansi_str_); + unicode_str_.clear(); + unicode_ = false; +} + +//Sets UNICODE string (clears ANSI one) +void message_table_item::set_string(const std::wstring& str) +{ + unicode_str_ = str; + pe_utils::strip_nullbytes(unicode_str_); + ansi_str_.clear(); + unicode_ = true; +} +} diff --git a/tools/pe_bliss/message_table.h b/tools/pe_bliss/message_table.h new file mode 100644 index 0000000000..5a3feb32c1 --- /dev/null +++ b/tools/pe_bliss/message_table.h @@ -0,0 +1,56 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <string> +#include <map> +#include "stdint_defs.h" + +namespace pe_bliss +{ +//Structure representing message table string +class message_table_item +{ +public: + //Default constructor + message_table_item(); + //Constructors from ANSI and UNICODE strings + explicit message_table_item(const std::string& str); + explicit message_table_item(const std::wstring& str); + + //Returns true if string is UNICODE + bool is_unicode() const; + //Returns ANSI string + const std::string& get_ansi_string() const; + //Returns UNICODE string + const std::wstring& get_unicode_string() const; + +public: + //Sets ANSI or UNICODE string + void set_string(const std::string& str); + void set_string(const std::wstring& str); + +private: + bool unicode_; + std::string ansi_str_; + std::wstring unicode_str_; +}; +} diff --git a/tools/pe_bliss/pe_base.cpp b/tools/pe_bliss/pe_base.cpp new file mode 100644 index 0000000000..97baa17cb3 --- /dev/null +++ b/tools/pe_bliss/pe_base.cpp @@ -0,0 +1,1680 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <string> +#include <vector> +#include <istream> +#include <ostream> +#include <algorithm> +#include <cmath> +#include <set> +#include <string.h> +#include "pe_exception.h" +#include "pe_base.h" + +namespace pe_bliss +{ +using namespace pe_win; + +//Constructor +pe_base::pe_base(std::istream& file, const pe_properties& props, bool read_debug_raw_data) +{ + props_ = props.duplicate().release(); + + //Save istream state + std::ios_base::iostate state = file.exceptions(); + std::streamoff old_offset = file.tellg(); + + try + { + file.exceptions(std::ios::goodbit); + //Read DOS header, PE headers and section data + read_dos_header(file); + read_pe(file, read_debug_raw_data); + } + catch(const std::exception&) + { + //If something went wrong, restore istream state + file.seekg(old_offset); + file.exceptions(state); + file.clear(); + //Rethrow + throw; + } + + //Restore istream state + file.seekg(old_offset); + file.exceptions(state); + file.clear(); +} + +pe_base::pe_base(const pe_properties& props, uint32_t section_alignment, bool dll, uint16_t subsystem) +{ + props_ = props.duplicate().release(); + props_->create_pe(section_alignment, subsystem); + + has_overlay_ = false; + memset(&dos_header_, 0, sizeof(dos_header_)); + + dos_header_.e_magic = 0x5A4D; //"MZ" + //Magic numbers from MSVC++ build + dos_header_.e_maxalloc = 0xFFFF; + dos_header_.e_cblp = 0x90; + dos_header_.e_cp = 3; + dos_header_.e_cparhdr = 4; + dos_header_.e_sp = 0xB8; + dos_header_.e_lfarlc = 64; + + set_characteristics(image_file_executable_image | image_file_relocs_stripped); + + if(get_pe_type() == pe_type_32) + set_characteristics_flags(image_file_32bit_machine); + + if(dll) + set_characteristics_flags(image_file_dll); + + set_subsystem_version(5, 1); //WinXP + set_os_version(5, 1); //WinXP +} + +pe_base::pe_base(const pe_base& pe) + :dos_header_(pe.dos_header_), + rich_overlay_(pe.rich_overlay_), + sections_(pe.sections_), + has_overlay_(pe.has_overlay_), + full_headers_data_(pe.full_headers_data_), + debug_data_(pe.debug_data_), + props_(0) +{ + props_ = pe.props_->duplicate().release(); +} + +pe_base& pe_base::operator=(const pe_base& pe) +{ + dos_header_ = pe.dos_header_; + rich_overlay_ = pe.rich_overlay_; + sections_ = pe.sections_; + has_overlay_ = pe.has_overlay_; + full_headers_data_ = pe.full_headers_data_; + debug_data_ = pe.debug_data_; + delete props_; + props_ = 0; + props_ = pe.props_->duplicate().release(); + + return *this; +} + +pe_base::~pe_base() +{ + delete props_; +} + +//Returns dos header +const image_dos_header& pe_base::get_dos_header() const +{ + return dos_header_; +} + +//Returns dos header +image_dos_header& pe_base::get_dos_header() +{ + return dos_header_; +} + +//Returns PE headers start position (e_lfanew) +int32_t pe_base::get_pe_header_start() const +{ + return dos_header_.e_lfanew; +} + +//Strips MSVC stub overlay +void pe_base::strip_stub_overlay() +{ + rich_overlay_.clear(); +} + +//Fills MSVC stub overlay with character c +void pe_base::fill_stub_overlay(char c) +{ + if(rich_overlay_.length()) + rich_overlay_.assign(rich_overlay_.length(), c); +} + +//Sets stub MSVS overlay +void pe_base::set_stub_overlay(const std::string& data) +{ + rich_overlay_ = data; +} + +//Returns stub overlay +const std::string& pe_base::get_stub_overlay() const +{ + return rich_overlay_; +} + +//Realigns all sections +void pe_base::realign_all_sections() +{ + for(unsigned int i = 0; i < sections_.size(); i++) + realign_section(i); +} + +//Returns number of sections from PE header +uint16_t pe_base::get_number_of_sections() const +{ + return props_->get_number_of_sections(); +} + +//Updates number of sections in PE header +uint16_t pe_base::update_number_of_sections() +{ + uint16_t new_number = static_cast<uint16_t>(sections_.size()); + props_->set_number_of_sections(new_number); + return new_number; +} + +//Returns section alignment +uint32_t pe_base::get_section_alignment() const +{ + return props_->get_section_alignment(); +} + +//Returns image sections list +section_list& pe_base::get_image_sections() +{ + return sections_; +} + +//Returns image sections list +const section_list& pe_base::get_image_sections() const +{ + return sections_; +} + +//Realigns section by index +void pe_base::realign_section(uint32_t index) +{ + //Check index + if(sections_.size() <= index) + throw pe_exception("Section not found", pe_exception::section_not_found); + + //Get section iterator + section_list::iterator it = sections_.begin() + index; + section& s = *it; + + //Calculate, how many null bytes we have in the end of raw section data + std::size_t strip = 0; + for(std::size_t i = (*it).get_raw_data().length(); i >= 1; --i) + { + if(s.get_raw_data()[i - 1] == 0) + strip++; + else + break; + } + + if(it == sections_.end() - 1) //If we're realigning the last section + { + //We can strip ending null bytes + s.set_size_of_raw_data(static_cast<uint32_t>(s.get_raw_data().length() - strip)); + s.get_raw_data().resize(s.get_raw_data().length() - strip, 0); + } + else + { + //Else just set size of raw data + uint32_t raw_size_aligned = s.get_aligned_raw_size(get_file_alignment()); + s.set_size_of_raw_data(raw_size_aligned); + s.get_raw_data().resize(raw_size_aligned, 0); + } +} + +//Returns file alignment +uint32_t pe_base::get_file_alignment() const +{ + return props_->get_file_alignment(); +} + +//Sets file alignment +void pe_base::set_file_alignment(uint32_t alignment) +{ + //Check alignment + if(alignment < minimum_file_alignment) + throw pe_exception("File alignment can't be less than 512", pe_exception::incorrect_file_alignment); + + if(!pe_utils::is_power_of_2(alignment)) + throw pe_exception("File alignment must be a power of 2", pe_exception::incorrect_file_alignment); + + if(alignment > get_section_alignment()) + throw pe_exception("File alignment must be <= section alignment", pe_exception::incorrect_file_alignment); + + //Set file alignment without any additional checks + set_file_alignment_unchecked(alignment); +} + +//Returns size of image +uint32_t pe_base::get_size_of_image() const +{ + return props_->get_size_of_image(); +} + +//Returns image entry point +uint32_t pe_base::get_ep() const +{ + return props_->get_ep(); +} + +//Sets image entry point (just a value of PE header) +void pe_base::set_ep(uint32_t new_ep) +{ + props_->set_ep(new_ep); +} + +//Returns number of RVA and sizes (number of DATA_DIRECTORY entries) +uint32_t pe_base::get_number_of_rvas_and_sizes() const +{ + return props_->get_number_of_rvas_and_sizes(); +} + +//Sets number of RVA and sizes (number of DATA_DIRECTORY entries) +void pe_base::set_number_of_rvas_and_sizes(uint32_t number) +{ + props_->set_number_of_rvas_and_sizes(number); +} + +//Returns PE characteristics +uint16_t pe_base::get_characteristics() const +{ + return props_->get_characteristics(); +} + +//Sets PE characteristics (a value inside header) +void pe_base::set_characteristics(uint16_t ch) +{ + props_->set_characteristics(ch); +} + +//Returns section from RVA +section& pe_base::section_from_rva(uint32_t rva) +{ + //Search for section + for(section_list::iterator i = sections_.begin(); i != sections_.end(); ++i) + { + section& s = *i; + //Return section if found + if(rva >= s.get_virtual_address() && rva < s.get_virtual_address() + s.get_aligned_virtual_size(get_section_alignment())) + return s; + } + + throw pe_exception("No section found by presented address", pe_exception::no_section_found); +} + +//Returns section from RVA +const section& pe_base::section_from_rva(uint32_t rva) const +{ + //Search for section + for(section_list::const_iterator i = sections_.begin(); i != sections_.end(); ++i) + { + const section& s = *i; + //Return section if found + if(rva >= s.get_virtual_address() && rva < s.get_virtual_address() + s.get_aligned_virtual_size(get_section_alignment())) + return s; + } + + throw pe_exception("No section found by presented address", pe_exception::no_section_found); +} + +//Returns section from directory ID +section& pe_base::section_from_directory(uint32_t directory_id) +{ + return section_from_rva(get_directory_rva(directory_id)); +} + +//Returns section from directory ID +const section& pe_base::section_from_directory(uint32_t directory_id) const +{ + return section_from_rva(get_directory_rva(directory_id)); +} + +//Sets section virtual size (actual for the last one of this PE or for unbound section) +void pe_base::set_section_virtual_size(section& s, uint32_t vsize) +{ + //Check if we're changing virtual size of the last section + //Of course, we can change virtual size of section that's not bound to this PE file + if(sections_.empty() || std::find_if(sections_.begin(), sections_.end() - 1, section_ptr_finder(s)) != sections_.end() - 1) + throw pe_exception("Can't change virtual size of any section, except last one", pe_exception::error_changing_section_virtual_size); + + //If we're setting virtual size to zero + if(vsize == 0) + { + //Check if section is empty + if(s.empty()) + throw pe_exception("Cannot set virtual size of empty section to zero", pe_exception::error_changing_section_virtual_size); + + //Set virtual size equal to aligned size of raw data + s.set_virtual_size(s.get_size_of_raw_data()); + } + else + { + s.set_virtual_size(vsize); + } + + //Update image size if we're changing virtual size for the last section of this PE + if(!sections_.empty() || &s == &(*(sections_.end() - 1))) + update_image_size(); +} + +//Expands section raw or virtual size to hold data from specified RVA with specified size +//Section must be free (not bound to any image) +//or the last section of this image +bool pe_base::expand_section(section& s, uint32_t needed_rva, uint32_t needed_size, section_expand_type expand) +{ + //Check if we're changing the last section + //Of course, we can change the section that's not bound to this PE file + if(sections_.empty() || std::find_if(sections_.begin(), sections_.end() - 1, section_ptr_finder(s)) != sections_.end() - 1) + throw pe_exception("Can't expand any section, except last one", pe_exception::error_expanding_section); + + //Check if we should expand our section + if(expand == expand_section_raw && section_data_length_from_rva(s, needed_rva, section_data_raw) < needed_size) + { + //Expand section raw data + s.get_raw_data().resize(needed_rva - s.get_virtual_address() + needed_size); + recalculate_section_sizes(s, false); + return true; + } + else if(expand == expand_section_virtual && section_data_length_from_rva(s, needed_rva, section_data_virtual) < needed_size) + { + //Expand section virtual data + set_section_virtual_size(s, needed_rva - s.get_virtual_address() + needed_size); + return true; + } + + return false; +} + +//Updates image virtual size +void pe_base::update_image_size() +{ + //Write virtual size of image to headers + if(!sections_.empty()) + set_size_of_image(sections_.back().get_virtual_address() + sections_.back().get_aligned_virtual_size(get_section_alignment())); + else + set_size_of_image(get_size_of_headers()); +} + +//Returns checksum of PE file from header +uint32_t pe_base::get_checksum() const +{ + return props_->get_checksum(); +} + +//Sets checksum of PE file +void pe_base::set_checksum(uint32_t checksum) +{ + props_->set_checksum(checksum); +} + +//Returns timestamp of PE file from header +uint32_t pe_base::get_time_date_stamp() const +{ + return props_->get_time_date_stamp(); +} + +//Sets timestamp of PE file +void pe_base::set_time_date_stamp(uint32_t timestamp) +{ + props_->set_time_date_stamp(timestamp); +} + +//Returns Machine field value of PE file from header +uint16_t pe_base::get_machine() const +{ + return props_->get_machine(); +} + +//Sets Machine field value of PE file +void pe_base::set_machine(uint16_t machine) +{ + props_->set_machine(machine); +} + +//Prepares section before attaching it +void pe_base::prepare_section(section& s) +{ + //Calculate its size of raw data + s.set_size_of_raw_data(static_cast<uint32_t>(pe_utils::align_up(s.get_raw_data().length(), get_file_alignment()))); + + //Check section virtual and raw size + if(!s.get_size_of_raw_data() && !s.get_virtual_size()) + throw pe_exception("Virtual and Physical sizes of section can't be 0 at the same time", pe_exception::zero_section_sizes); + + //If section virtual size is zero + if(!s.get_virtual_size()) + { + s.set_virtual_size(s.get_size_of_raw_data()); + } + else + { + //Else calculate its virtual size + s.set_virtual_size( + std::max<uint32_t>(pe_utils::align_up(s.get_size_of_raw_data(), get_file_alignment()), + pe_utils::align_up(s.get_virtual_size(), get_section_alignment()))); + } +} + +//Adds section to image +section& pe_base::add_section(section s) +{ + if(sections_.size() >= maximum_number_of_sections) + throw pe_exception("Maximum number of sections has been reached", pe_exception::no_more_sections_can_be_added); + + //Prepare section before adding it + prepare_section(s); + + //Calculate section virtual address + if(!sections_.empty()) + { + s.set_virtual_address(pe_utils::align_up(sections_.back().get_virtual_address() + sections_.back().get_aligned_virtual_size(get_section_alignment()), get_section_alignment())); + + //We should align last section raw size, if it wasn't aligned + section& last = sections_.back(); + last.set_size_of_raw_data(static_cast<uint32_t>(pe_utils::align_up(last.get_raw_data().length(), get_file_alignment()))); + } + else + { + s.set_virtual_address( + s.get_virtual_address() == 0 + ? pe_utils::align_up(get_size_of_headers(), get_section_alignment()) + : pe_utils::align_up(s.get_virtual_address(), get_section_alignment())); + } + + //Add section to the end of section list + sections_.push_back(s); + //Set number of sections in PE header + set_number_of_sections(static_cast<uint16_t>(sections_.size())); + //Recalculate virtual size of image + set_size_of_image(get_size_of_image() + s.get_aligned_virtual_size(get_section_alignment())); + //Return last section + return sections_.back(); +} + +//Returns true if sectios "s" is already attached to this PE file +bool pe_base::section_attached(const section& s) const +{ + return sections_.end() != std::find_if(sections_.begin(), sections_.end(), section_ptr_finder(s)); +} + +//Returns true if directory exists +bool pe_base::directory_exists(uint32_t id) const +{ + return props_->directory_exists(id); +} + +//Removes directory +void pe_base::remove_directory(uint32_t id) +{ + props_->remove_directory(id); +} + +//Returns directory RVA +uint32_t pe_base::get_directory_rva(uint32_t id) const +{ + return props_->get_directory_rva(id); +} + +//Returns directory size +uint32_t pe_base::get_directory_size(uint32_t id) const +{ + return props_->get_directory_size(id); +} + +//Sets directory RVA (just a value of PE header, no moving occurs) +void pe_base::set_directory_rva(uint32_t id, uint32_t rva) +{ + return props_->set_directory_rva(id, rva); +} + +//Sets directory size (just a value of PE header, no moving occurs) +void pe_base::set_directory_size(uint32_t id, uint32_t size) +{ + return props_->set_directory_size(id, size); +} + +//Strips only zero DATA_DIRECTORY entries to count = min_count +//Returns resulting number of data directories +//strip_iat_directory - if true, even not empty IAT directory will be stripped +uint32_t pe_base::strip_data_directories(uint32_t min_count, bool strip_iat_directory) +{ + return props_->strip_data_directories(min_count, strip_iat_directory); +} + +//Returns true if image has import directory +bool pe_base::has_imports() const +{ + return directory_exists(image_directory_entry_import); +} + +//Returns true if image has export directory +bool pe_base::has_exports() const +{ + return directory_exists(image_directory_entry_export); +} + +//Returns true if image has resource directory +bool pe_base::has_resources() const +{ + return directory_exists(image_directory_entry_resource); +} + +//Returns true if image has security directory +bool pe_base::has_security() const +{ + return directory_exists(image_directory_entry_security); +} + +//Returns true if image has relocations +bool pe_base::has_reloc() const +{ + return directory_exists(image_directory_entry_basereloc) && !(get_characteristics() & image_file_relocs_stripped); +} + +//Returns true if image has TLS directory +bool pe_base::has_tls() const +{ + return directory_exists(image_directory_entry_tls); +} + +//Returns true if image has config directory +bool pe_base::has_config() const +{ + return directory_exists(image_directory_entry_load_config); +} + +//Returns true if image has bound import directory +bool pe_base::has_bound_import() const +{ + return directory_exists(image_directory_entry_bound_import); +} + +//Returns true if image has delay import directory +bool pe_base::has_delay_import() const +{ + return directory_exists(image_directory_entry_delay_import); +} + +//Returns true if image has COM directory +bool pe_base::is_dotnet() const +{ + return directory_exists(image_directory_entry_com_descriptor); +} + +//Returns true if image has exception directory +bool pe_base::has_exception_directory() const +{ + return directory_exists(image_directory_entry_exception); +} + +//Returns true if image has debug directory +bool pe_base::has_debug() const +{ + return directory_exists(image_directory_entry_debug); +} + +//Returns corresponding section data pointer from RVA inside section "s" (checks bounds) +char* pe_base::section_data_from_rva(section& s, uint32_t rva) +{ + //Check if RVA is inside section "s" + if(rva >= s.get_virtual_address() && rva < s.get_virtual_address() + s.get_aligned_virtual_size(get_section_alignment())) + { + if(s.get_raw_data().empty()) + throw pe_exception("Section raw data is empty and cannot be changed", pe_exception::section_is_empty); + + return &s.get_raw_data()[rva - s.get_virtual_address()]; + } + + throw pe_exception("RVA not found inside section", pe_exception::rva_not_exists); +} + +//Returns corresponding section data pointer from RVA inside section "s" (checks bounds) +const char* pe_base::section_data_from_rva(const section& s, uint32_t rva, section_data_type datatype) const +{ + //Check if RVA is inside section "s" + if(rva >= s.get_virtual_address() && rva < s.get_virtual_address() + s.get_aligned_virtual_size(get_section_alignment())) + return (datatype == section_data_raw ? s.get_raw_data().data() : s.get_virtual_data(get_section_alignment()).c_str()) + rva - s.get_virtual_address(); + + throw pe_exception("RVA not found inside section", pe_exception::rva_not_exists); +} + +//Returns section TOTAL RAW/VIRTUAL data length from RVA inside section +uint32_t pe_base::section_data_length_from_rva(uint32_t rva, section_data_type datatype, bool include_headers) const +{ + //if RVA is inside of headers and we're searching them too... + if(include_headers && rva < full_headers_data_.length()) + return static_cast<unsigned long>(full_headers_data_.length()); + + const section& s = section_from_rva(rva); + return static_cast<unsigned long>(datatype == section_data_raw ? s.get_raw_data().length() /* instead of SizeOfRawData */ : s.get_aligned_virtual_size(get_section_alignment())); +} + +//Returns section TOTAL RAW/VIRTUAL data length from VA inside section for PE32 +uint32_t pe_base::section_data_length_from_va(uint32_t va, section_data_type datatype, bool include_headers) const +{ + return section_data_length_from_rva(va_to_rva(va), datatype, include_headers); +} + +//Returns section TOTAL RAW/VIRTUAL data length from VA inside section for PE32/PE64 +uint32_t pe_base::section_data_length_from_va(uint64_t va, section_data_type datatype, bool include_headers) const +{ + return section_data_length_from_rva(va_to_rva(va), datatype, include_headers); +} + +//Returns section remaining RAW/VIRTUAL data length from RVA "rva_inside" to the end of section containing RVA "rva" +uint32_t pe_base::section_data_length_from_rva(uint32_t rva, uint32_t rva_inside, section_data_type datatype, bool include_headers) const +{ + //if RVAs are inside of headers and we're searching them too... + if(include_headers && rva < full_headers_data_.length() && rva_inside < full_headers_data_.length()) + return static_cast<unsigned long>(full_headers_data_.length() - rva_inside); + + const section& s = section_from_rva(rva); + if(rva_inside < s.get_virtual_address()) + throw pe_exception("RVA not found inside section", pe_exception::rva_not_exists); + + //Calculate remaining length of section data from "rva" address + long length = static_cast<long>(datatype == section_data_raw ? s.get_raw_data().length() /* instead of SizeOfRawData */ : s.get_aligned_virtual_size(get_section_alignment())) + + s.get_virtual_address() - rva_inside; + + if(length < 0) + return 0; + + return static_cast<unsigned long>(length); +} + +//Returns section remaining RAW/VIRTUAL data length from VA "va_inside" to the end of section containing VA "va" for PE32 +uint32_t pe_base::section_data_length_from_va(uint32_t va, uint32_t va_inside, section_data_type datatype, bool include_headers) const +{ + return section_data_length_from_rva(va_to_rva(va), va_to_rva(va_inside), datatype, include_headers); +} + +//Returns section remaining RAW/VIRTUAL data length from VA "va_inside" to the end of section containing VA "va" for PE32/PE64 +uint32_t pe_base::section_data_length_from_va(uint64_t va, uint64_t va_inside, section_data_type datatype, bool include_headers) const +{ + return section_data_length_from_rva(va_to_rva(va), va_to_rva(va_inside), datatype, include_headers); +} + +//Returns section remaining RAW/VIRTUAL data length from RVA to the end of section "s" (checks bounds) +uint32_t pe_base::section_data_length_from_rva(const section& s, uint32_t rva_inside, section_data_type datatype) const +{ + //Check rva_inside + if(rva_inside >= s.get_virtual_address() && rva_inside < s.get_virtual_address() + s.get_aligned_virtual_size(get_section_alignment())) + { + //Calculate remaining length of section data from "rva" address + int32_t length = static_cast<int32_t>(datatype == section_data_raw ? s.get_raw_data().length() /* instead of SizeOfRawData */ : s.get_aligned_virtual_size(get_section_alignment())) + + s.get_virtual_address() - rva_inside; + + if(length < 0) + return 0; + + return static_cast<uint32_t>(length); + } + + throw pe_exception("RVA not found inside section", pe_exception::rva_not_exists); +} + +//Returns section remaining RAW/VIRTUAL data length from VA to the end of section "s" for PE32 (checks bounds) +uint32_t pe_base::section_data_length_from_va(const section& s, uint32_t va_inside, section_data_type datatype) const +{ + return section_data_length_from_rva(s, va_to_rva(va_inside), datatype); +} + +//Returns section remaining RAW/VIRTUAL data length from VA to the end of section "s" for PE32/PE64 (checks bounds) +uint32_t pe_base::section_data_length_from_va(const section& s, uint64_t va_inside, section_data_type datatype) const +{ + return section_data_length_from_rva(s, va_to_rva(va_inside), datatype); +} + +//Returns corresponding section data pointer from RVA inside section +char* pe_base::section_data_from_rva(uint32_t rva, bool include_headers) +{ + //if RVA is inside of headers and we're searching them too... + if(include_headers && rva < full_headers_data_.length()) + return &full_headers_data_[rva]; + + section& s = section_from_rva(rva); + + if(s.get_raw_data().empty()) + throw pe_exception("Section raw data is empty and cannot be changed", pe_exception::section_is_empty); + + return &s.get_raw_data()[rva - s.get_virtual_address()]; +} + +//Returns corresponding section data pointer from RVA inside section +const char* pe_base::section_data_from_rva(uint32_t rva, section_data_type datatype, bool include_headers) const +{ + //if RVA is inside of headers and we're searching them too... + if(include_headers && rva < full_headers_data_.length()) + return &full_headers_data_[rva]; + + const section& s = section_from_rva(rva); + return (datatype == section_data_raw ? s.get_raw_data().data() : s.get_virtual_data(get_section_alignment()).c_str()) + rva - s.get_virtual_address(); +} + +//Reads DOS headers from istream +void pe_base::read_dos_header(std::istream& file, image_dos_header& header) +{ + //Check istream flags + if(file.bad() || file.eof()) + throw pe_exception("PE file stream is bad or closed.", pe_exception::bad_pe_file); + + //Read DOS header and check istream + file.read(reinterpret_cast<char*>(&header), sizeof(image_dos_header)); + if(file.bad() || file.eof()) + throw pe_exception("Unable to read IMAGE_DOS_HEADER", pe_exception::bad_dos_header); + + //Check DOS header magic + if(header.e_magic != 0x5a4d) //"MZ" + throw pe_exception("IMAGE_DOS_HEADER signature is incorrect", pe_exception::bad_dos_header); +} + +//Reads DOS headers from istream +void pe_base::read_dos_header(std::istream& file) +{ + read_dos_header(file, dos_header_); +} + +//Reads PE image from istream +void pe_base::read_pe(std::istream& file, bool read_debug_raw_data) +{ + //Get istream size + std::streamoff filesize = pe_utils::get_file_size(file); + + //Check if PE header is DWORD-aligned + if((dos_header_.e_lfanew % sizeof(uint32_t)) != 0) + throw pe_exception("PE header is not DWORD-aligned", pe_exception::bad_dos_header); + + //Seek to NT headers + file.seekg(dos_header_.e_lfanew); + if(file.bad() || file.fail()) + throw pe_exception("Cannot reach IMAGE_NT_HEADERS", pe_exception::image_nt_headers_not_found); + + //Read NT headers + file.read(get_nt_headers_ptr(), get_sizeof_nt_header() - sizeof(image_data_directory) * image_numberof_directory_entries); + if(file.bad() || file.eof()) + throw pe_exception("Error reading IMAGE_NT_HEADERS", pe_exception::error_reading_image_nt_headers); + + //Check PE signature + if(get_pe_signature() != 0x4550) //"PE" + throw pe_exception("Incorrect PE signature", pe_exception::pe_signature_incorrect); + + //Check number of directories + if(get_number_of_rvas_and_sizes() > image_numberof_directory_entries) + set_number_of_rvas_and_sizes(image_numberof_directory_entries); + + if(get_number_of_rvas_and_sizes() > 0) + { + //Read data directory headers, if any + file.read(get_nt_headers_ptr() + (get_sizeof_nt_header() - sizeof(image_data_directory) * image_numberof_directory_entries), sizeof(image_data_directory) * get_number_of_rvas_and_sizes()); + if(file.bad() || file.eof()) + throw pe_exception("Error reading DATA_DIRECTORY headers", pe_exception::error_reading_data_directories); + } + + //Check section number + //Images with zero section number accepted + if(get_number_of_sections() > maximum_number_of_sections) + throw pe_exception("Incorrect number of sections", pe_exception::section_number_incorrect); + + //Check PE magic + if(get_magic() != get_needed_magic()) + throw pe_exception("Incorrect PE signature", pe_exception::pe_signature_incorrect); + + //Check section alignment + if(!pe_utils::is_power_of_2(get_section_alignment())) + throw pe_exception("Incorrect section alignment", pe_exception::incorrect_section_alignment); + + //Check file alignment + if(!pe_utils::is_power_of_2(get_file_alignment())) + throw pe_exception("Incorrect file alignment", pe_exception::incorrect_file_alignment); + + if(get_file_alignment() != get_section_alignment() && (get_file_alignment() < minimum_file_alignment || get_file_alignment() > get_section_alignment())) + throw pe_exception("Incorrect file alignment", pe_exception::incorrect_file_alignment); + + //Check size of image + if(pe_utils::align_up(get_size_of_image(), get_section_alignment()) == 0) + throw pe_exception("Incorrect size of image", pe_exception::incorrect_size_of_image); + + //Read rich data overlay / DOS stub (if any) + if(static_cast<uint32_t>(dos_header_.e_lfanew) > sizeof(image_dos_header)) + { + rich_overlay_.resize(dos_header_.e_lfanew - sizeof(image_dos_header)); + file.seekg(sizeof(image_dos_header)); + file.read(&rich_overlay_[0], dos_header_.e_lfanew - sizeof(image_dos_header)); + if(file.bad() || file.eof()) + throw pe_exception("Error reading 'Rich' & 'DOS stub' overlay", pe_exception::error_reading_overlay); + } + + //Calculate first section raw position + //Sum is safe here + uint32_t first_section = dos_header_.e_lfanew + get_size_of_optional_header() + sizeof(image_file_header) + sizeof(uint32_t) /* Signature */; + + if(get_number_of_sections() > 0) + { + //Go to first section + file.seekg(first_section); + if(file.bad() || file.fail()) + throw pe_exception("Cannot reach section headers", pe_exception::image_section_headers_not_found); + } + + uint32_t last_raw_size = 0; + + //Read all sections + for(int i = 0; i < get_number_of_sections(); i++) + { + section s; + //Read section header + file.read(reinterpret_cast<char*>(&s.get_raw_header()), sizeof(image_section_header)); + if(file.bad() || file.eof()) + throw pe_exception("Error reading section header", pe_exception::error_reading_section_header); + + //Save next section header position + std::streamoff next_sect = file.tellg(); + + //Check section virtual and raw sizes + if(!s.get_size_of_raw_data() && !s.get_virtual_size()) + throw pe_exception("Virtual and Physical sizes of section can't be 0 at the same time", pe_exception::zero_section_sizes); + + //Check for adequate values of section fields + if(!pe_utils::is_sum_safe(s.get_virtual_address(), s.get_virtual_size()) || s.get_virtual_size() > pe_utils::two_gb + || !pe_utils::is_sum_safe(s.get_pointer_to_raw_data(), s.get_size_of_raw_data()) || s.get_size_of_raw_data() > pe_utils::two_gb) + throw pe_exception("Incorrect section address or size", pe_exception::section_incorrect_addr_or_size); + + if(s.get_size_of_raw_data() != 0) + { + //If section has raw data + + //If section raw data size is greater than virtual, fix it + last_raw_size = s.get_size_of_raw_data(); + if(pe_utils::align_up(s.get_size_of_raw_data(), get_file_alignment()) > pe_utils::align_up(s.get_virtual_size(), get_section_alignment())) + s.set_size_of_raw_data(s.get_virtual_size()); + + //Check virtual and raw section sizes and addresses + if(s.get_virtual_address() + pe_utils::align_up(s.get_virtual_size(), get_section_alignment()) > pe_utils::align_up(get_size_of_image(), get_section_alignment()) + || + pe_utils::align_down(s.get_pointer_to_raw_data(), get_file_alignment()) + s.get_size_of_raw_data() > static_cast<uint32_t>(filesize)) + throw pe_exception("Incorrect section address or size", pe_exception::section_incorrect_addr_or_size); + + //Seek to section raw data + file.seekg(pe_utils::align_down(s.get_pointer_to_raw_data(), get_file_alignment())); + if(file.bad() || file.fail()) + throw pe_exception("Cannot reach section data", pe_exception::image_section_data_not_found); + + //Read section raw data + s.get_raw_data().resize(s.get_size_of_raw_data()); + file.read(&s.get_raw_data()[0], s.get_size_of_raw_data()); + if(file.bad() || file.fail()) + throw pe_exception("Error reading section data", pe_exception::image_section_data_not_found); + } + + //Check virtual address and size of section + if(s.get_virtual_address() + s.get_aligned_virtual_size(get_section_alignment()) > pe_utils::align_up(get_size_of_image(), get_section_alignment())) + throw pe_exception("Incorrect section address or size", pe_exception::section_incorrect_addr_or_size); + + //Save section + sections_.push_back(s); + + //Seek to the next section header + file.seekg(next_sect); + } + + //Check size of headers: SizeOfHeaders can't be larger than first section VA + if(!sections_.empty() && get_size_of_headers() > sections_.front().get_virtual_address()) + throw pe_exception("Incorrect size of headers", pe_exception::incorrect_size_of_headers); + + //If image has more than two sections + if(sections_.size() >= 2) + { + //Check sections virtual sizes + for(section_list::const_iterator i = sections_.begin() + 1; i != sections_.end(); ++i) + { + if((*i).get_virtual_address() != (*(i - 1)).get_virtual_address() + (*(i - 1)).get_aligned_virtual_size(get_section_alignment())) + throw pe_exception("Section table is incorrect", pe_exception::image_section_table_incorrect); + } + } + + //Check if image has overlay in the end of file + has_overlay_ = !sections_.empty() && filesize > static_cast<std::streamoff>(sections_.back().get_pointer_to_raw_data() + last_raw_size); + + { + //Additionally, read data from the beginning of istream to size of headers + file.seekg(0); + uint32_t size_of_headers = std::min<uint32_t>(get_size_of_headers(), static_cast<uint32_t>(filesize)); + + if(!sections_.empty()) + { + for(section_list::const_iterator i = sections_.begin(); i != sections_.end(); ++i) + { + if(!(*i).empty()) + { + size_of_headers = std::min<uint32_t>(get_size_of_headers(), (*i).get_pointer_to_raw_data()); + break; + } + } + } + + full_headers_data_.resize(size_of_headers); + file.read(&full_headers_data_[0], size_of_headers); + if(file.bad() || file.eof()) + throw pe_exception("Error reading file", pe_exception::error_reading_file); + } + + //Moreover, if there's debug directory, read its raw data for some debug info types + while(read_debug_raw_data && has_debug()) + { + try + { + //Check the length in bytes of the section containing debug directory + if(section_data_length_from_rva(get_directory_rva(image_directory_entry_debug), get_directory_rva(image_directory_entry_debug), section_data_virtual, true) < sizeof(image_debug_directory)) + break; + + unsigned long current_pos = get_directory_rva(image_directory_entry_debug); + + //First IMAGE_DEBUG_DIRECTORY table + image_debug_directory directory = section_data_from_rva<image_debug_directory>(current_pos, section_data_virtual, true); + + //Iterate over all IMAGE_DEBUG_DIRECTORY directories + while(directory.PointerToRawData + && current_pos < get_directory_rva(image_directory_entry_debug) + get_directory_size(image_directory_entry_debug)) + { + //If we have something to read + if((directory.Type == image_debug_type_codeview + || directory.Type == image_debug_type_misc + || directory.Type == image_debug_type_coff) + && directory.SizeOfData) + { + std::string data; + data.resize(directory.SizeOfData); + file.seekg(directory.PointerToRawData); + file.read(&data[0], directory.SizeOfData); + if(file.bad() || file.eof()) + throw pe_exception("Error reading file", pe_exception::error_reading_file); + + debug_data_.insert(std::make_pair(directory.PointerToRawData, data)); + } + + //Go to next debug entry + current_pos += sizeof(image_debug_directory); + directory = section_data_from_rva<image_debug_directory>(current_pos, section_data_virtual, true); + } + + break; + } + catch(const pe_exception&) + { + //Don't throw any exception here, if debug info is corrupted or incorrect + break; + } + catch(const std::bad_alloc&) + { + //Don't throw any exception here, if debug info is corrupted or incorrect + break; + } + } +} + +//Returns PE type of this image +pe_type pe_base::get_pe_type() const +{ + return props_->get_pe_type(); +} + +//Returns PE type (PE or PE+) from pe_type enumeration (minimal correctness checks) +pe_type pe_base::get_pe_type(std::istream& file) +{ + //Save state of the istream + std::ios_base::iostate state = file.exceptions(); + std::streamoff old_offset = file.tellg(); + image_nt_headers32 nt_headers; + image_dos_header header; + + try + { + //Read dos header + file.exceptions(std::ios::goodbit); + read_dos_header(file, header); + + //Seek to the NT headers start + file.seekg(header.e_lfanew); + if(file.bad() || file.fail()) + throw pe_exception("Cannot reach IMAGE_NT_HEADERS", pe_exception::image_nt_headers_not_found); + + //Read NT headers (we're using 32-bit version, because there's no significant differencies between 32 and 64 bit version structures) + file.read(reinterpret_cast<char*>(&nt_headers), sizeof(image_nt_headers32) - sizeof(image_data_directory) * image_numberof_directory_entries); + if(file.bad() || file.eof()) + throw pe_exception("Error reading IMAGE_NT_HEADERS", pe_exception::error_reading_image_nt_headers); + + //Check NT headers signature + if(nt_headers.Signature != 0x4550) //"PE" + throw pe_exception("Incorrect PE signature", pe_exception::pe_signature_incorrect); + + //Check NT headers magic + if(nt_headers.OptionalHeader.Magic != image_nt_optional_hdr32_magic && nt_headers.OptionalHeader.Magic != image_nt_optional_hdr64_magic) + throw pe_exception("Incorrect PE signature", pe_exception::pe_signature_incorrect); + } + catch(const std::exception&) + { + //If something went wrong, restore istream state + file.exceptions(state); + file.seekg(old_offset); + file.clear(); + //Retrhow exception + throw; + } + + //Restore stream state + file.exceptions(state); + file.seekg(old_offset); + file.clear(); + + //Determine PE type and return it + return nt_headers.OptionalHeader.Magic == image_nt_optional_hdr64_magic ? pe_type_64 : pe_type_32; +} + +//Returns true if image has overlay data at the end of file +bool pe_base::has_overlay() const +{ + return has_overlay_; +} + +//Clears PE characteristics flag +void pe_base::clear_characteristics_flags(uint16_t flags) +{ + set_characteristics(get_characteristics() & ~flags); +} + +//Sets PE characteristics flag +void pe_base::set_characteristics_flags(uint16_t flags) +{ + set_characteristics(get_characteristics() | flags); +} + +//Returns true if PE characteristics flag set +bool pe_base::check_characteristics_flag(uint16_t flag) const +{ + return (get_characteristics() & flag) ? true : false; +} + +//Returns subsystem value +uint16_t pe_base::get_subsystem() const +{ + return props_->get_subsystem(); +} + +//Sets subsystem value +void pe_base::set_subsystem(uint16_t subsystem) +{ + props_->set_subsystem(subsystem); +} + +//Returns true if image has console subsystem +bool pe_base::is_console() const +{ + return get_subsystem() == image_subsystem_windows_cui; +} + +//Returns true if image has Windows GUI subsystem +bool pe_base::is_gui() const +{ + return get_subsystem() == image_subsystem_windows_gui; +} + +//Sets required operation system version +void pe_base::set_os_version(uint16_t major, uint16_t minor) +{ + props_->set_os_version(major, minor); +} + +//Returns required operation system version (minor word) +uint16_t pe_base::get_minor_os_version() const +{ + return props_->get_minor_os_version(); +} + +//Returns required operation system version (major word) +uint16_t pe_base::get_major_os_version() const +{ + return props_->get_major_os_version(); +} + +//Sets required subsystem version +void pe_base::set_subsystem_version(uint16_t major, uint16_t minor) +{ + props_->set_subsystem_version(major, minor); +} + +//Returns required subsystem version (minor word) +uint16_t pe_base::get_minor_subsystem_version() const +{ + return props_->get_minor_subsystem_version(); +} + +//Returns required subsystem version (major word) +uint16_t pe_base::get_major_subsystem_version() const +{ + return props_->get_major_subsystem_version(); +} + +//Returns corresponding section data pointer from VA inside section "s" for PE32 (checks bounds) +char* pe_base::section_data_from_va(section& s, uint32_t va) //Always returns raw data +{ + return section_data_from_rva(s, va_to_rva(va)); +} + +//Returns corresponding section data pointer from VA inside section "s" for PE32 (checks bounds) +const char* pe_base::section_data_from_va(const section& s, uint32_t va, section_data_type datatype) const +{ + return section_data_from_rva(s, va_to_rva(va), datatype); +} + +//Returns corresponding section data pointer from VA inside section for PE32 +char* pe_base::section_data_from_va(uint32_t va, bool include_headers) //Always returns raw data +{ + return section_data_from_rva(va_to_rva(va), include_headers); +} + +//Returns corresponding section data pointer from VA inside section for PE32 +const char* pe_base::section_data_from_va(uint32_t va, section_data_type datatype, bool include_headers) const +{ + return section_data_from_rva(va_to_rva(va), datatype, include_headers); +} + +//Returns corresponding section data pointer from VA inside section "s" for PE32/PE64 (checks bounds) +char* pe_base::section_data_from_va(section& s, uint64_t va) //Always returns raw data +{ + return section_data_from_rva(s, va_to_rva(va)); +} + +//Returns corresponding section data pointer from VA inside section "s" for PE32/PE64 (checks bounds) +const char* pe_base::section_data_from_va(const section& s, uint64_t va, section_data_type datatype) const +{ + return section_data_from_rva(s, va_to_rva(va), datatype); +} + +//Returns corresponding section data pointer from VA inside section for PE32/PE64 +char* pe_base::section_data_from_va(uint64_t va, bool include_headers) //Always returns raw data +{ + return section_data_from_rva(va_to_rva(va), include_headers); +} + +//Returns corresponding section data pointer from VA inside section for PE32/PE64 +const char* pe_base::section_data_from_va(uint64_t va, section_data_type datatype, bool include_headers) const +{ + return section_data_from_rva(va_to_rva(va), datatype, include_headers); +} + +//Returns section from VA inside it for PE32 +section& pe_base::section_from_va(uint32_t va) +{ + return section_from_rva(va_to_rva(va)); +} + +//Returns section from VA inside it for PE32/PE64 +section& pe_base::section_from_va(uint64_t va) +{ + return section_from_rva(va_to_rva(va)); +} + +//Returns section from RVA inside it for PE32 +const section& pe_base::section_from_va(uint32_t va) const +{ + return section_from_rva(va_to_rva(va)); +} + +//Returns section from RVA inside it for PE32/PE64 +const section& pe_base::section_from_va(uint64_t va) const +{ + return section_from_rva(va_to_rva(va)); +} + +uint32_t pe_base::va_to_rva(uint32_t va, bool bound_check) const +{ + return props_->va_to_rva(va, bound_check); +} + +uint32_t pe_base::va_to_rva(uint64_t va, bool bound_check) const +{ + return props_->va_to_rva(va, bound_check); +} + +uint32_t pe_base::rva_to_va_32(uint32_t rva) const +{ + return props_->rva_to_va_32(rva); +} + +uint64_t pe_base::rva_to_va_64(uint32_t rva) const +{ + return props_->rva_to_va_64(rva); +} + +//Relative Virtual Address (RVA) to Virtual Address (VA) convertion for PE32 +void pe_base::rva_to_va(uint32_t rva, uint32_t& va) const +{ + va = rva_to_va_32(rva); +} + +//Relative Virtual Address (RVA) to Virtual Address (VA) convertions for PE32/PE64 +void pe_base::rva_to_va(uint32_t rva, uint64_t& va) const +{ + va = rva_to_va_64(rva); +} + +//Returns section from file offset (4gb max) +section& pe_base::section_from_file_offset(uint32_t offset) +{ + return *file_offset_to_section(offset); +} + +//Returns section from file offset (4gb max) +const section& pe_base::section_from_file_offset(uint32_t offset) const +{ + return *file_offset_to_section(offset); +} + +//Returns section and offset (raw data only) from its start from RVA +const std::pair<uint32_t, const section*> pe_base::section_and_offset_from_rva(uint32_t rva) const +{ + const section& s = section_from_rva(rva); + return std::make_pair(rva - s.get_virtual_address(), &s); +} + +//Returns DLL Characteristics +uint16_t pe_base::get_dll_characteristics() const +{ + return props_->get_dll_characteristics(); +} + +//Sets DLL Characteristics +void pe_base::set_dll_characteristics(uint16_t characteristics) +{ + props_->set_dll_characteristics(characteristics); +} + +//Returns size of headers +uint32_t pe_base::get_size_of_headers() const +{ + return props_->get_size_of_headers(); +} + +//Returns size of optional header +uint16_t pe_base::get_size_of_optional_header() const +{ + return props_->get_size_of_optional_header(); +} + +//Returns PE signature +uint32_t pe_base::get_pe_signature() const +{ + return props_->get_pe_signature(); +} + +//Returns magic value +uint32_t pe_base::get_magic() const +{ + return props_->get_magic(); +} + +//Returns image base for PE32 +void pe_base::get_image_base(uint32_t& base) const +{ + base = get_image_base_32(); +} + +//Returns image base for PE32 and PE64 respectively +uint32_t pe_base::get_image_base_32() const +{ + return props_->get_image_base_32(); +} + +//Sets image base for PE32 and PE64 respectively +uint64_t pe_base::get_image_base_64() const +{ + return props_->get_image_base_64(); +} + +//RVA to RAW file offset convertion (4gb max) +uint32_t pe_base::rva_to_file_offset(uint32_t rva) const +{ + //Maybe, RVA is inside PE headers + if(rva < get_size_of_headers()) + return rva; + + const section& s = section_from_rva(rva); + return s.get_pointer_to_raw_data() + rva - s.get_virtual_address(); +} + +//RAW file offset to RVA convertion (4gb max) +uint32_t pe_base::file_offset_to_rva(uint32_t offset) const +{ + //Maybe, offset is inside PE headers + if(offset < get_size_of_headers()) + return offset; + + const section_list::const_iterator it = file_offset_to_section(offset); + return offset - (*it).get_pointer_to_raw_data() + (*it).get_virtual_address(); +} + +//RAW file offset to section convertion helper (4gb max) +section_list::const_iterator pe_base::file_offset_to_section(uint32_t offset) const +{ + section_list::const_iterator it = std::find_if(sections_.begin(), sections_.end(), section_by_raw_offset(offset)); + if(it == sections_.end()) + throw pe_exception("No section found by presented file offset", pe_exception::no_section_found); + + return it; +} + +//RAW file offset to section convertion helper (4gb max) +section_list::iterator pe_base::file_offset_to_section(uint32_t offset) +{ + section_list::iterator it = std::find_if(sections_.begin(), sections_.end(), section_by_raw_offset(offset)); + if(it == sections_.end()) + throw pe_exception("No section found by presented file offset", pe_exception::no_section_found); + + return it; +} + +//RVA from section raw data offset +uint32_t pe_base::rva_from_section_offset(const section& s, uint32_t raw_offset_from_section_start) +{ + return s.get_virtual_address() + raw_offset_from_section_start; +} + +//Returns image base for PE32/PE64 +void pe_base::get_image_base(uint64_t& base) const +{ + base = get_image_base_64(); +} + +//Sets new image base +void pe_base::set_image_base(uint32_t base) +{ + props_->set_image_base(base); +} + +void pe_base::set_image_base_64(uint64_t base) +{ + props_->set_image_base_64(base); +} + +//Sets heap size commit for PE32 and PE64 respectively +void pe_base::set_heap_size_commit(uint32_t size) +{ + props_->set_heap_size_commit(size); +} + +void pe_base::set_heap_size_commit(uint64_t size) +{ + props_->set_heap_size_commit(size); +} + +//Sets heap size reserve for PE32 and PE64 respectively +void pe_base::set_heap_size_reserve(uint32_t size) +{ + props_->set_heap_size_reserve(size); +} + +void pe_base::set_heap_size_reserve(uint64_t size) +{ + props_->set_heap_size_reserve(size); +} + +//Sets stack size commit for PE32 and PE64 respectively +void pe_base::set_stack_size_commit(uint32_t size) +{ + props_->set_stack_size_commit(size); +} + +void pe_base::set_stack_size_commit(uint64_t size) +{ + props_->set_stack_size_commit(size); +} + +//Sets stack size reserve for PE32 and PE64 respectively +void pe_base::set_stack_size_reserve(uint32_t size) +{ + props_->set_stack_size_reserve(size); +} + +void pe_base::set_stack_size_reserve(uint64_t size) +{ + props_->set_stack_size_reserve(size); +} + +//Returns heap size commit for PE32 and PE64 respectively +uint32_t pe_base::get_heap_size_commit_32() const +{ + return props_->get_heap_size_commit_32(); +} + +uint64_t pe_base::get_heap_size_commit_64() const +{ + return props_->get_heap_size_commit_64(); +} + +//Returns heap size reserve for PE32 and PE64 respectively +uint32_t pe_base::get_heap_size_reserve_32() const +{ + return props_->get_heap_size_reserve_32(); +} + +uint64_t pe_base::get_heap_size_reserve_64() const +{ + return props_->get_heap_size_reserve_64(); +} + +//Returns stack size commit for PE32 and PE64 respectively +uint32_t pe_base::get_stack_size_commit_32() const +{ + return props_->get_stack_size_commit_32(); +} + +uint64_t pe_base::get_stack_size_commit_64() const +{ + return props_->get_stack_size_commit_64(); +} + +//Returns stack size reserve for PE32 and PE64 respectively +uint32_t pe_base::get_stack_size_reserve_32() const +{ + return props_->get_stack_size_reserve_32(); +} + +uint64_t pe_base::get_stack_size_reserve_64() const +{ + return props_->get_stack_size_reserve_64(); +} + +//Returns heap size commit for PE32 +void pe_base::get_heap_size_commit(uint32_t& size) const +{ + size = get_heap_size_commit_32(); +} + +//Returns heap size commit for PE32/PE64 +void pe_base::get_heap_size_commit(uint64_t& size) const +{ + size = get_heap_size_commit_64(); +} + +//Returns heap size reserve for PE32 +void pe_base::get_heap_size_reserve(uint32_t& size) const +{ + size = get_heap_size_reserve_32(); +} + +//Returns heap size reserve for PE32/PE64 +void pe_base::get_heap_size_reserve(uint64_t& size) const +{ + size = get_heap_size_reserve_64(); +} + +//Returns stack size commit for PE32 +void pe_base::get_stack_size_commit(uint32_t& size) const +{ + size = get_stack_size_commit_32(); +} + +//Returns stack size commit for PE32/PE64 +void pe_base::get_stack_size_commit(uint64_t& size) const +{ + size = get_stack_size_commit_64(); +} + +//Returns stack size reserve for PE32 +void pe_base::get_stack_size_reserve(uint32_t& size) const +{ + size = get_stack_size_reserve_32(); +} + +//Returns stack size reserve for PE32/PE64 +void pe_base::get_stack_size_reserve(uint64_t& size) const +{ + size = get_stack_size_reserve_64(); +} + +//Realigns file (changes file alignment) +void pe_base::realign_file(uint32_t new_file_alignment) +{ + //Checks alignment for correctness + set_file_alignment(new_file_alignment); + realign_all_sections(); +} + +//Helper function to recalculate RAW and virtual section sizes and strip it, if necessary +void pe_base::recalculate_section_sizes(section& s, bool auto_strip) +{ + prepare_section(s); //Recalculate section raw addresses + + //Strip RAW size of section, if it is the last one + //For all others it must be file-aligned and calculated by prepare_section() call + if(auto_strip && !(sections_.empty() || &s == &*(sections_.end() - 1))) + { + //Strip ending raw data nullbytes to optimize size + std::string& raw_data = s.get_raw_data(); + if(!raw_data.empty()) + { + std::string::size_type i = raw_data.length(); + for(; i != 1; --i) + { + if(raw_data[i - 1] != 0) + break; + } + + raw_data.resize(i); + } + + s.set_size_of_raw_data(static_cast<uint32_t>(raw_data.length())); + } + + //Can occur only for last section + if(pe_utils::align_up(s.get_virtual_size(), get_section_alignment()) < pe_utils::align_up(s.get_size_of_raw_data(), get_file_alignment())) + set_section_virtual_size(s, pe_utils::align_up(s.get_size_of_raw_data(), get_section_alignment())); //Recalculate section virtual size +} + +//Returns data from the beginning of image +//Size = SizeOfHeaders +const std::string& pe_base::get_full_headers_data() const +{ + return full_headers_data_; +} + +const pe_base::debug_data_list& pe_base::get_raw_debug_data_list() const +{ + return debug_data_; +} + +//Sets number of sections +void pe_base::set_number_of_sections(uint16_t number) +{ + props_->set_number_of_sections(number); +} + +//Sets size of image +void pe_base::set_size_of_image(uint32_t size) +{ + props_->set_size_of_image(size); +} + +//Sets size of headers +void pe_base::set_size_of_headers(uint32_t size) +{ + props_->set_size_of_headers(size); +} + +//Sets size of optional headers +void pe_base::set_size_of_optional_header(uint16_t size) +{ + props_->set_size_of_optional_header(size); +} + +//Returns nt headers data pointer +char* pe_base::get_nt_headers_ptr() +{ + return props_->get_nt_headers_ptr(); +} + +//Returns nt headers data pointer +const char* pe_base::get_nt_headers_ptr() const +{ + return props_->get_nt_headers_ptr(); +} + +//Returns sizeof() nt headers +uint32_t pe_base::get_sizeof_nt_header() const +{ + return props_->get_sizeof_nt_header(); +} + +//Returns sizeof() optional headers +uint32_t pe_base::get_sizeof_opt_headers() const +{ + return props_->get_sizeof_opt_headers(); +} + +//Sets file alignment (no checks) +void pe_base::set_file_alignment_unchecked(uint32_t alignment) +{ + props_->set_file_alignment_unchecked(alignment); +} + +//Sets base of code +void pe_base::set_base_of_code(uint32_t base) +{ + props_->set_base_of_code(base); +} + +//Returns base of code +uint32_t pe_base::get_base_of_code() const +{ + return props_->get_base_of_code(); +} + +//Returns needed magic of image +uint32_t pe_base::get_needed_magic() const +{ + return props_->get_needed_magic(); +} +} diff --git a/tools/pe_bliss/pe_base.h b/tools/pe_bliss/pe_base.h new file mode 100644 index 0000000000..b5416cf1e2 --- /dev/null +++ b/tools/pe_bliss/pe_base.h @@ -0,0 +1,544 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <string> +#include <vector> +#include <istream> +#include <ostream> +#include <map> +#include "pe_exception.h" +#include "pe_structures.h" +#include "utils.h" +#include "pe_section.h" +#include "pe_properties.h" + +//Please don't remove this information from header +//PEBliss 1.0.0 +//(c) DX 2011 - 2012, http://kaimi.ru +//Free to use for commertial and non-commertial purposes, modification and distribution + +// == more important == +//TODO: compact import rebuilder +//TODO: remove sections in the middle +//== less important == +//TODO: relocations that take more than one element (seems to be not possible in Windows PE, but anyway) +//TODO: delay import directory +//TODO: write message tables +//TODO: write string tables +//TODO: read security information +//TODO: read full .NET information + +namespace pe_bliss +{ +//Portable executable class +class pe_base +{ +public: //CONSTRUCTORS + //Constructor from stream + pe_base(std::istream& file, const pe_properties& props, bool read_debug_raw_data = true); + + //Constructor of empty PE-file + explicit pe_base(const pe_properties& props, uint32_t section_alignment = 0x1000, bool dll = false, uint16_t subsystem = pe_win::image_subsystem_windows_gui); + + pe_base(const pe_base& pe); + pe_base& operator=(const pe_base& pe); + +public: + ~pe_base(); + +public: //STUB + //Strips stub MSVS overlay, if any + void strip_stub_overlay(); + //Fills stub MSVS overlay with specified byte + void fill_stub_overlay(char c); + //Sets stub MSVS overlay + void set_stub_overlay(const std::string& data); + //Returns stub overlay contents + const std::string& get_stub_overlay() const; + + +public: //DIRECTORIES + //Returns true if directory exists + bool directory_exists(uint32_t id) const; + //Removes directory + void remove_directory(uint32_t id); + + //Returns directory RVA + uint32_t get_directory_rva(uint32_t id) const; + //Returns directory size + uint32_t get_directory_size(uint32_t id) const; + + //Sets directory RVA (just a value of PE header, no moving occurs) + void set_directory_rva(uint32_t id, uint32_t rva); + //Sets directory size (just a value of PE header, no moving occurs) + void set_directory_size(uint32_t id, uint32_t size); + + //Strips only zero DATA_DIRECTORY entries to count = min_count + //Returns resulting number of data directories + //strip_iat_directory - if true, even not empty IAT directory will be stripped + uint32_t strip_data_directories(uint32_t min_count = 1, bool strip_iat_directory = true); + + //Returns true if image has import directory + bool has_imports() const; + //Returns true if image has export directory + bool has_exports() const; + //Returns true if image has resource directory + bool has_resources() const; + //Returns true if image has security directory + bool has_security() const; + //Returns true if image has relocations + bool has_reloc() const; + //Returns true if image has TLS directory + bool has_tls() const; + //Returns true if image has config directory + bool has_config() const; + //Returns true if image has bound import directory + bool has_bound_import() const; + //Returns true if image has delay import directory + bool has_delay_import() const; + //Returns true if image has COM directory + bool is_dotnet() const; + //Returns true if image has exception directory + bool has_exception_directory() const; + //Returns true if image has debug directory + bool has_debug() const; + + //Returns subsystem value + uint16_t get_subsystem() const; + //Sets subsystem value + void set_subsystem(uint16_t subsystem); + //Returns true if image has console subsystem + bool is_console() const; + //Returns true if image has Windows GUI subsystem + bool is_gui() const; + + //Sets required operation system version + void set_os_version(uint16_t major, uint16_t minor); + //Returns required operation system version (minor word) + uint16_t get_minor_os_version() const; + //Returns required operation system version (major word) + uint16_t get_major_os_version() const; + + //Sets required subsystem version + void set_subsystem_version(uint16_t major, uint16_t minor); + //Returns required subsystem version (minor word) + uint16_t get_minor_subsystem_version() const; + //Returns required subsystem version (major word) + uint16_t get_major_subsystem_version() const; + +public: //PE HEADER + //Returns DOS header + const pe_win::image_dos_header& get_dos_header() const; + pe_win::image_dos_header& get_dos_header(); + + //Returns PE header start (e_lfanew) + int32_t get_pe_header_start() const; + + //Returns file alignment + uint32_t get_file_alignment() const; + //Sets file alignment, checking the correctness of its value + void set_file_alignment(uint32_t alignment); + + //Returns size of image + uint32_t get_size_of_image() const; + + //Returns image entry point + uint32_t get_ep() const; + //Sets image entry point (just a value of PE header) + void set_ep(uint32_t new_ep); + + //Returns number of RVA and sizes (number of DATA_DIRECTORY entries) + uint32_t get_number_of_rvas_and_sizes() const; + //Sets number of RVA and sizes (number of DATA_DIRECTORY entries) + void set_number_of_rvas_and_sizes(uint32_t number); + + //Returns PE characteristics + uint16_t get_characteristics() const; + //Sets PE characteristics (a value inside header) + void set_characteristics(uint16_t ch); + //Clears PE characteristics flag + void clear_characteristics_flags(uint16_t flags); + //Sets PE characteristics flag + void set_characteristics_flags(uint16_t flags); + //Returns true if PE characteristics flag set + bool check_characteristics_flag(uint16_t flag) const; + + //Returns DLL Characteristics + uint16_t get_dll_characteristics() const; + //Sets DLL Characteristics + void set_dll_characteristics(uint16_t characteristics); + + //Returns size of headers + uint32_t get_size_of_headers() const; + //Returns size of optional header + uint16_t get_size_of_optional_header() const; + + //Returns PE signature + uint32_t get_pe_signature() const; + + //Returns magic value + uint32_t get_magic() const; + + //Returns image base for PE32 and PE64 respectively + uint32_t get_image_base_32() const; + void get_image_base(uint32_t& base) const; + //Sets image base for PE32 and PE64 respectively + uint64_t get_image_base_64() const; + void get_image_base(uint64_t& base) const; + + //Sets new image base + void set_image_base(uint32_t base); + void set_image_base_64(uint64_t base); + + //Sets heap size commit for PE32 and PE64 respectively + void set_heap_size_commit(uint32_t size); + void set_heap_size_commit(uint64_t size); + //Sets heap size reserve for PE32 and PE64 respectively + void set_heap_size_reserve(uint32_t size); + void set_heap_size_reserve(uint64_t size); + //Sets stack size commit for PE32 and PE64 respectively + void set_stack_size_commit(uint32_t size); + void set_stack_size_commit(uint64_t size); + //Sets stack size reserve for PE32 and PE64 respectively + void set_stack_size_reserve(uint32_t size); + void set_stack_size_reserve(uint64_t size); + + //Returns heap size commit for PE32 and PE64 respectively + uint32_t get_heap_size_commit_32() const; + void get_heap_size_commit(uint32_t& size) const; + uint64_t get_heap_size_commit_64() const; + void get_heap_size_commit(uint64_t& size) const; + //Returns heap size reserve for PE32 and PE64 respectively + uint32_t get_heap_size_reserve_32() const; + void get_heap_size_reserve(uint32_t& size) const; + uint64_t get_heap_size_reserve_64() const; + void get_heap_size_reserve(uint64_t& size) const; + //Returns stack size commit for PE32 and PE64 respectively + uint32_t get_stack_size_commit_32() const; + void get_stack_size_commit(uint32_t& size) const; + uint64_t get_stack_size_commit_64() const; + void get_stack_size_commit(uint64_t& size) const; + //Returns stack size reserve for PE32 and PE64 respectively + uint32_t get_stack_size_reserve_32() const; + void get_stack_size_reserve(uint32_t& size) const; + uint64_t get_stack_size_reserve_64() const; + void get_stack_size_reserve(uint64_t& size) const; + + //Updates virtual size of image corresponding to section virtual sizes + void update_image_size(); + + //Returns checksum of PE file from header + uint32_t get_checksum() const; + //Sets checksum of PE file + void set_checksum(uint32_t checksum); + + //Returns timestamp of PE file from header + uint32_t get_time_date_stamp() const; + //Sets timestamp of PE file + void set_time_date_stamp(uint32_t timestamp); + + //Returns Machine field value of PE file from header + uint16_t get_machine() const; + //Sets Machine field value of PE file + void set_machine(uint16_t machine); + + //Returns data from the beginning of image + //Size = SizeOfHeaders + const std::string& get_full_headers_data() const; + + typedef std::multimap<uint32_t, std::string> debug_data_list; + //Returns raw list of debug data + const debug_data_list& get_raw_debug_data_list() const; + + //Reads and checks DOS header + static void read_dos_header(std::istream& file, pe_win::image_dos_header& header); + + //Returns sizeof() nt headers + uint32_t get_sizeof_nt_header() const; + //Returns sizeof() optional headers + uint32_t get_sizeof_opt_headers() const; + //Returns raw nt headers data pointer + const char* get_nt_headers_ptr() const; + + //Sets size of headers (to NT headers) + void set_size_of_headers(uint32_t size); + //Sets size of optional headers (to NT headers) + void set_size_of_optional_header(uint16_t size); + + //Sets base of code + void set_base_of_code(uint32_t base); + //Returns base of code + uint32_t get_base_of_code() const; + +public: //ADDRESS CONVERTIONS + //Virtual Address (VA) to Relative Virtual Address (RVA) convertions + //for PE32 and PE64 respectively + //bound_check checks integer overflow + uint32_t va_to_rva(uint32_t va, bool bound_check = true) const; + uint32_t va_to_rva(uint64_t va, bool bound_check = true) const; + + //Relative Virtual Address (RVA) to Virtual Address (VA) convertions + //for PE32 and PE64 respectively + uint32_t rva_to_va_32(uint32_t rva) const; + void rva_to_va(uint32_t rva, uint32_t& va) const; + uint64_t rva_to_va_64(uint32_t rva) const; + void rva_to_va(uint32_t rva, uint64_t& va) const; + + //RVA to RAW file offset convertion (4gb max) + uint32_t rva_to_file_offset(uint32_t rva) const; + //RAW file offset to RVA convertion (4gb max) + uint32_t file_offset_to_rva(uint32_t offset) const; + + //RVA from section raw data offset + static uint32_t rva_from_section_offset(const section& s, uint32_t raw_offset_from_section_start); + +public: //IMAGE SECTIONS + //Returns number of sections from PE header + uint16_t get_number_of_sections() const; + + //Updates number of sections in PE header + uint16_t update_number_of_sections(); + + //Returns section alignment + uint32_t get_section_alignment() const; + + //Returns section list + section_list& get_image_sections(); + const section_list& get_image_sections() const; + + //Realigns all sections, if you made any changes to sections or alignments + void realign_all_sections(); + //Resligns section with specified index + void realign_section(uint32_t index); + + //Returns section from RVA inside it + section& section_from_rva(uint32_t rva); + const section& section_from_rva(uint32_t rva) const; + //Returns section from directory ID + section& section_from_directory(uint32_t directory_id); + const section& section_from_directory(uint32_t directory_id) const; + //Returns section from VA inside it for PE32 and PE64 respectively + section& section_from_va(uint32_t va); + const section& section_from_va(uint32_t va) const; + section& section_from_va(uint64_t va); + const section& section_from_va(uint64_t va) const; + //Returns section from file offset (4gb max) + section& section_from_file_offset(uint32_t offset); + const section& section_from_file_offset(uint32_t offset) const; + + //Returns section TOTAL RAW/VIRTUAL data length from RVA inside section + //If include_headers = true, data from the beginning of PE file to SizeOfHeaders will be searched, too + uint32_t section_data_length_from_rva(uint32_t rva, section_data_type datatype = section_data_raw, bool include_headers = false) const; + //Returns section TOTAL RAW/VIRTUAL data length from VA inside section for PE32 and PE64 respectively + //If include_headers = true, data from the beginning of PE file to SizeOfHeaders will be searched, too + uint32_t section_data_length_from_va(uint32_t va, section_data_type datatype = section_data_raw, bool include_headers = false) const; + uint32_t section_data_length_from_va(uint64_t va, section_data_type datatype = section_data_raw, bool include_headers = false) const; + + //Returns section remaining RAW/VIRTUAL data length from RVA to the end of section "s" (checks bounds) + uint32_t section_data_length_from_rva(const section& s, uint32_t rva_inside, section_data_type datatype = section_data_raw) const; + //Returns section remaining RAW/VIRTUAL data length from VA to the end of section "s" for PE32 and PE64 respectively (checks bounds) + uint32_t section_data_length_from_va(const section& s, uint64_t va_inside, section_data_type datatype = section_data_raw) const; + uint32_t section_data_length_from_va(const section& s, uint32_t va_inside, section_data_type datatype = section_data_raw) const; + + //Returns section remaining RAW/VIRTUAL data length from RVA "rva_inside" to the end of section containing RVA "rva" + //If include_headers = true, data from the beginning of PE file to SizeOfHeaders will be searched, too + uint32_t section_data_length_from_rva(uint32_t rva, uint32_t rva_inside, section_data_type datatype = section_data_raw, bool include_headers = false) const; + //Returns section remaining RAW/VIRTUAL data length from VA "va_inside" to the end of section containing VA "va" for PE32 and PE64 respectively + //If include_headers = true, data from the beginning of PE file to SizeOfHeaders will be searched, too + uint32_t section_data_length_from_va(uint32_t va, uint32_t va_inside, section_data_type datatype = section_data_raw, bool include_headers = false) const; + uint32_t section_data_length_from_va(uint64_t va, uint64_t va_inside, section_data_type datatype = section_data_raw, bool include_headers = false) const; + + //If include_headers = true, data from the beginning of PE file to SizeOfHeaders will be searched, too + //Returns corresponding section data pointer from RVA inside section + char* section_data_from_rva(uint32_t rva, bool include_headers = false); + const char* section_data_from_rva(uint32_t rva, section_data_type datatype = section_data_raw, bool include_headers = false) const; + //Returns corresponding section data pointer from VA inside section for PE32 and PE64 respectively + char* section_data_from_va(uint32_t va, bool include_headers = false); + const char* section_data_from_va(uint32_t va, section_data_type datatype = section_data_raw, bool include_headers = false) const; + char* section_data_from_va(uint64_t va, bool include_headers = false); + const char* section_data_from_va(uint64_t va, section_data_type datatype = section_data_raw, bool include_headers = false) const; + + //Returns corresponding section data pointer from RVA inside section "s" (checks bounds) + char* section_data_from_rva(section& s, uint32_t rva); + const char* section_data_from_rva(const section& s, uint32_t rva, section_data_type datatype = section_data_raw) const; + //Returns corresponding section data pointer from VA inside section "s" for PE32 and PE64 respectively (checks bounds) + char* section_data_from_va(section& s, uint32_t va); //Always returns raw data + const char* section_data_from_va(const section& s, uint32_t va, section_data_type datatype = section_data_raw) const; + char* section_data_from_va(section& s, uint64_t va); //Always returns raw data + const char* section_data_from_va(const section& s, uint64_t va, section_data_type datatype = section_data_raw) const; + + //Returns corresponding section data pointer from RVA inside section "s" (checks bounds, checks sizes, the most safe function) + template<typename T> + T section_data_from_rva(const section& s, uint32_t rva, section_data_type datatype = section_data_raw) const + { + if(rva >= s.get_virtual_address() && rva < s.get_virtual_address() + s.get_aligned_virtual_size(get_section_alignment()) && pe_utils::is_sum_safe(rva, sizeof(T))) + { + const std::string& data = datatype == section_data_raw ? s.get_raw_data() : s.get_virtual_data(get_section_alignment()); + //Don't check for underflow here, comparsion is unsigned + if(data.size() < rva - s.get_virtual_address() + sizeof(T)) + throw pe_exception("RVA and requested data size does not exist inside section", pe_exception::rva_not_exists); + + return *reinterpret_cast<const T*>(data.data() + rva - s.get_virtual_address()); + } + + throw pe_exception("RVA not found inside section", pe_exception::rva_not_exists); + } + + //Returns corresponding section data pointer from RVA inside section (checks rva, checks sizes, the most safe function) + //If include_headers = true, data from the beginning of PE file to SizeOfHeaders will be searched, too + template<typename T> + T section_data_from_rva(uint32_t rva, section_data_type datatype = section_data_raw, bool include_headers = false) const + { + //if RVA is inside of headers and we're searching them too... + if(include_headers && pe_utils::is_sum_safe(rva, sizeof(T)) && (rva + sizeof(T) < full_headers_data_.length())) + return *reinterpret_cast<const T*>(&full_headers_data_[rva]); + + const section& s = section_from_rva(rva); + const std::string& data = datatype == section_data_raw ? s.get_raw_data() : s.get_virtual_data(get_section_alignment()); + //Don't check for underflow here, comparsion is unsigned + if(data.size() < rva - s.get_virtual_address() + sizeof(T)) + throw pe_exception("RVA and requested data size does not exist inside section", pe_exception::rva_not_exists); + + return *reinterpret_cast<const T*>(data.data() + rva - s.get_virtual_address()); + } + + //Returns corresponding section data pointer from VA inside section "s" (checks bounds, checks sizes, the most safe function) + template<typename T> + T section_data_from_va(const section& s, uint32_t va, section_data_type datatype = section_data_raw) const + { + return section_data_from_rva<T>(s, va_to_rva(va), datatype); + } + + template<typename T> + T section_data_from_va(const section& s, uint64_t va, section_data_type datatype = section_data_raw) const + { + return section_data_from_rva<T>(s, va_to_rva(va), datatype); + } + + //Returns corresponding section data pointer from VA inside section (checks rva, checks sizes, the most safe function) + //If include_headers = true, data from the beginning of PE file to SizeOfHeaders will be searched, too + template<typename T> + T section_data_from_va(uint32_t va, section_data_type datatype = section_data_raw, bool include_headers = false) const + { + return section_data_from_rva<T>(va_to_rva(va), datatype, include_headers); + } + + template<typename T> + T section_data_from_va(uint64_t va, section_data_type datatype = section_data_raw, bool include_headers = false) const + { + return section_data_from_rva<T>(va_to_rva(va), datatype, include_headers); + } + + //Returns section and offset (raw data only) from its start from RVA + const std::pair<uint32_t, const section*> section_and_offset_from_rva(uint32_t rva) const; + + //Sets virtual size of section "s" + //Section must be free (not bound to any image) + //or the last section of this image + //Function calls update_image_size automatically in second case + void set_section_virtual_size(section& s, uint32_t vsize); + + //Represents section expand type for expand_section function + enum section_expand_type + { + expand_section_raw, //Section raw data size will be expanded + expand_section_virtual //Section virtual data size will be expanded + }; + + //Expands section raw or virtual size to hold data from specified RVA with specified size + //Section must be free (not bound to any image) + //or the last section of this image + //Returns true if section was expanded + bool expand_section(section& s, uint32_t needed_rva, uint32_t needed_size, section_expand_type expand); + + //Adds section to image + //Returns last section + section& add_section(section s); + //Prepares section to later add it to image (checks and recalculates virtual and raw section size) + //Section must be prepared by this function before calling add_section + void prepare_section(section& s); + + //Returns true if sectios "s" is already attached to this PE file + bool section_attached(const section& s) const; + + +public: //IMAGE + //Returns PE type (PE or PE+) from pe_type enumeration (minimal correctness checks) + static pe_type get_pe_type(std::istream& file); + //Returns PE type of this image + pe_type get_pe_type() const; + + //Returns true if image has overlay data at the end of file + bool has_overlay() const; + + //Realigns file (changes file alignment) + void realign_file(uint32_t new_file_alignment); + + //Helper function to recalculate RAW and virtual section sizes and strip it, if necessary + //auto_strip = strip section, if necessary + void recalculate_section_sizes(section& s, bool auto_strip); + + // ========== END OF PUBLIC MEMBERS AND STRUCTURES ========== // +private: + //Image DOS header + pe_win::image_dos_header dos_header_; + //Rich (stub) overlay data (for MSVS) + std::string rich_overlay_; + //List of image sections + section_list sections_; + //True if image has overlay + bool has_overlay_; + //Raw SizeOfHeaders-sized data from the beginning of image + std::string full_headers_data_; + //Raw debug data for all directories + //PointerToRawData; Data + debug_data_list debug_data_; + //PE or PE+ related properties + pe_properties* props_; + + //Reads and checks DOS header + void read_dos_header(std::istream& file); + + //Reads and checks PE headers and section headers, data + void read_pe(std::istream& file, bool read_debug_raw_data); + + //Sets number of sections + void set_number_of_sections(uint16_t number); + //Sets size of image + void set_size_of_image(uint32_t size); + //Sets file alignment (no checks) + void set_file_alignment_unchecked(uint32_t alignment); + //Returns needed magic of image + uint32_t get_needed_magic() const; + //Returns nt headers data pointer + char* get_nt_headers_ptr(); + +private: + static const uint16_t maximum_number_of_sections = 0x60; + static const uint32_t minimum_file_alignment = 512; + +private: + //RAW file offset to section convertion helpers (4gb max) + section_list::const_iterator file_offset_to_section(uint32_t offset) const; + section_list::iterator file_offset_to_section(uint32_t offset); +}; +} diff --git a/tools/pe_bliss/pe_bliss.h b/tools/pe_bliss/pe_bliss.h new file mode 100644 index 0000000000..1a8b430284 --- /dev/null +++ b/tools/pe_bliss/pe_bliss.h @@ -0,0 +1,39 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include "pe_base.h" +#include "pe_rebuilder.h" +#include "pe_factory.h" +#include "pe_bound_import.h" +#include "pe_debug.h" +#include "pe_dotnet.h" +#include "pe_exception_directory.h" +#include "pe_exports.h" +#include "pe_imports.h" +#include "pe_load_config.h" +#include "pe_relocations.h" +#include "pe_resources.h" +#include "pe_rich_data.h" +#include "pe_tls.h" +#include "pe_properties_generic.h" +#include "pe_checksum.h" +#include "entropy.h" diff --git a/tools/pe_bliss/pe_bliss_godot.cpp b/tools/pe_bliss/pe_bliss_godot.cpp new file mode 100644 index 0000000000..8297aa1045 --- /dev/null +++ b/tools/pe_bliss/pe_bliss_godot.cpp @@ -0,0 +1,118 @@ +#include "pe_bliss/pe_bliss.h" +#include "pe_bliss/pe_bliss_resources.h" +#include "core/ustring.h" +#include "core/dvector.h" +#include "os/file_access.h" + +using namespace pe_bliss; + +String pe_bliss_add_resrc(const char* p_path, int version_major, int version_minor, + String& company_name, String& file_description, + String& legal_copyright, String& version_text, + String& product_name, String& godot_version, + DVector<uint8_t>& icon_content) { + try + { + pe_base image(pe_factory::create_pe(p_path)); + + const section_list& pe_sections = image.get_image_sections(); + uint32_t end_of_pe = 0; + FileAccess *dst; + DVector<uint8_t> overlay_data; + if(image.has_overlay()) + { + end_of_pe = pe_sections.back().get_pointer_to_raw_data() + pe_sections.back().get_size_of_raw_data(); + dst=FileAccess::open(p_path,FileAccess::READ); + if (dst) { + overlay_data.resize(dst->get_len()-end_of_pe); + dst->seek(end_of_pe); + DVector<uint8_t>::Write overlay_data_write = overlay_data.write(); + dst->get_buffer(overlay_data_write.ptr(),overlay_data.size()); + dst->close(); + memdelete(dst); + } + } + resource_directory root; + if(image.has_resources()) + { + root = resource_directory(get_resources(image)); + } + pe_resource_manager res(root); + if(image.has_resources()) + { + if(icon_content.size()) { + if(res.resource_exists(pe_resource_viewer::resource_icon)) + { + res.remove_resource_type(pe_resource_viewer::resource_icon); + } + if(res.resource_exists(pe_resource_viewer::resource_icon_group)) + { + res.remove_resource_type(pe_resource_viewer::resource_icon_group); + } + } + if(res.resource_exists(pe_resource_viewer::resource_version)) + { + res.remove_resource_type(pe_resource_viewer::resource_version); + } + } + file_version_info file_info; + file_info.set_file_os(file_version_info::file_os_nt_win32); + file_info.set_file_type(file_version_info::file_type_application); + unsigned int ver = version_major << 16; + ver = ver + version_minor; + file_info.set_file_version_ms(ver); + file_info.set_file_version_ls(0x00000000); + file_info.set_product_version_ms(ver); + file_info.set_product_version_ls(0x00000000); + lang_string_values_map strings; + translation_values_map translations; + version_info_editor version(strings, translations); + version.add_translation(version_info_editor::default_language_translation); + version.set_company_name(company_name.c_str()); + version.set_file_description(file_description.c_str()); + if (!product_name.empty()) { + version.set_internal_name((product_name+String(".exe")).c_str()); + version.set_original_filename((product_name+String(".exe")).c_str()); + version.set_product_name(product_name.c_str()); + } + version.set_legal_copyright(legal_copyright.c_str()); + version.set_product_version(version_text.c_str()); + if(!godot_version.empty()) version.set_property(L"Godot Engine Version", godot_version.c_str() ); + resource_version_info_writer(res).set_version_info(file_info, strings, translations, 1033, 1200); + if(icon_content.size()) { + std::string icon; + icon.resize(icon_content.size()); + for(int i=0; i<icon_content.size(); i++) + { + icon[i] = icon_content[i]; + } + resource_cursor_icon_writer(res).add_icon(icon, L"MAIN_ICON", 1033); + } + if(image.has_resources()) + { + rebuild_resources(image, root, image.section_from_directory(pe_win::image_directory_entry_resource)); + } else { + section new_resources; + new_resources.get_raw_data().resize(1); + new_resources.set_name(".rsrc"); + new_resources.readable(true); + section& attached_section = image.add_section(new_resources); + rebuild_resources(image, root, attached_section); + } + rebuild_pe(image, p_path); + if(image.has_overlay() && end_of_pe) { + dst=FileAccess::open(p_path,FileAccess::READ_WRITE); + if (dst) { + dst->seek_end(); + DVector<uint8_t>::Read overlay_data_read = overlay_data.read(); + dst->store_buffer(overlay_data_read.ptr(),overlay_data.size()); + dst->close(); + memdelete(dst); + } + } + return String(); + } catch(const pe_exception& e) { + String ret("Error In Add rsrc Section : "); + return ret + String(e.what()); + } +} diff --git a/tools/pe_bliss/pe_bliss_godot.h b/tools/pe_bliss/pe_bliss_godot.h new file mode 100644 index 0000000000..0365ca9eaf --- /dev/null +++ b/tools/pe_bliss/pe_bliss_godot.h @@ -0,0 +1,7 @@ + + +String pe_bliss_add_resrc(const char* p_path, int version_major, int version_minor, + String& company_name, String& file_description, + String& legal_copyright, String& version_text, + String& product_name, String& godot_version, + DVector<uint8_t>& icon_content); diff --git a/tools/pe_bliss/pe_bliss_resources.h b/tools/pe_bliss/pe_bliss_resources.h new file mode 100644 index 0000000000..60369f8011 --- /dev/null +++ b/tools/pe_bliss/pe_bliss_resources.h @@ -0,0 +1,36 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include "file_version_info.h" +#include "message_table.h" +#include "pe_resource_manager.h" +#include "pe_resource_viewer.h" +#include "version_info_editor.h" +#include "version_info_viewer.h" +#include "resource_bitmap_reader.h" +#include "resource_bitmap_writer.h" +#include "resource_cursor_icon_reader.h" +#include "resource_cursor_icon_writer.h" +#include "resource_version_info_reader.h" +#include "resource_version_info_writer.h" +#include "resource_string_table_reader.h" +#include "resource_message_list_reader.h" diff --git a/tools/pe_bliss/pe_bound_import.cpp b/tools/pe_bliss/pe_bound_import.cpp new file mode 100644 index 0000000000..4b54b36105 --- /dev/null +++ b/tools/pe_bliss/pe_bound_import.cpp @@ -0,0 +1,311 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <string.h> +#include "pe_bound_import.h" +#include "utils.h" + +namespace pe_bliss +{ +using namespace pe_win; + +//BOUND IMPORT +//Default constructor +bound_import_ref::bound_import_ref() + :timestamp_(0) +{} + +//Constructor from data +bound_import_ref::bound_import_ref(const std::string& module_name, uint32_t timestamp) + :module_name_(module_name), timestamp_(timestamp) +{} + +//Returns imported module name +const std::string& bound_import_ref::get_module_name() const +{ + return module_name_; +} + +//Returns bound import date and time stamp +uint32_t bound_import_ref::get_timestamp() const +{ + return timestamp_; +} + +//Sets module name +void bound_import_ref::set_module_name(const std::string& module_name) +{ + module_name_ = module_name; +} + +//Sets timestamp +void bound_import_ref::set_timestamp(uint32_t timestamp) +{ + timestamp_ = timestamp; +} + +//Default constructor +bound_import::bound_import() + :timestamp_(0) +{} + +//Constructor from data +bound_import::bound_import(const std::string& module_name, uint32_t timestamp) + :module_name_(module_name), timestamp_(timestamp) +{} + +//Returns imported module name +const std::string& bound_import::get_module_name() const +{ + return module_name_; +} + +//Returns bound import date and time stamp +uint32_t bound_import::get_timestamp() const +{ + return timestamp_; +} + +//Returns bound references cound +size_t bound_import::get_module_ref_count() const +{ + return refs_.size(); +} + +//Returns module references +const bound_import::ref_list& bound_import::get_module_ref_list() const +{ + return refs_; +} + +//Adds module reference +void bound_import::add_module_ref(const bound_import_ref& ref) +{ + refs_.push_back(ref); +} + +//Clears module references list +void bound_import::clear_module_refs() +{ + refs_.clear(); +} + +//Returns module references +bound_import::ref_list& bound_import::get_module_ref_list() +{ + return refs_; +} + +//Sets module name +void bound_import::set_module_name(const std::string& module_name) +{ + module_name_ = module_name; +} + +//Sets timestamp +void bound_import::set_timestamp(uint32_t timestamp) +{ + timestamp_ = timestamp; +} + +const bound_import_module_list get_bound_import_module_list(const pe_base& pe) +{ + //Returned bound import modules list + bound_import_module_list ret; + + //If image has no bound imports + if(!pe.has_bound_import()) + return ret; + + uint32_t bound_import_data_len = + pe.section_data_length_from_rva(pe.get_directory_rva(image_directory_entry_bound_import), pe.get_directory_rva(image_directory_entry_bound_import), section_data_raw, true); + + if(bound_import_data_len < pe.get_directory_size(image_directory_entry_bound_import)) + throw pe_exception("Incorrect bound import directory", pe_exception::incorrect_bound_import_directory); + + const char* bound_import_data = pe.section_data_from_rva(pe.get_directory_rva(image_directory_entry_bound_import), section_data_raw, true); + + //Check read in "read_pe" function raw bound import data size + if(bound_import_data_len < sizeof(image_bound_import_descriptor)) + throw pe_exception("Incorrect bound import directory", pe_exception::incorrect_bound_import_directory); + + //current bound_import_data_ in-string position + unsigned long current_pos = 0; + //first bound import descriptor + //so, we're working with raw data here, no section helpers available + const image_bound_import_descriptor* descriptor = reinterpret_cast<const image_bound_import_descriptor*>(&bound_import_data[current_pos]); + + //Enumerate until zero + while(descriptor->OffsetModuleName) + { + //Check module name offset + if(descriptor->OffsetModuleName >= bound_import_data_len) + throw pe_exception("Incorrect bound import directory", pe_exception::incorrect_bound_import_directory); + + //Check module name for null-termination + if(!pe_utils::is_null_terminated(&bound_import_data[descriptor->OffsetModuleName], bound_import_data_len - descriptor->OffsetModuleName)) + throw pe_exception("Incorrect bound import directory", pe_exception::incorrect_bound_import_directory); + + //Create bound import descriptor structure + bound_import elem(&bound_import_data[descriptor->OffsetModuleName], descriptor->TimeDateStamp); + + //Check DWORDs + if(descriptor->NumberOfModuleForwarderRefs >= pe_utils::max_dword / sizeof(image_bound_forwarder_ref) + || !pe_utils::is_sum_safe(current_pos, 2 /* this descriptor and the next one */ * sizeof(image_bound_import_descriptor) + descriptor->NumberOfModuleForwarderRefs * sizeof(image_bound_forwarder_ref))) + throw pe_exception("Incorrect bound import directory", pe_exception::incorrect_bound_import_directory); + + //Move after current descriptor + current_pos += sizeof(image_bound_import_descriptor); + + //Enumerate referenced bound import descriptors + for(unsigned long i = 0; i != descriptor->NumberOfModuleForwarderRefs; ++i) + { + //They're just after parent descriptor + //Check size of structure + if(current_pos + sizeof(image_bound_forwarder_ref) > bound_import_data_len) + throw pe_exception("Incorrect bound import directory", pe_exception::incorrect_bound_import_directory); + + //Get IMAGE_BOUND_FORWARDER_REF pointer + const image_bound_forwarder_ref* ref_descriptor = reinterpret_cast<const image_bound_forwarder_ref*>(&bound_import_data[current_pos]); + + //Check referenced module name + if(ref_descriptor->OffsetModuleName >= bound_import_data_len) + throw pe_exception("Incorrect bound import directory", pe_exception::incorrect_bound_import_directory); + + //And its null-termination + if(!pe_utils::is_null_terminated(&bound_import_data[ref_descriptor->OffsetModuleName], bound_import_data_len - ref_descriptor->OffsetModuleName)) + throw pe_exception("Incorrect bound import directory", pe_exception::incorrect_bound_import_directory); + + //Add referenced module to current bound import structure + elem.add_module_ref(bound_import_ref(&bound_import_data[ref_descriptor->OffsetModuleName], ref_descriptor->TimeDateStamp)); + + //Move after referenced bound import descriptor + current_pos += sizeof(image_bound_forwarder_ref); + } + + //Check structure size + if(current_pos + sizeof(image_bound_import_descriptor) > bound_import_data_len) + throw pe_exception("Incorrect bound import directory", pe_exception::incorrect_bound_import_directory); + + //Move to next bound import descriptor + descriptor = reinterpret_cast<const image_bound_import_descriptor*>(&bound_import_data[current_pos]); + + //Save created descriptor structure and references + ret.push_back(elem); + } + + //Return result + return ret; +} + +//imports - bound imported modules list +//imports_section - section where export directory will be placed (must be attached to PE image) +//offset_from_section_start - offset from imports_section raw data start +//save_to_pe_headers - if true, new bound import directory information will be saved to PE image headers +//auto_strip_last_section - if true and bound imports are placed in the last section, it will be automatically stripped +const image_directory rebuild_bound_imports(pe_base& pe, const bound_import_module_list& imports, section& imports_section, uint32_t offset_from_section_start, bool save_to_pe_header, bool auto_strip_last_section) +{ + //Check that exports_section is attached to this PE image + if(!pe.section_attached(imports_section)) + throw pe_exception("Bound import section must be attached to PE file", pe_exception::section_is_not_attached); + + uint32_t directory_pos = pe_utils::align_up(offset_from_section_start, sizeof(uint32_t)); + uint32_t needed_size = sizeof(image_bound_import_descriptor) /* Ending null descriptor */; + uint32_t needed_size_for_strings = 0; + + //Calculate needed size for bound import data + for(bound_import_module_list::const_iterator it = imports.begin(); it != imports.end(); ++it) + { + const bound_import& import = *it; + needed_size += sizeof(image_bound_import_descriptor); + needed_size_for_strings += static_cast<uint32_t>((*it).get_module_name().length()) + 1 /* nullbyte */; + + const bound_import::ref_list& refs = import.get_module_ref_list(); + for(bound_import::ref_list::const_iterator ref_it = refs.begin(); ref_it != refs.end(); ++ref_it) + { + needed_size_for_strings += static_cast<uint32_t>((*ref_it).get_module_name().length()) + 1 /* nullbyte */; + needed_size += sizeof(image_bound_forwarder_ref); + } + } + + needed_size += needed_size_for_strings; + + //Check if imports_section is last one. If it's not, check if there's enough place for bound import data + if(&imports_section != &*(pe.get_image_sections().end() - 1) && + (imports_section.empty() || pe_utils::align_up(imports_section.get_size_of_raw_data(), pe.get_file_alignment()) < needed_size + directory_pos)) + throw pe_exception("Insufficient space for bound import directory", pe_exception::insufficient_space); + + std::string& raw_data = imports_section.get_raw_data(); + + //This will be done only if imports_section is the last section of image or for section with unaligned raw length of data + if(raw_data.length() < needed_size + directory_pos) + raw_data.resize(needed_size + directory_pos); //Expand section raw data + + uint32_t current_pos_for_structures = directory_pos; + uint32_t current_pos_for_strings = current_pos_for_structures + needed_size - needed_size_for_strings; + + for(bound_import_module_list::const_iterator it = imports.begin(); it != imports.end(); ++it) + { + const bound_import& import = *it; + image_bound_import_descriptor descriptor; + descriptor.NumberOfModuleForwarderRefs = static_cast<uint16_t>(import.get_module_ref_list().size()); + descriptor.OffsetModuleName = static_cast<uint16_t>(current_pos_for_strings - directory_pos); + descriptor.TimeDateStamp = import.get_timestamp(); + + memcpy(&raw_data[current_pos_for_structures], &descriptor, sizeof(descriptor)); + current_pos_for_structures += sizeof(descriptor); + + size_t length = import.get_module_name().length() + 1 /* nullbyte */; + memcpy(&raw_data[current_pos_for_strings], import.get_module_name().c_str(), length); + current_pos_for_strings += static_cast<uint32_t>(length); + + const bound_import::ref_list& refs = import.get_module_ref_list(); + for(bound_import::ref_list::const_iterator ref_it = refs.begin(); ref_it != refs.end(); ++ref_it) + { + const bound_import_ref& ref = *ref_it; + image_bound_forwarder_ref ref_descriptor = {0}; + ref_descriptor.OffsetModuleName = static_cast<uint16_t>(current_pos_for_strings - directory_pos); + ref_descriptor.TimeDateStamp = ref.get_timestamp(); + + memcpy(&raw_data[current_pos_for_structures], &ref_descriptor, sizeof(ref_descriptor)); + current_pos_for_structures += sizeof(ref_descriptor); + + length = ref.get_module_name().length() + 1 /* nullbyte */; + memcpy(&raw_data[current_pos_for_strings], ref.get_module_name().c_str(), length); + current_pos_for_strings += static_cast<uint32_t>(length); + } + } + + //Adjust section raw and virtual sizes + pe.recalculate_section_sizes(imports_section, auto_strip_last_section); + + image_directory ret(pe.rva_from_section_offset(imports_section, directory_pos), needed_size); + + //If auto-rewrite of PE headers is required + if(save_to_pe_header) + { + pe.set_directory_rva(image_directory_entry_bound_import, ret.get_rva()); + pe.set_directory_size(image_directory_entry_bound_import, ret.get_size()); + } + + return ret; +} +} diff --git a/tools/pe_bliss/pe_bound_import.h b/tools/pe_bliss/pe_bound_import.h new file mode 100644 index 0000000000..667e28792e --- /dev/null +++ b/tools/pe_bliss/pe_bound_import.h @@ -0,0 +1,108 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <vector> +#include <string> +#include "pe_structures.h" +#include "pe_base.h" +#include "pe_directory.h" + +namespace pe_bliss +{ +//Class representing bound import reference +class bound_import_ref +{ +public: + //Default constructor + bound_import_ref(); + //Constructor from data + bound_import_ref(const std::string& module_name, uint32_t timestamp); + + //Returns imported module name + const std::string& get_module_name() const; + //Returns bound import date and time stamp + uint32_t get_timestamp() const; + +public: //Setters + //Sets module name + void set_module_name(const std::string& module_name); + //Sets timestamp + void set_timestamp(uint32_t timestamp); + +private: + std::string module_name_; //Imported module name + uint32_t timestamp_; //Bound import timestamp +}; + +//Class representing image bound import information +class bound_import +{ +public: + typedef std::vector<bound_import_ref> ref_list; + +public: + //Default constructor + bound_import(); + //Constructor from data + bound_import(const std::string& module_name, uint32_t timestamp); + + //Returns imported module name + const std::string& get_module_name() const; + //Returns bound import date and time stamp + uint32_t get_timestamp() const; + + //Returns bound references cound + size_t get_module_ref_count() const; + //Returns module references + const ref_list& get_module_ref_list() const; + +public: //Setters + //Sets module name + void set_module_name(const std::string& module_name); + //Sets timestamp + void set_timestamp(uint32_t timestamp); + + //Adds module reference + void add_module_ref(const bound_import_ref& ref); + //Clears module references list + void clear_module_refs(); + //Returns module references + ref_list& get_module_ref_list(); + +private: + std::string module_name_; //Imported module name + uint32_t timestamp_; //Bound import timestamp + ref_list refs_; //Module references list +}; + +typedef std::vector<bound_import> bound_import_module_list; + +//Returns bound import information +const bound_import_module_list get_bound_import_module_list(const pe_base& pe);//Export directory rebuilder + +//imports - bound imported modules list +//imports_section - section where export directory will be placed (must be attached to PE image) +//offset_from_section_start - offset from imports_section raw data start +//save_to_pe_headers - if true, new bound import directory information will be saved to PE image headers +//auto_strip_last_section - if true and bound imports are placed in the last section, it will be automatically stripped +const image_directory rebuild_bound_imports(pe_base& pe, const bound_import_module_list& imports, section& imports_section, uint32_t offset_from_section_start = 0, bool save_to_pe_header = true, bool auto_strip_last_section = true); +} diff --git a/tools/pe_bliss/pe_checksum.cpp b/tools/pe_bliss/pe_checksum.cpp new file mode 100644 index 0000000000..5971a33c90 --- /dev/null +++ b/tools/pe_bliss/pe_checksum.cpp @@ -0,0 +1,103 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include "pe_checksum.h" +#include "pe_structures.h" +#include "pe_base.h" + +namespace pe_bliss +{ +using namespace pe_win; + +//Calculate checksum of image +uint32_t calculate_checksum(std::istream& file) +{ + //Save istream state + std::ios_base::iostate state = file.exceptions(); + std::streamoff old_offset = file.tellg(); + + //Checksum value + unsigned long long checksum = 0; + + try + { + image_dos_header header; + + file.exceptions(std::ios::goodbit); + + //Read DOS header + pe_base::read_dos_header(file, header); + + //Calculate PE checksum + file.seekg(0); + unsigned long long top = 0xFFFFFFFF; + top++; + + //"CheckSum" field position in optional PE headers - it's always 64 for PE and PE+ + static const unsigned long checksum_pos_in_optional_headers = 64; + //Calculate real PE headers "CheckSum" field position + //Sum is safe here + unsigned long pe_checksum_pos = header.e_lfanew + sizeof(image_file_header) + sizeof(uint32_t) + checksum_pos_in_optional_headers; + + //Calculate checksum for each byte of file + std::streamoff filesize = pe_utils::get_file_size(file); + for(long long i = 0; i < filesize; i += 4) + { + unsigned long dw = 0; + + //Read DWORD from file + file.read(reinterpret_cast<char*>(&dw), sizeof(unsigned long)); + //Skip "CheckSum" DWORD + if(i == pe_checksum_pos) + continue; + + //Calculate checksum + checksum = (checksum & 0xffffffff) + dw + (checksum >> 32); + if(checksum > top) + checksum = (checksum & 0xffffffff) + (checksum >> 32); + } + + //Finish checksum + checksum = (checksum & 0xffff) + (checksum >> 16); + checksum = (checksum) + (checksum >> 16); + checksum = checksum & 0xffff; + + checksum += static_cast<unsigned long>(filesize); + } + catch(const std::exception&) + { + //If something went wrong, restore istream state + file.exceptions(state); + file.seekg(old_offset); + file.clear(); + //Rethrow + throw; + } + + //Restore istream state + file.exceptions(state); + file.seekg(old_offset); + file.clear(); + + //Return checksum + return static_cast<uint32_t>(checksum); +} +} diff --git a/tools/pe_bliss/pe_checksum.h b/tools/pe_bliss/pe_checksum.h new file mode 100644 index 0000000000..a568d5d369 --- /dev/null +++ b/tools/pe_bliss/pe_checksum.h @@ -0,0 +1,30 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <istream> +#include "stdint_defs.h" + +namespace pe_bliss +{ +//Calculate checksum of image (performs no checks on PE structures) +uint32_t calculate_checksum(std::istream& file); +} diff --git a/tools/pe_bliss/pe_debug.cpp b/tools/pe_bliss/pe_debug.cpp new file mode 100644 index 0000000000..a0ed3f5af1 --- /dev/null +++ b/tools/pe_bliss/pe_debug.cpp @@ -0,0 +1,865 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <string.h> +#include "pe_debug.h" +#include "utils.h" + +namespace pe_bliss +{ +using namespace pe_win; +//DEBUG +//Default constructor +debug_info::debug_info() + :characteristics_(0), + time_stamp_(0), + major_version_(0), minor_version_(0), + type_(0), + size_of_data_(0), + address_of_raw_data_(0), + pointer_to_raw_data_(0), + advanced_info_type_(advanced_info_none) +{} + +//Constructor from data +debug_info::debug_info(const image_debug_directory& debug) + :characteristics_(debug.Characteristics), + time_stamp_(debug.TimeDateStamp), + major_version_(debug.MajorVersion), minor_version_(debug.MinorVersion), + type_(debug.Type), + size_of_data_(debug.SizeOfData), + address_of_raw_data_(debug.AddressOfRawData), + pointer_to_raw_data_(debug.PointerToRawData), + advanced_info_type_(advanced_info_none) +{} + +//Returns debug characteristics +uint32_t debug_info::get_characteristics() const +{ + return characteristics_; +} + +//Returns debug datetimestamp +uint32_t debug_info::get_time_stamp() const +{ + return time_stamp_; +} + +//Returns major version +uint32_t debug_info::get_major_version() const +{ + return major_version_; +} + +//Returns minor version +uint32_t debug_info::get_minor_version() const +{ + return minor_version_; +} + +//Returns type of debug info (unchecked) +uint32_t debug_info::get_type_raw() const +{ + return type_; +} + +//Returns type of debug info from debug_info_type enumeration +debug_info::debug_info_type debug_info::get_type() const +{ + //Determine debug type + switch(type_) + { + case image_debug_type_coff: + return debug_type_coff; + + case image_debug_type_codeview: + return debug_type_codeview; + + case image_debug_type_fpo: + return debug_type_fpo; + + case image_debug_type_misc: + return debug_type_misc; + + case image_debug_type_exception: + return debug_type_exception; + + case image_debug_type_fixup: + return debug_type_fixup; + + case image_debug_type_omap_to_src: + return debug_type_omap_to_src; + + case image_debug_type_omap_from_src: + return debug_type_omap_from_src; + + case image_debug_type_borland: + return debug_type_borland; + + case image_debug_type_clsid: + return debug_type_clsid; + + case image_debug_type_reserved10: + return debug_type_reserved10; + } + + return debug_type_unknown; +} + +//Returns size of debug data (internal, .pdb or other file doesn't count) +uint32_t debug_info::get_size_of_data() const +{ + return size_of_data_; +} + +//Returns RVA of debug info when mapped to memory or zero, if info is not mapped +uint32_t debug_info::get_rva_of_raw_data() const +{ + return address_of_raw_data_; +} + +//Returns raw file pointer to raw data +uint32_t debug_info::get_pointer_to_raw_data() const +{ + return pointer_to_raw_data_; +} + +//Copy constructor +debug_info::debug_info(const debug_info& info) + :characteristics_(info.characteristics_), + time_stamp_(info.time_stamp_), + major_version_(info.major_version_), minor_version_(info.minor_version_), + type_(info.type_), + size_of_data_(info.size_of_data_), + address_of_raw_data_(info.address_of_raw_data_), + pointer_to_raw_data_(info.pointer_to_raw_data_), + advanced_info_type_(info.advanced_info_type_) +{ + copy_advanced_info(info); +} + +//Copy assignment operator +debug_info& debug_info::operator=(const debug_info& info) +{ + copy_advanced_info(info); + + characteristics_ = info.characteristics_; + time_stamp_ = info.time_stamp_; + major_version_ = info.major_version_; + minor_version_ = info.minor_version_; + type_ = info.type_; + size_of_data_ = info.size_of_data_; + address_of_raw_data_ = info.address_of_raw_data_; + pointer_to_raw_data_ = info.pointer_to_raw_data_; + advanced_info_type_ = info.advanced_info_type_; + + return *this; +} + +//Default constructor +debug_info::advanced_info::advanced_info() + :adv_pdb_7_0_info(0) //Zero pointer to advanced data +{} + +//Returns true if advanced debug info is present +bool debug_info::advanced_info::is_present() const +{ + return adv_pdb_7_0_info != 0; +} + +//Helper for advanced debug information copying +void debug_info::copy_advanced_info(const debug_info& info) +{ + free_present_advanced_info(); + + switch(info.advanced_info_type_) + { + case advanced_info_pdb_7_0: + advanced_debug_info_.adv_pdb_7_0_info = new pdb_7_0_info(*info.advanced_debug_info_.adv_pdb_7_0_info); + break; + case advanced_info_pdb_2_0: + advanced_debug_info_.adv_pdb_2_0_info = new pdb_2_0_info(*info.advanced_debug_info_.adv_pdb_2_0_info); + break; + case advanced_info_misc: + advanced_debug_info_.adv_misc_info = new misc_debug_info(*info.advanced_debug_info_.adv_misc_info); + break; + case advanced_info_coff: + advanced_debug_info_.adv_coff_info = new coff_debug_info(*info.advanced_debug_info_.adv_coff_info); + break; + default: + break; + } + + advanced_info_type_ = info.advanced_info_type_; +} + +//Helper for clearing any present advanced debug information +void debug_info::free_present_advanced_info() +{ + switch(advanced_info_type_) + { + case advanced_info_pdb_7_0: + delete advanced_debug_info_.adv_pdb_7_0_info; + break; + case advanced_info_pdb_2_0: + delete advanced_debug_info_.adv_pdb_2_0_info; + break; + case advanced_info_misc: + delete advanced_debug_info_.adv_misc_info; + break; + case advanced_info_coff: + delete advanced_debug_info_.adv_coff_info; + break; + default: + break; + } + + advanced_debug_info_.adv_pdb_7_0_info = 0; + advanced_info_type_ = advanced_info_none; +} + +//Destructor +debug_info::~debug_info() +{ + free_present_advanced_info(); +} + +//Sets advanced debug information +void debug_info::set_advanced_debug_info(const pdb_7_0_info& info) +{ + free_present_advanced_info(); + advanced_debug_info_.adv_pdb_7_0_info = new pdb_7_0_info(info); + advanced_info_type_ = advanced_info_pdb_7_0; +} + +void debug_info::set_advanced_debug_info(const pdb_2_0_info& info) +{ + free_present_advanced_info(); + advanced_debug_info_.adv_pdb_2_0_info = new pdb_2_0_info(info); + advanced_info_type_ = advanced_info_pdb_2_0; +} + +void debug_info::set_advanced_debug_info(const misc_debug_info& info) +{ + free_present_advanced_info(); + advanced_debug_info_.adv_misc_info = new misc_debug_info(info); + advanced_info_type_ = advanced_info_misc; +} + +void debug_info::set_advanced_debug_info(const coff_debug_info& info) +{ + free_present_advanced_info(); + advanced_debug_info_.adv_coff_info = new coff_debug_info(info); + advanced_info_type_ = advanced_info_coff; +} + +//Returns advanced debug information type +debug_info::advanced_info_type debug_info::get_advanced_info_type() const +{ + return advanced_info_type_; +} + +//Returns advanced debug information or throws an exception, +//if requested information type is not contained by structure +template<> +const pdb_7_0_info debug_info::get_advanced_debug_info<pdb_7_0_info>() const +{ + if(advanced_info_type_ != advanced_info_pdb_7_0) + throw pe_exception("Debug info structure does not contain PDB 7.0 data", pe_exception::advanced_debug_information_request_error); + + return *advanced_debug_info_.adv_pdb_7_0_info; +} + +template<> +const pdb_2_0_info debug_info::get_advanced_debug_info<pdb_2_0_info>() const +{ + if(advanced_info_type_ != advanced_info_pdb_2_0) + throw pe_exception("Debug info structure does not contain PDB 2.0 data", pe_exception::advanced_debug_information_request_error); + + return *advanced_debug_info_.adv_pdb_2_0_info; +} + +template<> +const misc_debug_info debug_info::get_advanced_debug_info<misc_debug_info>() const +{ + if(advanced_info_type_ != advanced_info_misc) + throw pe_exception("Debug info structure does not contain MISC data", pe_exception::advanced_debug_information_request_error); + + return *advanced_debug_info_.adv_misc_info; +} + +template<> +const coff_debug_info debug_info::get_advanced_debug_info<coff_debug_info>() const +{ + if(advanced_info_type_ != advanced_info_coff) + throw pe_exception("Debug info structure does not contain COFF data", pe_exception::advanced_debug_information_request_error); + + return *advanced_debug_info_.adv_coff_info; +} + +//Sets advanced debug information type, if no advanced info structure available +void debug_info::set_advanced_info_type(advanced_info_type type) +{ + free_present_advanced_info(); + if(advanced_info_type_ >= advanced_info_codeview_4_0) //Don't set info type for those types, which have advanced info structures + advanced_info_type_ = type; +} + +//Default constructor +pdb_7_0_info::pdb_7_0_info() + :age_(0) +{ + memset(&guid_, 0, sizeof(guid_)); +} + +//Constructor from data +pdb_7_0_info::pdb_7_0_info(const CV_INFO_PDB70* info) + :age_(info->Age), guid_(info->Signature), + pdb_file_name_(reinterpret_cast<const char*>(info->PdbFileName)) //Must be checked before for null-termination +{} + +//Returns debug PDB 7.0 structure GUID +const guid pdb_7_0_info::get_guid() const +{ + return guid_; +} + +//Returns age of build +uint32_t pdb_7_0_info::get_age() const +{ + return age_; +} + +//Returns PDB file name / path +const std::string& pdb_7_0_info::get_pdb_file_name() const +{ + return pdb_file_name_; +} + +//Default constructor +pdb_2_0_info::pdb_2_0_info() + :age_(0), signature_(0) +{} + +//Constructor from data +pdb_2_0_info::pdb_2_0_info(const CV_INFO_PDB20* info) + :age_(info->Age), signature_(info->Signature), + pdb_file_name_(reinterpret_cast<const char*>(info->PdbFileName)) //Must be checked before for null-termination +{} + +//Returns debug PDB 2.0 structure signature +uint32_t pdb_2_0_info::get_signature() const +{ + return signature_; +} + +//Returns age of build +uint32_t pdb_2_0_info::get_age() const +{ + return age_; +} + +//Returns PDB file name / path +const std::string& pdb_2_0_info::get_pdb_file_name() const +{ + return pdb_file_name_; +} + +//Default constructor +misc_debug_info::misc_debug_info() + :data_type_(0), unicode_(false) +{} + +//Constructor from data +misc_debug_info::misc_debug_info(const image_debug_misc* info) + :data_type_(info->DataType), unicode_(info->Unicode ? true : false) +{ + //IMAGE_DEBUG_MISC::Data must be checked before! + if(info->Unicode) + { +#ifdef PE_BLISS_WINDOWS + debug_data_unicode_ = std::wstring(reinterpret_cast<const wchar_t*>(info->Data), (info->Length - sizeof(image_debug_misc) + 1 /* BYTE[1] in the end of structure */) / 2); +#else + debug_data_unicode_ = pe_utils::from_ucs2(u16string(reinterpret_cast<const unicode16_t*>(info->Data), (info->Length - sizeof(image_debug_misc) + 1 /* BYTE[1] in the end of structure */) / 2)); +#endif + + pe_utils::strip_nullbytes(debug_data_unicode_); //Strip nullbytes in the end of string + } + else + { + debug_data_ansi_ = std::string(reinterpret_cast<const char*>(info->Data), info->Length - sizeof(image_debug_misc) + 1 /* BYTE[1] in the end of structure */); + pe_utils::strip_nullbytes(debug_data_ansi_); //Strip nullbytes in the end of string + } +} + +//Returns debug data type +uint32_t misc_debug_info::get_data_type() const +{ + return data_type_; +} + +//Returns true if data type is exe name +bool misc_debug_info::is_exe_name() const +{ + return data_type_ == image_debug_misc_exename; +} + +//Returns true if debug data is UNICODE +bool misc_debug_info::is_unicode() const +{ + return unicode_; +} + +//Returns debug data (ANSI) +const std::string& misc_debug_info::get_data_ansi() const +{ + return debug_data_ansi_; +} + +//Returns debug data (UNICODE) +const std::wstring& misc_debug_info::get_data_unicode() const +{ + return debug_data_unicode_; +} + +//Default constructor +coff_debug_info::coff_debug_info() + :number_of_symbols_(0), + lva_to_first_symbol_(0), + number_of_line_numbers_(0), + lva_to_first_line_number_(0), + rva_to_first_byte_of_code_(0), + rva_to_last_byte_of_code_(0), + rva_to_first_byte_of_data_(0), + rva_to_last_byte_of_data_(0) +{} + +//Constructor from data +coff_debug_info::coff_debug_info(const image_coff_symbols_header* info) + :number_of_symbols_(info->NumberOfSymbols), + lva_to_first_symbol_(info->LvaToFirstSymbol), + number_of_line_numbers_(info->NumberOfLinenumbers), + lva_to_first_line_number_(info->LvaToFirstLinenumber), + rva_to_first_byte_of_code_(info->RvaToFirstByteOfCode), + rva_to_last_byte_of_code_(info->RvaToLastByteOfCode), + rva_to_first_byte_of_data_(info->RvaToFirstByteOfData), + rva_to_last_byte_of_data_(info->RvaToLastByteOfData) +{} + +//Returns number of symbols +uint32_t coff_debug_info::get_number_of_symbols() const +{ + return number_of_symbols_; +} + +//Returns virtual address of the first symbol +uint32_t coff_debug_info::get_lva_to_first_symbol() const +{ + return lva_to_first_symbol_; +} + +//Returns number of line-number entries +uint32_t coff_debug_info::get_number_of_line_numbers() const +{ + return number_of_line_numbers_; +} + +//Returns virtual address of the first line-number entry +uint32_t coff_debug_info::get_lva_to_first_line_number() const +{ + return lva_to_first_line_number_; +} + +//Returns relative virtual address of the first byte of code +uint32_t coff_debug_info::get_rva_to_first_byte_of_code() const +{ + return rva_to_first_byte_of_code_; +} + +//Returns relative virtual address of the last byte of code +uint32_t coff_debug_info::get_rva_to_last_byte_of_code() const +{ + return rva_to_last_byte_of_code_; +} + +//Returns relative virtual address of the first byte of data +uint32_t coff_debug_info::get_rva_to_first_byte_of_data() const +{ + return rva_to_first_byte_of_data_; +} + +//Returns relative virtual address of the last byte of data +uint32_t coff_debug_info::get_rva_to_last_byte_of_data() const +{ + return rva_to_last_byte_of_data_; +} + +//Returns COFF symbols list +const coff_debug_info::coff_symbols_list& coff_debug_info::get_symbols() const +{ + return symbols_; +} + +//Adds COFF symbol +void coff_debug_info::add_symbol(const coff_symbol& sym) +{ + symbols_.push_back(sym); +} + +//Default constructor +coff_debug_info::coff_symbol::coff_symbol() + :storage_class_(0), + index_(0), + section_number_(0), rva_(0), + type_(0), + is_filename_(false) +{} + +//Returns storage class +uint32_t coff_debug_info::coff_symbol::get_storage_class() const +{ + return storage_class_; +} + +//Returns symbol index +uint32_t coff_debug_info::coff_symbol::get_index() const +{ + return index_; +} + +//Returns section number +uint32_t coff_debug_info::coff_symbol::get_section_number() const +{ + return section_number_; +} + +//Returns RVA +uint32_t coff_debug_info::coff_symbol::get_rva() const +{ + return rva_; +} + +//Returns true if structure contains file name +bool coff_debug_info::coff_symbol::is_file() const +{ + return is_filename_; +} + +//Returns text data (symbol or file name) +const std::string& coff_debug_info::coff_symbol::get_symbol() const +{ + return name_; +} + +//Sets storage class +void coff_debug_info::coff_symbol::set_storage_class(uint32_t storage_class) +{ + storage_class_ = storage_class; +} + +//Sets symbol index +void coff_debug_info::coff_symbol::set_index(uint32_t index) +{ + index_ = index; +} + +//Sets section number +void coff_debug_info::coff_symbol::set_section_number(uint32_t section_number) +{ + section_number_ = section_number; +} + +//Sets RVA +void coff_debug_info::coff_symbol::set_rva(uint32_t rva) +{ + rva_ = rva; +} + +//Sets file name +void coff_debug_info::coff_symbol::set_file_name(const std::string& file_name) +{ + name_ = file_name; + is_filename_ = true; +} + +//Sets symbol name +void coff_debug_info::coff_symbol::set_symbol_name(const std::string& symbol_name) +{ + name_ = symbol_name; + is_filename_ = false; +} + +//Returns type +uint16_t coff_debug_info::coff_symbol::get_type() const +{ + return type_; +} + +//Sets type +void coff_debug_info::coff_symbol::set_type(uint16_t type) +{ + type_ = type; +} + +//Returns debug information list +const debug_info_list get_debug_information(const pe_base& pe) +{ + debug_info_list ret; + + //If there's no debug directory, return empty list + if(!pe.has_debug()) + return ret; + + //Check the length in bytes of the section containing debug directory + if(pe.section_data_length_from_rva(pe.get_directory_rva(image_directory_entry_debug), pe.get_directory_rva(image_directory_entry_debug), section_data_virtual, true) + < sizeof(image_debug_directory)) + throw pe_exception("Incorrect debug directory", pe_exception::incorrect_debug_directory); + + unsigned long current_pos = pe.get_directory_rva(image_directory_entry_debug); + + //First IMAGE_DEBUG_DIRECTORY table + image_debug_directory directory = pe.section_data_from_rva<image_debug_directory>(current_pos, section_data_virtual, true); + + if(!pe_utils::is_sum_safe(pe.get_directory_rva(image_directory_entry_debug), pe.get_directory_size(image_directory_entry_debug))) + throw pe_exception("Incorrect debug directory", pe_exception::incorrect_debug_directory); + + //Iterate over all IMAGE_DEBUG_DIRECTORY directories + while(directory.PointerToRawData + && current_pos < pe.get_directory_rva(image_directory_entry_debug) + pe.get_directory_size(image_directory_entry_debug)) + { + //Create debug information structure + debug_info info(directory); + + //Find raw debug data + const pe_base::debug_data_list& debug_datas = pe.get_raw_debug_data_list(); + pe_base::debug_data_list::const_iterator it = debug_datas.find(directory.PointerToRawData); + if(it != debug_datas.end()) //If it exists, we'll do some detailed debug info research + { + const std::string& debug_data = (*it).second; + switch(directory.Type) + { + case image_debug_type_coff: + { + //Check data length + if(debug_data.length() < sizeof(image_coff_symbols_header)) + throw pe_exception("Incorrect debug directory", pe_exception::incorrect_debug_directory); + + //Get coff header structure pointer + const image_coff_symbols_header* coff = reinterpret_cast<const image_coff_symbols_header*>(debug_data.data()); + + //Check possible overflows + if(coff->NumberOfSymbols >= pe_utils::max_dword / sizeof(image_symbol) + || !pe_utils::is_sum_safe(coff->NumberOfSymbols * sizeof(image_symbol), coff->LvaToFirstSymbol)) + throw pe_exception("Incorrect debug directory", pe_exception::incorrect_debug_directory); + + //Check data length again + if(debug_data.length() < coff->NumberOfSymbols * sizeof(image_symbol) + coff->LvaToFirstSymbol) + throw pe_exception("Incorrect debug directory", pe_exception::incorrect_debug_directory); + + //Create COFF debug info structure + coff_debug_info coff_info(coff); + + //Enumerate debug symbols data + for(uint32_t i = 0; i < coff->NumberOfSymbols; ++i) + { + //Safe sum (checked above) + const image_symbol* sym = reinterpret_cast<const image_symbol*>(debug_data.data() + i * sizeof(image_symbol) + coff->LvaToFirstSymbol); + + coff_debug_info::coff_symbol symbol; + symbol.set_index(i); //Save symbol index + symbol.set_storage_class(sym->StorageClass); //Save storage class + symbol.set_type(sym->Type); //Save storage class + + //Check data length again + if(!pe_utils::is_sum_safe(i, sym->NumberOfAuxSymbols) + || (i + sym->NumberOfAuxSymbols) > coff->NumberOfSymbols + || debug_data.length() < (i + 1) * sizeof(image_symbol) + coff->LvaToFirstSymbol + sym->NumberOfAuxSymbols * sizeof(image_symbol)) + throw pe_exception("Incorrect debug directory", pe_exception::incorrect_debug_directory); + + //If symbol is filename + if(sym->StorageClass == image_sym_class_file) + { + //Save file name, it is situated just after this IMAGE_SYMBOL structure + std::string file_name(reinterpret_cast<const char*>(debug_data.data() + (i + 1) * sizeof(image_symbol)), sym->NumberOfAuxSymbols * sizeof(image_symbol)); + pe_utils::strip_nullbytes(file_name); + symbol.set_file_name(file_name); + + //Save symbol info + coff_info.add_symbol(symbol); + + //Move to next symbol + i += sym->NumberOfAuxSymbols; + continue; + } + + //Dump some other symbols + if(((sym->StorageClass == image_sym_class_static) + && (sym->NumberOfAuxSymbols == 0) + && (sym->SectionNumber == 1)) + || + ((sym->StorageClass == image_sym_class_external) + && ISFCN(sym->Type) + && (sym->SectionNumber > 0)) + ) + { + //Save RVA and section number + symbol.set_section_number(sym->SectionNumber); + symbol.set_rva(sym->Value); + + //If symbol has short name + if(sym->N.Name.Short) + { + //Copy and save symbol name + char name_buff[9]; + memcpy(name_buff, sym->N.ShortName, 8); + name_buff[8] = '\0'; + symbol.set_symbol_name(name_buff); + } + else + { + //Symbol has long name + + //Check possible overflows + if(!pe_utils::is_sum_safe(coff->LvaToFirstSymbol + coff->NumberOfSymbols * sizeof(image_symbol), sym->N.Name.Long)) + throw pe_exception("Incorrect debug directory", pe_exception::incorrect_debug_directory); + + //Here we have an offset to the string table + uint32_t symbol_offset = coff->LvaToFirstSymbol + coff->NumberOfSymbols * sizeof(image_symbol) + sym->N.Name.Long; + + //Check data length + if(debug_data.length() < symbol_offset) + throw pe_exception("Incorrect debug directory", pe_exception::incorrect_debug_directory); + + //Check symbol name for null-termination + if(!pe_utils::is_null_terminated(debug_data.data() + symbol_offset, debug_data.length() - symbol_offset)) + throw pe_exception("Incorrect debug directory", pe_exception::incorrect_debug_directory); + + //Save symbol name + symbol.set_symbol_name(debug_data.data() + symbol_offset); + } + + //Save symbol info + coff_info.add_symbol(symbol); + + //Move to next symbol + i += sym->NumberOfAuxSymbols; + continue; + } + } + + info.set_advanced_debug_info(coff_info); + } + break; + + case image_debug_type_codeview: + { + //Check data length + if(debug_data.length() < sizeof(OMFSignature*)) + throw pe_exception("Incorrect debug directory", pe_exception::incorrect_debug_directory); + + //Get POMFSignature structure pointer from the very beginning of debug data + const OMFSignature* sig = reinterpret_cast<const OMFSignature*>(debug_data.data()); + if(!memcmp(sig->Signature, "RSDS", 4)) + { + //Signature is "RSDS" - PDB 7.0 + + //Check data length + if(debug_data.length() < sizeof(CV_INFO_PDB70)) + throw pe_exception("Incorrect debug directory", pe_exception::incorrect_debug_directory); + + const CV_INFO_PDB70* pdb_data = reinterpret_cast<const CV_INFO_PDB70*>(debug_data.data()); + + //Check PDB file name null-termination + if(!pe_utils::is_null_terminated(pdb_data->PdbFileName, debug_data.length() - (sizeof(CV_INFO_PDB70) - 1 /* BYTE of filename in structure */))) + throw pe_exception("Incorrect debug directory", pe_exception::incorrect_debug_directory); + + info.set_advanced_debug_info(pdb_7_0_info(pdb_data)); + } + else if(!memcmp(sig->Signature, "NB10", 4)) + { + //Signature is "NB10" - PDB 2.0 + + //Check data length + if(debug_data.length() < sizeof(CV_INFO_PDB20)) + throw pe_exception("Incorrect debug directory", pe_exception::incorrect_debug_directory); + + const CV_INFO_PDB20* pdb_data = reinterpret_cast<const CV_INFO_PDB20*>(debug_data.data()); + + //Check PDB file name null-termination + if(!pe_utils::is_null_terminated(pdb_data->PdbFileName, debug_data.length() - (sizeof(CV_INFO_PDB20) - 1 /* BYTE of filename in structure */))) + throw pe_exception("Incorrect debug directory", pe_exception::incorrect_debug_directory); + + info.set_advanced_debug_info(pdb_2_0_info(pdb_data)); + } + else if(!memcmp(sig->Signature, "NB09", 4)) + { + //CodeView 4.0, no structures available + info.set_advanced_info_type(debug_info::advanced_info_codeview_4_0); + } + else if(!memcmp(sig->Signature, "NB11", 4)) + { + //CodeView 5.0, no structures available + info.set_advanced_info_type(debug_info::advanced_info_codeview_5_0); + } + else if(!memcmp(sig->Signature, "NB05", 4)) + { + //Other CodeView, no structures available + info.set_advanced_info_type(debug_info::advanced_info_codeview); + } + } + + break; + + case image_debug_type_misc: + { + //Check data length + if(debug_data.length() < sizeof(image_debug_misc)) + throw pe_exception("Incorrect debug directory", pe_exception::incorrect_debug_directory); + + //Get misc structure pointer + const image_debug_misc* misc_data = reinterpret_cast<const image_debug_misc*>(debug_data.data()); + + //Check misc data length + if(debug_data.length() < misc_data->Length /* Total length of record */) + throw pe_exception("Incorrect debug directory", pe_exception::incorrect_debug_directory); + + //Save advanced information + info.set_advanced_debug_info(misc_debug_info(misc_data)); + } + break; + } + } + + //Save debug information structure + ret.push_back(info); + + //Check possible overflow + if(!pe_utils::is_sum_safe(current_pos, sizeof(image_debug_directory))) + throw pe_exception("Incorrect debug directory", pe_exception::incorrect_debug_directory); + + //Go to next debug entry + current_pos += sizeof(image_debug_directory); + directory = pe.section_data_from_rva<image_debug_directory>(current_pos, section_data_virtual, true); + } + + return ret; +} +} diff --git a/tools/pe_bliss/pe_debug.h b/tools/pe_bliss/pe_debug.h new file mode 100644 index 0000000000..73a7e6860d --- /dev/null +++ b/tools/pe_bliss/pe_debug.h @@ -0,0 +1,324 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <vector> +#include "pe_structures.h" +#include "pe_base.h" + +namespace pe_bliss +{ +//Class representing advanced RSDS (PDB 7.0) information +class pdb_7_0_info +{ +public: + //Default constructor + pdb_7_0_info(); + //Constructor from data + explicit pdb_7_0_info(const pe_win::CV_INFO_PDB70* info); + + //Returns debug PDB 7.0 structure GUID + const pe_win::guid get_guid() const; + //Returns age of build + uint32_t get_age() const; + //Returns PDB file name / path + const std::string& get_pdb_file_name() const; + +private: + uint32_t age_; + pe_win::guid guid_; + std::string pdb_file_name_; +}; + +//Class representing advanced NB10 (PDB 2.0) information +class pdb_2_0_info +{ +public: + //Default constructor + pdb_2_0_info(); + //Constructor from data + explicit pdb_2_0_info(const pe_win::CV_INFO_PDB20* info); + + //Returns debug PDB 2.0 structure signature + uint32_t get_signature() const; + //Returns age of build + uint32_t get_age() const; + //Returns PDB file name / path + const std::string& get_pdb_file_name() const; + +private: + uint32_t age_; + uint32_t signature_; + std::string pdb_file_name_; +}; + +//Class representing advanced misc (IMAGE_DEBUG_TYPE_MISC) info +class misc_debug_info +{ +public: + //Default constructor + misc_debug_info(); + //Constructor from data + explicit misc_debug_info(const pe_win::image_debug_misc* info); + + //Returns debug data type + uint32_t get_data_type() const; + //Returns true if data type is exe name + bool is_exe_name() const; + + //Returns true if debug data is UNICODE + bool is_unicode() const; + //Returns debug data (ANSI or UNICODE) + const std::string& get_data_ansi() const; + const std::wstring& get_data_unicode() const; + +private: + uint32_t data_type_; + bool unicode_; + std::string debug_data_ansi_; + std::wstring debug_data_unicode_; +}; + +//Class representing COFF (IMAGE_DEBUG_TYPE_COFF) debug info +class coff_debug_info +{ +public: + //Structure representing COFF symbol + struct coff_symbol + { + public: + //Default constructor + coff_symbol(); + + //Returns storage class + uint32_t get_storage_class() const; + //Returns symbol index + uint32_t get_index() const; + //Returns section number + uint32_t get_section_number() const; + //Returns RVA + uint32_t get_rva() const; + //Returns type + uint16_t get_type() const; + + //Returns true if structure contains file name + bool is_file() const; + //Returns text data (symbol or file name) + const std::string& get_symbol() const; + + public: //These functions do not change everything inside image, they are used by PE class + //Sets storage class + void set_storage_class(uint32_t storage_class); + //Sets symbol index + void set_index(uint32_t index); + //Sets section number + void set_section_number(uint32_t section_number); + //Sets RVA + void set_rva(uint32_t rva); + //Sets type + void set_type(uint16_t type); + + //Sets file name + void set_file_name(const std::string& file_name); + //Sets symbol name + void set_symbol_name(const std::string& symbol_name); + + private: + uint32_t storage_class_; + uint32_t index_; + uint32_t section_number_, rva_; + uint16_t type_; + bool is_filename_; + std::string name_; + }; + +public: + typedef std::vector<coff_symbol> coff_symbols_list; + +public: + //Default constructor + coff_debug_info(); + //Constructor from data + explicit coff_debug_info(const pe_win::image_coff_symbols_header* info); + + //Returns number of symbols + uint32_t get_number_of_symbols() const; + //Returns virtual address of the first symbol + uint32_t get_lva_to_first_symbol() const; + //Returns number of line-number entries + uint32_t get_number_of_line_numbers() const; + //Returns virtual address of the first line-number entry + uint32_t get_lva_to_first_line_number() const; + //Returns relative virtual address of the first byte of code + uint32_t get_rva_to_first_byte_of_code() const; + //Returns relative virtual address of the last byte of code + uint32_t get_rva_to_last_byte_of_code() const; + //Returns relative virtual address of the first byte of data + uint32_t get_rva_to_first_byte_of_data() const; + //Returns relative virtual address of the last byte of data + uint32_t get_rva_to_last_byte_of_data() const; + + //Returns COFF symbols list + const coff_symbols_list& get_symbols() const; + +public: //These functions do not change everything inside image, they are used by PE class + //Adds COFF symbol + void add_symbol(const coff_symbol& sym); + +private: + uint32_t number_of_symbols_; + uint32_t lva_to_first_symbol_; + uint32_t number_of_line_numbers_; + uint32_t lva_to_first_line_number_; + uint32_t rva_to_first_byte_of_code_; + uint32_t rva_to_last_byte_of_code_; + uint32_t rva_to_first_byte_of_data_; + uint32_t rva_to_last_byte_of_data_; + +private: + coff_symbols_list symbols_; +}; + +//Class representing debug information +class debug_info +{ +public: + //Enumeration of debug information types + enum debug_info_type + { + debug_type_unknown, + debug_type_coff, + debug_type_codeview, + debug_type_fpo, + debug_type_misc, + debug_type_exception, + debug_type_fixup, + debug_type_omap_to_src, + debug_type_omap_from_src, + debug_type_borland, + debug_type_reserved10, + debug_type_clsid + }; + +public: + //Enumeration of advanced debug information types + enum advanced_info_type + { + advanced_info_none, //No advanced info + advanced_info_pdb_7_0, //PDB 7.0 + advanced_info_pdb_2_0, //PDB 2.0 + advanced_info_misc, //MISC debug info + advanced_info_coff, //COFF debug info + //No advanced info structures available for types below + advanced_info_codeview_4_0, //CodeView 4.0 + advanced_info_codeview_5_0, //CodeView 5.0 + advanced_info_codeview //CodeView + }; + +public: + //Default constructor + debug_info(); + //Constructor from data + explicit debug_info(const pe_win::image_debug_directory& debug); + //Copy constructor + debug_info(const debug_info& info); + //Copy assignment operator + debug_info& operator=(const debug_info& info); + //Destructor + ~debug_info(); + + //Returns debug characteristics + uint32_t get_characteristics() const; + //Returns debug datetimestamp + uint32_t get_time_stamp() const; + //Returns major version + uint32_t get_major_version() const; + //Returns minor version + uint32_t get_minor_version() const; + //Returns type of debug info (unchecked) + uint32_t get_type_raw() const; + //Returns type of debug info from debug_info_type enumeration + debug_info_type get_type() const; + //Returns size of debug data (internal, .pdb or other file doesn't count) + uint32_t get_size_of_data() const; + //Returns RVA of debug info when mapped to memory or zero, if info is not mapped + uint32_t get_rva_of_raw_data() const; + //Returns raw file pointer to raw data + uint32_t get_pointer_to_raw_data() const; + + //Returns advanced debug information type + advanced_info_type get_advanced_info_type() const; + //Returns advanced debug information or throws an exception, + //if requested information type is not contained by structure + template<typename AdvancedInfo> + const AdvancedInfo get_advanced_debug_info() const; + +public: //These functions do not change everything inside image, they are used by PE class + //Sets advanced debug information + void set_advanced_debug_info(const pdb_7_0_info& info); + void set_advanced_debug_info(const pdb_2_0_info& info); + void set_advanced_debug_info(const misc_debug_info& info); + void set_advanced_debug_info(const coff_debug_info& info); + + //Sets advanced debug information type, if no advanced info structure available + void set_advanced_info_type(advanced_info_type type); + +private: + uint32_t characteristics_; + uint32_t time_stamp_; + uint32_t major_version_, minor_version_; + uint32_t type_; + uint32_t size_of_data_; + uint32_t address_of_raw_data_; //RVA when mapped or 0 + uint32_t pointer_to_raw_data_; //RAW file offset + + //Union containing advanced debug information pointer + union advanced_info + { + public: + //Default constructor + advanced_info(); + + //Returns true if advanced debug info is present + bool is_present() const; + + public: + pdb_7_0_info* adv_pdb_7_0_info; + pdb_2_0_info* adv_pdb_2_0_info; + misc_debug_info* adv_misc_info; + coff_debug_info* adv_coff_info; + }; + + //Helper for advanced debug information copying + void copy_advanced_info(const debug_info& info); + //Helper for clearing any present advanced debug information + void free_present_advanced_info(); + + advanced_info advanced_debug_info_; + //Advanced information type + advanced_info_type advanced_info_type_; +}; + +typedef std::vector<debug_info> debug_info_list; + +//Returns debug information list +const debug_info_list get_debug_information(const pe_base& pe); +} diff --git a/tools/pe_bliss/pe_directory.cpp b/tools/pe_bliss/pe_directory.cpp new file mode 100644 index 0000000000..13ad2afc5d --- /dev/null +++ b/tools/pe_bliss/pe_directory.cpp @@ -0,0 +1,59 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include "pe_directory.h" + +namespace pe_bliss +{ +//Default constructor +image_directory::image_directory() + :rva_(0), size_(0) +{} + +//Constructor from data +image_directory::image_directory(uint32_t rva, uint32_t size) + :rva_(rva), size_(size) +{} + +//Returns RVA +uint32_t image_directory::get_rva() const +{ + return rva_; +} + +//Returns size +uint32_t image_directory::get_size() const +{ + return size_; +} + +//Sets RVA +void image_directory::set_rva(uint32_t rva) +{ + rva_ = rva; +} + +//Sets size +void image_directory::set_size(uint32_t size) +{ + size_ = size; +} +} diff --git a/tools/pe_bliss/pe_directory.h b/tools/pe_bliss/pe_directory.h new file mode 100644 index 0000000000..a7b1ea7a5f --- /dev/null +++ b/tools/pe_bliss/pe_directory.h @@ -0,0 +1,50 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include "stdint_defs.h" + +namespace pe_bliss +{ +//Class representing image directory data +class image_directory +{ +public: + //Default constructor + image_directory(); + //Constructor from data + image_directory(uint32_t rva, uint32_t size); + + //Returns RVA + uint32_t get_rva() const; + //Returns size + uint32_t get_size() const; + + //Sets RVA + void set_rva(uint32_t rva); + //Sets size + void set_size(uint32_t size); + +private: + uint32_t rva_; + uint32_t size_; +}; +} diff --git a/tools/pe_bliss/pe_dotnet.cpp b/tools/pe_bliss/pe_dotnet.cpp new file mode 100644 index 0000000000..f34a76eae8 --- /dev/null +++ b/tools/pe_bliss/pe_dotnet.cpp @@ -0,0 +1,186 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <string.h> +#include "pe_dotnet.h" + +namespace pe_bliss +{ +using namespace pe_win; + +//.NET +basic_dotnet_info::basic_dotnet_info() +{ + memset(&header_, 0, sizeof(header_)); +} + +//Constructor from data +basic_dotnet_info::basic_dotnet_info(const image_cor20_header& header) + :header_(header) +{} + +//Returns major runtime version +uint16_t basic_dotnet_info::get_major_runtime_version() const +{ + return header_.MajorRuntimeVersion; +} + +//Returns minor runtime version +uint16_t basic_dotnet_info::get_minor_runtime_version() const +{ + return header_.MinorRuntimeVersion; +} + +//Returns RVA of metadata (symbol table and startup information) +uint32_t basic_dotnet_info::get_rva_of_metadata() const +{ + return header_.MetaData.VirtualAddress; +} + +//Returns size of metadata (symbol table and startup information) +uint32_t basic_dotnet_info::get_size_of_metadata() const +{ + return header_.MetaData.Size; +} + +//Returns flags +uint32_t basic_dotnet_info::get_flags() const +{ + return header_.Flags; +} + +//Returns true if entry point is native +bool basic_dotnet_info::is_native_entry_point() const +{ + return (header_.Flags & comimage_flags_native_entrypoint) ? true : false; +} + +//Returns true if 32 bit required +bool basic_dotnet_info::is_32bit_required() const +{ + return (header_.Flags & comimage_flags_32bitrequired) ? true : false; +} + +//Returns true if image is IL library +bool basic_dotnet_info::is_il_library() const +{ + return (header_.Flags & comimage_flags_il_library) ? true : false; +} + +//Returns true if image uses IL only +bool basic_dotnet_info::is_il_only() const +{ + return (header_.Flags & comimage_flags_ilonly) ? true : false; +} + +//Returns entry point RVA (if entry point is native) +//Returns entry point managed token (if entry point is managed) +uint32_t basic_dotnet_info::get_entry_point_rva_or_token() const +{ + return header_.EntryPointToken; +} + +//Returns RVA of managed resources +uint32_t basic_dotnet_info::get_rva_of_resources() const +{ + return header_.Resources.VirtualAddress; +} + +//Returns size of managed resources +uint32_t basic_dotnet_info::get_size_of_resources() const +{ + return header_.Resources.Size; +} + +//Returns RVA of strong name signature +uint32_t basic_dotnet_info::get_rva_of_strong_name_signature() const +{ + return header_.StrongNameSignature.VirtualAddress; +} + +//Returns size of strong name signature +uint32_t basic_dotnet_info::get_size_of_strong_name_signature() const +{ + return header_.StrongNameSignature.Size; +} + +//Returns RVA of code manager table +uint32_t basic_dotnet_info::get_rva_of_code_manager_table() const +{ + return header_.CodeManagerTable.VirtualAddress; +} + +//Returns size of code manager table +uint32_t basic_dotnet_info::get_size_of_code_manager_table() const +{ + return header_.CodeManagerTable.Size; +} + +//Returns RVA of VTable fixups +uint32_t basic_dotnet_info::get_rva_of_vtable_fixups() const +{ + return header_.VTableFixups.VirtualAddress; +} + +//Returns size of VTable fixups +uint32_t basic_dotnet_info::get_size_of_vtable_fixups() const +{ + return header_.VTableFixups.Size; +} + +//Returns RVA of export address table jumps +uint32_t basic_dotnet_info::get_rva_of_export_address_table_jumps() const +{ + return header_.ExportAddressTableJumps.VirtualAddress; +} + +//Returns size of export address table jumps +uint32_t basic_dotnet_info::get_size_of_export_address_table_jumps() const +{ + return header_.ExportAddressTableJumps.Size; +} + +//Returns RVA of managed native header +//(precompiled header info, usually set to zero, for internal use) +uint32_t basic_dotnet_info::get_rva_of_managed_native_header() const +{ + return header_.ManagedNativeHeader.VirtualAddress; +} + +//Returns size of managed native header +//(precompiled header info, usually set to zero, for internal use) +uint32_t basic_dotnet_info::get_size_of_managed_native_header() const +{ + return header_.ManagedNativeHeader.Size; +} + +//Returns basic .NET information +//If image is not native, throws an exception +const basic_dotnet_info get_basic_dotnet_info(const pe_base& pe) +{ + //If there's no debug directory, return empty list + if(!pe.is_dotnet()) + throw pe_exception("Image does not have managed code", pe_exception::image_does_not_have_managed_code); + + //Return basic .NET information + return basic_dotnet_info(pe.section_data_from_rva<image_cor20_header>(pe.get_directory_rva(image_directory_entry_com_descriptor), section_data_virtual, true)); +} +} diff --git a/tools/pe_bliss/pe_dotnet.h b/tools/pe_bliss/pe_dotnet.h new file mode 100644 index 0000000000..96b0ac7d0a --- /dev/null +++ b/tools/pe_bliss/pe_dotnet.h @@ -0,0 +1,97 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include "pe_structures.h" +#include "pe_base.h" + +namespace pe_bliss +{ +//Class representing basic .NET header information +class basic_dotnet_info +{ +public: + //Default constructor + basic_dotnet_info(); + //Constructor from data + explicit basic_dotnet_info(const pe_win::image_cor20_header& header); + + //Returns major runtime version + uint16_t get_major_runtime_version() const; + //Returns minor runtime version + uint16_t get_minor_runtime_version() const; + + //Returns RVA of metadata (symbol table and startup information) + uint32_t get_rva_of_metadata() const; + //Returns size of metadata (symbol table and startup information) + uint32_t get_size_of_metadata() const; + + //Returns flags + uint32_t get_flags() const; + + //Returns true if entry point is native + bool is_native_entry_point() const; + //Returns true if 32 bit required + bool is_32bit_required() const; + //Returns true if image is IL library + bool is_il_library() const; + //Returns true if image uses IL only + bool is_il_only() const; + + //Returns entry point RVA (if entry point is native) + //Returns entry point managed token (if entry point is managed) + uint32_t get_entry_point_rva_or_token() const; + + //Returns RVA of managed resources + uint32_t get_rva_of_resources() const; + //Returns size of managed resources + uint32_t get_size_of_resources() const; + //Returns RVA of strong name signature + uint32_t get_rva_of_strong_name_signature() const; + //Returns size of strong name signature + uint32_t get_size_of_strong_name_signature() const; + //Returns RVA of code manager table + uint32_t get_rva_of_code_manager_table() const; + //Returns size of code manager table + uint32_t get_size_of_code_manager_table() const; + //Returns RVA of VTable fixups + uint32_t get_rva_of_vtable_fixups() const; + //Returns size of VTable fixups + uint32_t get_size_of_vtable_fixups() const; + //Returns RVA of export address table jumps + uint32_t get_rva_of_export_address_table_jumps() const; + //Returns size of export address table jumps + uint32_t get_size_of_export_address_table_jumps() const; + //Returns RVA of managed native header + //(precompiled header info, usually set to zero, for internal use) + uint32_t get_rva_of_managed_native_header() const; + //Returns size of managed native header + //(precompiled header info, usually set to zero, for internal use) + uint32_t get_size_of_managed_native_header() const; + +private: + pe_win::image_cor20_header header_; +}; + +//Returns basic .NET information +//If image is not native, throws an exception +const basic_dotnet_info get_basic_dotnet_info(const pe_base& pe); +} diff --git a/tools/pe_bliss/pe_exception.cpp b/tools/pe_bliss/pe_exception.cpp new file mode 100644 index 0000000000..3161f93599 --- /dev/null +++ b/tools/pe_bliss/pe_exception.cpp @@ -0,0 +1,40 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include "pe_exception.h" + +namespace pe_bliss +{ +//PE exception class constructors +pe_exception::pe_exception(const char* text, exception_id id) + :std::runtime_error(text), id_(id) +{} + +pe_exception::pe_exception(const std::string& text, exception_id id) + :std::runtime_error(text), id_(id) +{} + +//Returns exception ID +pe_exception::exception_id pe_exception::get_id() const +{ + return id_; +} +} diff --git a/tools/pe_bliss/pe_exception.h b/tools/pe_bliss/pe_exception.h new file mode 100644 index 0000000000..2b58a95772 --- /dev/null +++ b/tools/pe_bliss/pe_exception.h @@ -0,0 +1,130 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <exception> +#include <stdexcept> + +namespace pe_bliss +{ +//PE exception class +class pe_exception : public std::runtime_error +{ +public: + //Exception IDs + enum exception_id + { + unknown_error, + bad_pe_file, + bad_dos_header, + image_nt_headers_not_found, + error_reading_image_nt_headers, + error_reading_data_directories, + error_reading_file, + pe_signature_incorrect, + incorrect_number_of_rva_and_sizes, + error_changing_section_virtual_size, + section_number_incorrect, + section_table_incorrect, + incorrect_section_alignment, + incorrect_file_alignment, + incorrect_size_of_image, + incorrect_size_of_headers, + image_section_headers_not_found, + zero_section_sizes, + section_incorrect_addr_or_size, + section_not_found, + image_section_data_not_found, + no_section_found, + image_section_table_incorrect, + directory_does_not_exist, + rva_not_exists, + error_reading_section_header, + error_reading_overlay, + incorrect_address_conversion, + + incorrect_export_directory, + incorrect_import_directory, + incorrect_relocation_directory, + incorrect_tls_directory, + incorrect_config_directory, + incorrect_bound_import_directory, + incorrect_resource_directory, + incorrect_exception_directory, + incorrect_debug_directory, + + resource_directory_entry_error, + resource_directory_entry_not_found, + resource_data_entry_not_found, + resource_incorrect_bitmap, + resource_incorrect_icon, + resource_incorrect_cursor, + resource_incorrect_string_table, + resource_string_not_found, + resource_incorrect_message_table, + resource_incorrect_version_info, + + advanced_debug_information_request_error, + image_does_not_have_managed_code, + + section_is_empty, + data_is_empty, + stream_is_bad, + + section_is_not_attached, + insufficient_space, + + cannot_rebase_relocations, + + exports_list_is_empty, + duplicate_exported_function_ordinal, + duplicate_exported_function_name, + + version_info_string_does_not_exist, + + no_more_sections_can_be_added, + + no_icon_group_found, + no_cursor_group_found, + + encoding_convertion_error, + + error_expanding_section, + + cannot_rebuild_image + }; + +public: + //Class constructors + explicit pe_exception(const char* text, exception_id id = unknown_error); + explicit pe_exception(const std::string& text, exception_id id = unknown_error); + + //Returns exception ID from exception_id enumeration + exception_id get_id() const; + + //Destructor + virtual ~pe_exception() throw() + {} + +private: + exception_id id_; +}; +} diff --git a/tools/pe_bliss/pe_exception_directory.cpp b/tools/pe_bliss/pe_exception_directory.cpp new file mode 100644 index 0000000000..1813f02021 --- /dev/null +++ b/tools/pe_bliss/pe_exception_directory.cpp @@ -0,0 +1,177 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include "pe_exception_directory.h" + +namespace pe_bliss +{ +using namespace pe_win; + +//EXCEPTION DIRECTORY (exists on PE+ only) +//Default constructor +exception_entry::exception_entry() + :begin_address_(0), end_address_(0), unwind_info_address_(0), + unwind_info_version_(0), + flags_(0), + size_of_prolog_(0), + count_of_codes_(0), + frame_register_(0), + frame_offset_(0) +{} + +//Constructor from data +exception_entry::exception_entry(const image_runtime_function_entry& entry, const unwind_info& unwind_info) + :begin_address_(entry.BeginAddress), end_address_(entry.EndAddress), unwind_info_address_(entry.UnwindInfoAddress), + unwind_info_version_(unwind_info.Version), + flags_(unwind_info.Flags), + size_of_prolog_(unwind_info.SizeOfProlog), + count_of_codes_(unwind_info.CountOfCodes), + frame_register_(unwind_info.FrameRegister), + frame_offset_(unwind_info.FrameOffset) +{} + +//Returns starting address of function, affected by exception unwinding +uint32_t exception_entry::get_begin_address() const +{ + return begin_address_; +} + +//Returns ending address of function, affected by exception unwinding +uint32_t exception_entry::get_end_address() const +{ + return end_address_; +} + +//Returns unwind info address +uint32_t exception_entry::get_unwind_info_address() const +{ + return unwind_info_address_; +} + +//Returns UNWIND_INFO structure version +uint8_t exception_entry::get_unwind_info_version() const +{ + return unwind_info_version_; +} + +//Returns unwind info flags +uint8_t exception_entry::get_flags() const +{ + return flags_; +} + +//The function has an exception handler that should be called +//when looking for functions that need to examine exceptions +bool exception_entry::has_exception_handler() const +{ + return (flags_ & unw_flag_ehandler) ? true : false; +} + +//The function has a termination handler that should be called +//when unwinding an exception +bool exception_entry::has_termination_handler() const +{ + return (flags_ & unw_flag_uhandler) ? true : false; +} + +//The unwind info structure is not the primary one for the procedure +bool exception_entry::is_chaininfo() const +{ + return (flags_ & unw_flag_chaininfo) ? true : false; +} + +//Returns size of function prolog +uint8_t exception_entry::get_size_of_prolog() const +{ + return size_of_prolog_; +} + +//Returns number of unwind slots +uint8_t exception_entry::get_number_of_unwind_slots() const +{ + return count_of_codes_; +} + +//If the function uses frame pointer +bool exception_entry::uses_frame_pointer() const +{ + return frame_register_ != 0; +} + +//Number of the nonvolatile register used as the frame pointer, +//using the same encoding for the operation info field of UNWIND_CODE nodes +uint8_t exception_entry::get_frame_pointer_register_number() const +{ + return frame_register_; +} + +//The scaled offset from RSP that is applied to the FP reg when it is established. +//The actual FP reg is set to RSP + 16 * this number, allowing offsets from 0 to 240 +uint8_t exception_entry::get_scaled_rsp_offset() const +{ + return frame_offset_; +} + +//Returns exception directory data (exists on PE+ only) +//Unwind opcodes are not listed, because their format and list are subject to change +const exception_entry_list get_exception_directory_data(const pe_base& pe) +{ + exception_entry_list ret; + + //If image doesn't have exception directory, return empty list + if(!pe.has_exception_directory()) + return ret; + + //Check the length in bytes of the section containing exception directory + if(pe.section_data_length_from_rva(pe.get_directory_rva(image_directory_entry_exception), pe.get_directory_rva(image_directory_entry_exception), section_data_virtual, true) + < sizeof(image_runtime_function_entry)) + throw pe_exception("Incorrect exception directory", pe_exception::incorrect_exception_directory); + + unsigned long current_pos = pe.get_directory_rva(image_directory_entry_exception); + + //Check if structures are DWORD-aligned + if(current_pos % sizeof(uint32_t)) + throw pe_exception("Incorrect exception directory", pe_exception::incorrect_exception_directory); + + //First IMAGE_RUNTIME_FUNCTION_ENTRY table + image_runtime_function_entry exception_table = pe.section_data_from_rva<image_runtime_function_entry>(current_pos, section_data_virtual, true); + + //todo: virtual addresses BeginAddress and EndAddress are not checked to be inside image + while(exception_table.BeginAddress) + { + //Check addresses + if(exception_table.BeginAddress > exception_table.EndAddress) + throw pe_exception("Incorrect exception directory", pe_exception::incorrect_exception_directory); + + //Get unwind information + unwind_info info = pe.section_data_from_rva<unwind_info>(exception_table.UnwindInfoAddress, section_data_virtual, true); + + //Create exception entry and save it + ret.push_back(exception_entry(exception_table, info)); + + //Go to next exception entry + current_pos += sizeof(image_runtime_function_entry); + exception_table = pe.section_data_from_rva<image_runtime_function_entry>(current_pos, section_data_virtual, true); + } + + return ret; +} +} diff --git a/tools/pe_bliss/pe_exception_directory.h b/tools/pe_bliss/pe_exception_directory.h new file mode 100644 index 0000000000..6f4fc2298b --- /dev/null +++ b/tools/pe_bliss/pe_exception_directory.h @@ -0,0 +1,88 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <vector> +#include "pe_structures.h" +#include "pe_base.h" + +namespace pe_bliss +{ +//Class representing exception directory entry +class exception_entry +{ +public: + //Default constructor + exception_entry(); + //Constructor from data + exception_entry(const pe_win::image_runtime_function_entry& entry, const pe_win::unwind_info& unwind_info); + + //Returns starting address of function, affected by exception unwinding + uint32_t get_begin_address() const; + //Returns ending address of function, affected by exception unwinding + uint32_t get_end_address() const; + //Returns unwind info address + uint32_t get_unwind_info_address() const; + + //Returns UNWIND_INFO structure version + uint8_t get_unwind_info_version() const; + + //Returns unwind info flags + uint8_t get_flags() const; + //The function has an exception handler that should be called + //when looking for functions that need to examine exceptions + bool has_exception_handler() const; + //The function has a termination handler that should be called + //when unwinding an exception + bool has_termination_handler() const; + //The unwind info structure is not the primary one for the procedure + bool is_chaininfo() const; + + //Returns size of function prolog + uint8_t get_size_of_prolog() const; + + //Returns number of unwind slots + uint8_t get_number_of_unwind_slots() const; + + //If the function uses frame pointer + bool uses_frame_pointer() const; + //Number of the nonvolatile register used as the frame pointer, + //using the same encoding for the operation info field of UNWIND_CODE nodes + uint8_t get_frame_pointer_register_number() const; + //The scaled offset from RSP that is applied to the FP reg when it is established. + //The actual FP reg is set to RSP + 16 * this number, allowing offsets from 0 to 240 + uint8_t get_scaled_rsp_offset() const; + +private: + uint32_t begin_address_, end_address_, unwind_info_address_; + uint8_t unwind_info_version_; + uint8_t flags_; + uint8_t size_of_prolog_; + uint8_t count_of_codes_; + uint8_t frame_register_, frame_offset_; +}; + +typedef std::vector<exception_entry> exception_entry_list; + +//Returns exception directory data (exists on PE+ only) +//Unwind opcodes are not listed, because their format and list are subject to change +const exception_entry_list get_exception_directory_data(const pe_base& pe); +} diff --git a/tools/pe_bliss/pe_exports.cpp b/tools/pe_bliss/pe_exports.cpp new file mode 100644 index 0000000000..c2ad895554 --- /dev/null +++ b/tools/pe_bliss/pe_exports.cpp @@ -0,0 +1,700 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <set> +#include <algorithm> +#include <string.h> +#include "pe_exports.h" +#include "utils.h" + +namespace pe_bliss +{ +using namespace pe_win; + +//EXPORTS +//Default constructor +exported_function::exported_function() + :ordinal_(0), rva_(0), has_name_(false), name_ordinal_(0), forward_(false) +{} + +//Returns ordinal of function (actually, ordinal = hint + ordinal base) +uint16_t exported_function::get_ordinal() const +{ + return ordinal_; +} + +//Returns RVA of function +uint32_t exported_function::get_rva() const +{ + return rva_; +} + +//Returns name of function +const std::string& exported_function::get_name() const +{ + return name_; +} + +//Returns true if function has name and name ordinal +bool exported_function::has_name() const +{ + return has_name_; +} + +//Returns name ordinal of function +uint16_t exported_function::get_name_ordinal() const +{ + return name_ordinal_; +} + +//Returns true if function is forwarded to other library +bool exported_function::is_forwarded() const +{ + return forward_; +} + +//Returns the name of forwarded function +const std::string& exported_function::get_forwarded_name() const +{ + return forward_name_; +} + +//Sets ordinal of function +void exported_function::set_ordinal(uint16_t ordinal) +{ + ordinal_ = ordinal; +} + +//Sets RVA of function +void exported_function::set_rva(uint32_t rva) +{ + rva_ = rva; +} + +//Sets name of function (or clears it, if empty name is passed) +void exported_function::set_name(const std::string& name) +{ + name_ = name; + has_name_ = !name.empty(); +} + +//Sets name ordinal +void exported_function::set_name_ordinal(uint16_t name_ordinal) +{ + name_ordinal_ = name_ordinal; +} + +//Sets forwarded function name (or clears it, if empty name is passed) +void exported_function::set_forwarded_name(const std::string& name) +{ + forward_name_ = name; + forward_ = !name.empty(); +} + +//Default constructor +export_info::export_info() + :characteristics_(0), + timestamp_(0), + major_version_(0), + minor_version_(0), + ordinal_base_(0), + number_of_functions_(0), + number_of_names_(0), + address_of_functions_(0), + address_of_names_(0), + address_of_name_ordinals_(0) +{} + +//Returns characteristics +uint32_t export_info::get_characteristics() const +{ + return characteristics_; +} + +//Returns timestamp +uint32_t export_info::get_timestamp() const +{ + return timestamp_; +} + +//Returns major version +uint16_t export_info::get_major_version() const +{ + return major_version_; +} + +//Returns minor version +uint16_t export_info::get_minor_version() const +{ + return minor_version_; +} + +//Returns DLL name +const std::string& export_info::get_name() const +{ + return name_; +} + +//Returns ordinal base +uint32_t export_info::get_ordinal_base() const +{ + return ordinal_base_; +} + +//Returns number of functions +uint32_t export_info::get_number_of_functions() const +{ + return number_of_functions_; +} + +//Returns number of function names +uint32_t export_info::get_number_of_names() const +{ + return number_of_names_; +} + +//Returns RVA of function address table +uint32_t export_info::get_rva_of_functions() const +{ + return address_of_functions_; +} + +//Returns RVA of function name address table +uint32_t export_info::get_rva_of_names() const +{ + return address_of_names_; +} + +//Returns RVA of name ordinals table +uint32_t export_info::get_rva_of_name_ordinals() const +{ + return address_of_name_ordinals_; +} + +//Sets characteristics +void export_info::set_characteristics(uint32_t characteristics) +{ + characteristics_ = characteristics; +} + +//Sets timestamp +void export_info::set_timestamp(uint32_t timestamp) +{ + timestamp_ = timestamp; +} + +//Sets major version +void export_info::set_major_version(uint16_t major_version) +{ + major_version_ = major_version; +} + +//Sets minor version +void export_info::set_minor_version(uint16_t minor_version) +{ + minor_version_ = minor_version; +} + +//Sets DLL name +void export_info::set_name(const std::string& name) +{ + name_ = name; +} + +//Sets ordinal base +void export_info::set_ordinal_base(uint32_t ordinal_base) +{ + ordinal_base_ = ordinal_base; +} + +//Sets number of functions +void export_info::set_number_of_functions(uint32_t number_of_functions) +{ + number_of_functions_ = number_of_functions; +} + +//Sets number of function names +void export_info::set_number_of_names(uint32_t number_of_names) +{ + number_of_names_ = number_of_names; +} + +//Sets RVA of function address table +void export_info::set_rva_of_functions(uint32_t rva_of_functions) +{ + address_of_functions_ = rva_of_functions; +} + +//Sets RVA of function name address table +void export_info::set_rva_of_names(uint32_t rva_of_names) +{ + address_of_names_ = rva_of_names; +} + +//Sets RVA of name ordinals table +void export_info::set_rva_of_name_ordinals(uint32_t rva_of_name_ordinals) +{ + address_of_name_ordinals_ = rva_of_name_ordinals; +} + +const exported_functions_list get_exported_functions(const pe_base& pe, export_info* info); + +//Returns array of exported functions +const exported_functions_list get_exported_functions(const pe_base& pe) +{ + return get_exported_functions(pe, 0); +} + +//Returns array of exported functions and information about export +const exported_functions_list get_exported_functions(const pe_base& pe, export_info& info) +{ + return get_exported_functions(pe, &info); +} + +//Helper: sorts exported function list by ordinals +struct ordinal_sorter +{ +public: + bool operator()(const exported_function& func1, const exported_function& func2) const; +}; + +//Returns array of exported functions and information about export (if info != 0) +const exported_functions_list get_exported_functions(const pe_base& pe, export_info* info) +{ + //Returned exported functions info array + std::vector<exported_function> ret; + + if(pe.has_exports()) + { + //Check the length in bytes of the section containing export directory + if(pe.section_data_length_from_rva(pe.get_directory_rva(image_directory_entry_export), + pe.get_directory_rva(image_directory_entry_export), section_data_virtual, true) + < sizeof(image_export_directory)) + throw pe_exception("Incorrect export directory", pe_exception::incorrect_export_directory); + + image_export_directory exports = pe.section_data_from_rva<image_export_directory>(pe.get_directory_rva(image_directory_entry_export), section_data_virtual, true); + + unsigned long max_name_length; + + if(info) + { + //Save some export info data + info->set_characteristics(exports.Characteristics); + info->set_major_version(exports.MajorVersion); + info->set_minor_version(exports.MinorVersion); + + //Get byte count that we have for dll name + if((max_name_length = pe.section_data_length_from_rva(exports.Name, exports.Name, section_data_virtual, true)) < 2) + throw pe_exception("Incorrect export directory", pe_exception::incorrect_export_directory); + + //Get dll name pointer + const char* dll_name = pe.section_data_from_rva(exports.Name, section_data_virtual, true); + + //Check for null-termination + if(!pe_utils::is_null_terminated(dll_name, max_name_length)) + throw pe_exception("Incorrect export directory", pe_exception::incorrect_export_directory); + + //Save the rest of export information data + info->set_name(dll_name); + info->set_number_of_functions(exports.NumberOfFunctions); + info->set_number_of_names(exports.NumberOfNames); + info->set_ordinal_base(exports.Base); + info->set_rva_of_functions(exports.AddressOfFunctions); + info->set_rva_of_names(exports.AddressOfNames); + info->set_rva_of_name_ordinals(exports.AddressOfNameOrdinals); + info->set_timestamp(exports.TimeDateStamp); + } + + if(!exports.NumberOfFunctions) + return ret; + + //Check IMAGE_EXPORT_DIRECTORY fields + if(exports.NumberOfNames > exports.NumberOfFunctions) + throw pe_exception("Incorrect export directory", pe_exception::incorrect_export_directory); + + //Check some export directory fields + if((!exports.AddressOfNameOrdinals && exports.AddressOfNames) || + (exports.AddressOfNameOrdinals && !exports.AddressOfNames) || + !exports.AddressOfFunctions + || exports.NumberOfFunctions >= pe_utils::max_dword / sizeof(uint32_t) + || exports.NumberOfNames > pe_utils::max_dword / sizeof(uint32_t) + || !pe_utils::is_sum_safe(exports.AddressOfFunctions, exports.NumberOfFunctions * sizeof(uint32_t)) + || !pe_utils::is_sum_safe(exports.AddressOfNames, exports.NumberOfNames * sizeof(uint32_t)) + || !pe_utils::is_sum_safe(exports.AddressOfNameOrdinals, exports.NumberOfFunctions * sizeof(uint32_t)) + || !pe_utils::is_sum_safe(pe.get_directory_rva(image_directory_entry_export), pe.get_directory_size(image_directory_entry_export))) + throw pe_exception("Incorrect export directory", pe_exception::incorrect_export_directory); + + //Check if it is enough bytes to hold AddressOfFunctions table + if(pe.section_data_length_from_rva(exports.AddressOfFunctions, exports.AddressOfFunctions, section_data_virtual, true) + < exports.NumberOfFunctions * sizeof(uint32_t)) + throw pe_exception("Incorrect export directory", pe_exception::incorrect_export_directory); + + if(exports.AddressOfNames) + { + //Check if it is enough bytes to hold name and ordinal tables + if(pe.section_data_length_from_rva(exports.AddressOfNameOrdinals, exports.AddressOfNameOrdinals, section_data_virtual, true) + < exports.NumberOfNames * sizeof(uint16_t)) + throw pe_exception("Incorrect export directory", pe_exception::incorrect_export_directory); + + if(pe.section_data_length_from_rva(exports.AddressOfNames, exports.AddressOfNames, section_data_virtual, true) + < exports.NumberOfNames * sizeof(uint32_t)) + throw pe_exception("Incorrect export directory", pe_exception::incorrect_export_directory); + } + + for(uint32_t ordinal = 0; ordinal < exports.NumberOfFunctions; ordinal++) + { + //Get function address + //Sum and multiplication are safe (checked above) + uint32_t rva = pe.section_data_from_rva<uint32_t>(exports.AddressOfFunctions + ordinal * sizeof(uint32_t), section_data_virtual, true); + + //If we have a skip + if(!rva) + continue; + + exported_function func; + func.set_rva(rva); + + if(!pe_utils::is_sum_safe(exports.Base, ordinal) || exports.Base + ordinal > pe_utils::max_word) + throw pe_exception("Incorrect export directory", pe_exception::incorrect_export_directory); + + func.set_ordinal(static_cast<uint16_t>(ordinal + exports.Base)); + + //Scan for function name ordinal + for(uint32_t i = 0; i < exports.NumberOfNames; i++) + { + uint16_t ordinal2 = pe.section_data_from_rva<uint16_t>(exports.AddressOfNameOrdinals + i * sizeof(uint16_t), section_data_virtual, true); + + //If function has name (and name ordinal) + if(ordinal == ordinal2) + { + //Get function name + //Sum and multiplication are safe (checked above) + uint32_t function_name_rva = pe.section_data_from_rva<uint32_t>(exports.AddressOfNames + i * sizeof(uint32_t), section_data_virtual, true); + + //Get byte count that we have for function name + if((max_name_length = pe.section_data_length_from_rva(function_name_rva, function_name_rva, section_data_virtual, true)) < 2) + throw pe_exception("Incorrect export directory", pe_exception::incorrect_export_directory); + + //Get function name pointer + const char* func_name = pe.section_data_from_rva(function_name_rva, section_data_virtual, true); + + //Check for null-termination + if(!pe_utils::is_null_terminated(func_name, max_name_length)) + throw pe_exception("Incorrect export directory", pe_exception::incorrect_export_directory); + + //Save function info + func.set_name(func_name); + func.set_name_ordinal(ordinal2); + + //If the function is just a redirect, save its name + if(rva >= pe.get_directory_rva(image_directory_entry_export) + sizeof(image_directory_entry_export) && + rva < pe.get_directory_rva(image_directory_entry_export) + pe.get_directory_size(image_directory_entry_export)) + { + if((max_name_length = pe.section_data_length_from_rva(rva, rva, section_data_virtual, true)) < 2) + throw pe_exception("Incorrect export directory", pe_exception::incorrect_export_directory); + + //Get forwarded function name pointer + const char* forwarded_func_name = pe.section_data_from_rva(rva, section_data_virtual, true); + + //Check for null-termination + if(!pe_utils::is_null_terminated(forwarded_func_name, max_name_length)) + throw pe_exception("Incorrect export directory", pe_exception::incorrect_export_directory); + + //Set the name of forwarded function + func.set_forwarded_name(forwarded_func_name); + } + + break; + } + } + + //Add function info to output array + ret.push_back(func); + } + } + + return ret; +} + +//Helper export functions +//Returns pair: <ordinal base for supplied functions; maximum ordinal value for supplied functions> +const std::pair<uint16_t, uint16_t> get_export_ordinal_limits(const exported_functions_list& exports) +{ + if(exports.empty()) + return std::make_pair(0, 0); + + uint16_t max_ordinal = 0; //Maximum ordinal number + uint16_t ordinal_base = pe_utils::max_word; //Minimum ordinal value + for(exported_functions_list::const_iterator it = exports.begin(); it != exports.end(); ++it) + { + const exported_function& func = (*it); + + //Calculate maximum and minimum ordinal numbers + max_ordinal = std::max<uint16_t>(max_ordinal, func.get_ordinal()); + ordinal_base = std::min<uint16_t>(ordinal_base, func.get_ordinal()); + } + + return std::make_pair(ordinal_base, max_ordinal); +} + +//Checks if exported function name already exists +bool exported_name_exists(const std::string& function_name, const exported_functions_list& exports) +{ + for(exported_functions_list::const_iterator it = exports.begin(); it != exports.end(); ++it) + { + if((*it).has_name() && (*it).get_name() == function_name) + return true; + } + + return false; +} + +//Checks if exported function name already exists +bool exported_ordinal_exists(uint16_t ordinal, const exported_functions_list& exports) +{ + for(exported_functions_list::const_iterator it = exports.begin(); it != exports.end(); ++it) + { + if((*it).get_ordinal() == ordinal) + return true; + } + + return false; +} + +//Helper: sorts exported function list by ordinals +bool ordinal_sorter::operator()(const exported_function& func1, const exported_function& func2) const +{ + return func1.get_ordinal() < func2.get_ordinal(); +} + +//Export directory rebuilder +//info - export information +//exported_functions_list - list of exported functions +//exports_section - section where export directory will be placed (must be attached to PE image) +//offset_from_section_start - offset from exports_section raw data start +//save_to_pe_headers - if true, new export directory information will be saved to PE image headers +//auto_strip_last_section - if true and exports are placed in the last section, it will be automatically stripped +//number_of_functions and number_of_names parameters don't matter in "info" when rebuilding, they're calculated independently +//characteristics, major_version, minor_version, timestamp and name are the only used members of "info" structure +//Returns new export directory information +//exported_functions_list is copied intentionally to be sorted by ordinal values later +//Name ordinals in exported function don't matter, they will be recalculated +const image_directory rebuild_exports(pe_base& pe, const export_info& info, exported_functions_list exports, section& exports_section, uint32_t offset_from_section_start, bool save_to_pe_header, bool auto_strip_last_section) +{ + //Check that exports_section is attached to this PE image + if(!pe.section_attached(exports_section)) + throw pe_exception("Exports section must be attached to PE file", pe_exception::section_is_not_attached); + + //Needed space for strings + uint32_t needed_size_for_strings = static_cast<uint32_t>(info.get_name().length() + 1); + uint32_t number_of_names = 0; //Number of named functions + uint32_t max_ordinal = 0; //Maximum ordinal number + uint32_t ordinal_base = static_cast<uint32_t>(-1); //Minimum ordinal value + + if(exports.empty()) + ordinal_base = info.get_ordinal_base(); + + uint32_t needed_size_for_function_names = 0; //Needed space for function name strings + uint32_t needed_size_for_function_forwards = 0; //Needed space for function forwards names + + //List all exported functions + //Calculate needed size for function list + { + //Also check that there're no duplicate names and ordinals + std::set<std::string> used_function_names; + std::set<uint16_t> used_function_ordinals; + + for(exported_functions_list::const_iterator it = exports.begin(); it != exports.end(); ++it) + { + const exported_function& func = (*it); + //Calculate maximum and minimum ordinal numbers + max_ordinal = std::max<uint32_t>(max_ordinal, func.get_ordinal()); + ordinal_base = std::min<uint32_t>(ordinal_base, func.get_ordinal()); + + //Check if ordinal is unique + if(!used_function_ordinals.insert(func.get_ordinal()).second) + throw pe_exception("Duplicate exported function ordinal", pe_exception::duplicate_exported_function_ordinal); + + if(func.has_name()) + { + //If function is named + ++number_of_names; + needed_size_for_function_names += static_cast<uint32_t>(func.get_name().length() + 1); + + //Check if it's name and name ordinal are unique + if(!used_function_names.insert(func.get_name()).second) + throw pe_exception("Duplicate exported function name", pe_exception::duplicate_exported_function_name); + } + + //If function is forwarded to another DLL + if(func.is_forwarded()) + needed_size_for_function_forwards += static_cast<uint32_t>(func.get_forwarded_name().length() + 1); + } + } + + //Sort functions by ordinal value + std::sort(exports.begin(), exports.end(), ordinal_sorter()); + + //Calculate needed space for different things... + needed_size_for_strings += needed_size_for_function_names; + needed_size_for_strings += needed_size_for_function_forwards; + uint32_t needed_size_for_function_name_ordinals = number_of_names * sizeof(uint16_t); + uint32_t needed_size_for_function_name_rvas = number_of_names * sizeof(uint32_t); + uint32_t needed_size_for_function_addresses = (max_ordinal - ordinal_base + 1) * sizeof(uint32_t); + + //Export directory header will be placed first + uint32_t directory_pos = pe_utils::align_up(offset_from_section_start, sizeof(uint32_t)); + + uint32_t needed_size = sizeof(image_export_directory); //Calculate needed size for export tables and strings + //sizeof(IMAGE_EXPORT_DIRECTORY) = export directory header + + //Total needed space... + needed_size += needed_size_for_function_name_ordinals; //For list of names ordinals + needed_size += needed_size_for_function_addresses; //For function RVAs + needed_size += needed_size_for_strings; //For all strings + needed_size += needed_size_for_function_name_rvas; //For function name strings RVAs + + //Check if exports_section is last one. If it's not, check if there's enough place for exports data + if(&exports_section != &*(pe.get_image_sections().end() - 1) && + (exports_section.empty() || pe_utils::align_up(exports_section.get_size_of_raw_data(), pe.get_file_alignment()) < needed_size + directory_pos)) + throw pe_exception("Insufficient space for export directory", pe_exception::insufficient_space); + + std::string& raw_data = exports_section.get_raw_data(); + + //This will be done only if exports_section is the last section of image or for section with unaligned raw length of data + if(raw_data.length() < needed_size + directory_pos) + raw_data.resize(needed_size + directory_pos); //Expand section raw data + + //Library name will be placed after it + uint32_t current_pos_of_function_names = static_cast<uint32_t>(info.get_name().length() + 1 + directory_pos + sizeof(image_export_directory)); + //Next - function names + uint32_t current_pos_of_function_name_ordinals = current_pos_of_function_names + needed_size_for_function_names; + //Next - function name ordinals + uint32_t current_pos_of_function_forwards = current_pos_of_function_name_ordinals + needed_size_for_function_name_ordinals; + //Finally - function addresses + uint32_t current_pos_of_function_addresses = current_pos_of_function_forwards + needed_size_for_function_forwards; + //Next - function names RVAs + uint32_t current_pos_of_function_names_rvas = current_pos_of_function_addresses + needed_size_for_function_addresses; + + { + //Create export directory and fill it + image_export_directory dir = {0}; + dir.Characteristics = info.get_characteristics(); + dir.MajorVersion = info.get_major_version(); + dir.MinorVersion = info.get_minor_version(); + dir.TimeDateStamp = info.get_timestamp(); + dir.NumberOfFunctions = max_ordinal - ordinal_base + 1; + dir.NumberOfNames = number_of_names; + dir.Base = ordinal_base; + dir.AddressOfFunctions = pe.rva_from_section_offset(exports_section, current_pos_of_function_addresses); + dir.AddressOfNameOrdinals = pe.rva_from_section_offset(exports_section, current_pos_of_function_name_ordinals); + dir.AddressOfNames = pe.rva_from_section_offset(exports_section, current_pos_of_function_names_rvas); + dir.Name = pe.rva_from_section_offset(exports_section, directory_pos + sizeof(image_export_directory)); + + //Save it + memcpy(&raw_data[directory_pos], &dir, sizeof(dir)); + } + + //Sve library name + memcpy(&raw_data[directory_pos + sizeof(image_export_directory)], info.get_name().c_str(), info.get_name().length() + 1); + + //A map to sort function names alphabetically + typedef std::map<std::string, uint16_t> funclist; //function name; function name ordinal + funclist funcs; + + uint32_t last_ordinal = ordinal_base; + //Enumerate all exported functions + for(exported_functions_list::const_iterator it = exports.begin(); it != exports.end(); ++it) + { + const exported_function& func = (*it); + + //If we're skipping some ordinals... + if(func.get_ordinal() > last_ordinal) + { + //Fill this function RVAs data with zeros + uint32_t len = sizeof(uint32_t) * (func.get_ordinal() - last_ordinal - 1); + if(len) + { + memset(&raw_data[current_pos_of_function_addresses], 0, len); + current_pos_of_function_addresses += len; + } + + //Save last encountered ordinal + last_ordinal = func.get_ordinal(); + } + + //If function is named, save its name ordinal and name in sorted alphabetically order + if(func.has_name()) + funcs.insert(std::make_pair(func.get_name(), static_cast<uint16_t>(func.get_ordinal() - ordinal_base))); //Calculate name ordinal + + //If function is forwarded to another DLL + if(func.is_forwarded()) + { + //Write its forwarded name and its RVA + uint32_t function_rva = pe.rva_from_section_offset(exports_section, current_pos_of_function_forwards); + memcpy(&raw_data[current_pos_of_function_addresses], &function_rva, sizeof(function_rva)); + current_pos_of_function_addresses += sizeof(function_rva); + + memcpy(&raw_data[current_pos_of_function_forwards], func.get_forwarded_name().c_str(), func.get_forwarded_name().length() + 1); + current_pos_of_function_forwards += static_cast<uint32_t>(func.get_forwarded_name().length() + 1); + } + else + { + //Write actual function RVA + uint32_t function_rva = func.get_rva(); + memcpy(&raw_data[current_pos_of_function_addresses], &function_rva, sizeof(function_rva)); + current_pos_of_function_addresses += sizeof(function_rva); + } + } + + //Enumerate sorted function names + for(funclist::const_iterator it = funcs.begin(); it != funcs.end(); ++it) + { + //Save function name RVA + uint32_t function_name_rva = pe.rva_from_section_offset(exports_section, current_pos_of_function_names); + memcpy(&raw_data[current_pos_of_function_names_rvas], &function_name_rva, sizeof(function_name_rva)); + current_pos_of_function_names_rvas += sizeof(function_name_rva); + + //Save function name + memcpy(&raw_data[current_pos_of_function_names], (*it).first.c_str(), (*it).first.length() + 1); + current_pos_of_function_names += static_cast<uint32_t>((*it).first.length() + 1); + + //Save function name ordinal + uint16_t name_ordinal = (*it).second; + memcpy(&raw_data[current_pos_of_function_name_ordinals], &name_ordinal, sizeof(name_ordinal)); + current_pos_of_function_name_ordinals += sizeof(name_ordinal); + } + + //Adjust section raw and virtual sizes + pe.recalculate_section_sizes(exports_section, auto_strip_last_section); + + image_directory ret(pe.rva_from_section_offset(exports_section, directory_pos), needed_size); + + //If auto-rewrite of PE headers is required + if(save_to_pe_header) + { + pe.set_directory_rva(image_directory_entry_export, ret.get_rva()); + pe.set_directory_size(image_directory_entry_export, ret.get_size()); + } + + return ret; +} +} diff --git a/tools/pe_bliss/pe_exports.h b/tools/pe_bliss/pe_exports.h new file mode 100644 index 0000000000..127cf86ed6 --- /dev/null +++ b/tools/pe_bliss/pe_exports.h @@ -0,0 +1,184 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <vector> +#include <string> +#include "pe_structures.h" +#include "pe_base.h" +#include "pe_directory.h" + +namespace pe_bliss +{ +//Class representing exported function +class exported_function +{ +public: + //Default constructor + exported_function(); + + //Returns ordinal of function (actually, ordinal = hint + ordinal base) + uint16_t get_ordinal() const; + + //Returns RVA of function + uint32_t get_rva() const; + + //Returns true if function has name and name ordinal + bool has_name() const; + //Returns name of function + const std::string& get_name() const; + //Returns name ordinal of function + uint16_t get_name_ordinal() const; + + //Returns true if function is forwarded to other library + bool is_forwarded() const; + //Returns the name of forwarded function + const std::string& get_forwarded_name() const; + +public: //Setters do not change everything inside image, they are used by PE class + //You can also use them to rebuild export directory + + //Sets ordinal of function + void set_ordinal(uint16_t ordinal); + + //Sets RVA of function + void set_rva(uint32_t rva); + + //Sets name of function (or clears it, if empty name is passed) + void set_name(const std::string& name); + //Sets name ordinal + void set_name_ordinal(uint16_t name_ordinal); + + //Sets forwarded function name (or clears it, if empty name is passed) + void set_forwarded_name(const std::string& name); + +private: + uint16_t ordinal_; //Function ordinal + uint32_t rva_; //Function RVA + std::string name_; //Function name + bool has_name_; //true == function has name + uint16_t name_ordinal_; //Function name ordinal + bool forward_; //true == function is forwarded + std::string forward_name_; //Name of forwarded function +}; + +//Class representing export information +class export_info +{ +public: + //Default constructor + export_info(); + + //Returns characteristics + uint32_t get_characteristics() const; + //Returns timestamp + uint32_t get_timestamp() const; + //Returns major version + uint16_t get_major_version() const; + //Returns minor version + uint16_t get_minor_version() const; + //Returns DLL name + const std::string& get_name() const; + //Returns ordinal base + uint32_t get_ordinal_base() const; + //Returns number of functions + uint32_t get_number_of_functions() const; + //Returns number of function names + uint32_t get_number_of_names() const; + //Returns RVA of function address table + uint32_t get_rva_of_functions() const; + //Returns RVA of function name address table + uint32_t get_rva_of_names() const; + //Returns RVA of name ordinals table + uint32_t get_rva_of_name_ordinals() const; + +public: //Setters do not change everything inside image, they are used by PE class + //You can also use them to rebuild export directory using rebuild_exports + + //Sets characteristics + void set_characteristics(uint32_t characteristics); + //Sets timestamp + void set_timestamp(uint32_t timestamp); + //Sets major version + void set_major_version(uint16_t major_version); + //Sets minor version + void set_minor_version(uint16_t minor_version); + //Sets DLL name + void set_name(const std::string& name); + //Sets ordinal base + void set_ordinal_base(uint32_t ordinal_base); + //Sets number of functions + void set_number_of_functions(uint32_t number_of_functions); + //Sets number of function names + void set_number_of_names(uint32_t number_of_names); + //Sets RVA of function address table + void set_rva_of_functions(uint32_t rva_of_functions); + //Sets RVA of function name address table + void set_rva_of_names(uint32_t rva_of_names); + //Sets RVA of name ordinals table + void set_rva_of_name_ordinals(uint32_t rva_of_name_ordinals); + +private: + uint32_t characteristics_; + uint32_t timestamp_; + uint16_t major_version_; + uint16_t minor_version_; + std::string name_; + uint32_t ordinal_base_; + uint32_t number_of_functions_; + uint32_t number_of_names_; + uint32_t address_of_functions_; + uint32_t address_of_names_; + uint32_t address_of_name_ordinals_; +}; + +//Exported functions list typedef +typedef std::vector<exported_function> exported_functions_list; + +//Returns array of exported functions +const exported_functions_list get_exported_functions(const pe_base& pe); +//Returns array of exported functions and information about export +const exported_functions_list get_exported_functions(const pe_base& pe, export_info& info); + +//Helper export functions +//Returns pair: <ordinal base for supplied functions; maximum ordinal value for supplied functions> +const std::pair<uint16_t, uint16_t> get_export_ordinal_limits(const exported_functions_list& exports); + +//Checks if exported function name already exists +bool exported_name_exists(const std::string& function_name, const exported_functions_list& exports); + +//Checks if exported function ordinal already exists +bool exported_ordinal_exists(uint16_t ordinal, const exported_functions_list& exports); + +//Export directory rebuilder +//info - export information +//exported_functions_list - list of exported functions +//exports_section - section where export directory will be placed (must be attached to PE image) +//offset_from_section_start - offset from exports_section raw data start +//save_to_pe_headers - if true, new export directory information will be saved to PE image headers +//auto_strip_last_section - if true and exports are placed in the last section, it will be automatically stripped +//number_of_functions and number_of_names parameters don't matter in "info" when rebuilding, they're calculated independently +//characteristics, major_version, minor_version, timestamp and name are the only used members of "info" structure +//Returns new export directory information +//exported_functions_list is copied intentionally to be sorted by ordinal values later +//Name ordinals in exported function don't matter, they will be recalculated +const image_directory rebuild_exports(pe_base& pe, const export_info& info, exported_functions_list exports, section& exports_section, uint32_t offset_from_section_start = 0, bool save_to_pe_header = true, bool auto_strip_last_section = true); +} diff --git a/tools/pe_bliss/pe_factory.cpp b/tools/pe_bliss/pe_factory.cpp new file mode 100644 index 0000000000..f6d8a3e1ed --- /dev/null +++ b/tools/pe_bliss/pe_factory.cpp @@ -0,0 +1,43 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include "pe_factory.h" +#include "pe_properties_generic.h" + +namespace pe_bliss +{ +pe_base pe_factory::create_pe(std::istream& file, bool read_debug_raw_data) +{ + return pe_base::get_pe_type(file) == pe_type_32 + ? pe_base(file, pe_properties_32(), read_debug_raw_data) + : pe_base(file, pe_properties_64(), read_debug_raw_data); +} + +pe_base pe_factory::create_pe(const char* file_path, bool read_debug_raw_data) +{ + std::ifstream pe_file(file_path, std::ios::in | std::ios::binary); + if(!pe_file) + { + throw pe_exception("Error in open file.", pe_exception::stream_is_bad); + } + return pe_factory::create_pe(pe_file,read_debug_raw_data); +} +} diff --git a/tools/pe_bliss/pe_factory.h b/tools/pe_bliss/pe_factory.h new file mode 100644 index 0000000000..60b42d9b71 --- /dev/null +++ b/tools/pe_bliss/pe_factory.h @@ -0,0 +1,39 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <memory> +#include <istream> +#include <fstream> +#include "pe_base.h" + +namespace pe_bliss +{ +class pe_factory +{ +public: + //Creates pe_base class instance from PE or PE+ istream + //If read_bound_import_raw_data, raw bound import data will be read (used to get bound import info) + //If read_debug_raw_data, raw debug data will be read (used to get image debug info) + static pe_base create_pe(std::istream& file, bool read_debug_raw_data = true); + static pe_base create_pe(const char* file_path, bool read_debug_raw_data = true); +}; +} diff --git a/tools/pe_bliss/pe_imports.cpp b/tools/pe_bliss/pe_imports.cpp new file mode 100644 index 0000000000..0a6c01d6c0 --- /dev/null +++ b/tools/pe_bliss/pe_imports.cpp @@ -0,0 +1,777 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <string.h> +#include "pe_imports.h" +#include "pe_properties_generic.h" + +namespace pe_bliss +{ +using namespace pe_win; + +//IMPORTS +//Default constructor +//If set_to_pe_headers = true, IMAGE_DIRECTORY_ENTRY_IMPORT entry will be reset +//to new value after import rebuilding +//If auto_zero_directory_entry_iat = true, IMAGE_DIRECTORY_ENTRY_IAT will be set to zero +//IMAGE_DIRECTORY_ENTRY_IAT is used by loader to temporarily make section, where IMAGE_DIRECTORY_ENTRY_IAT RVA points, writeable +//to be able to modify IAT thunks +import_rebuilder_settings::import_rebuilder_settings(bool set_to_pe_headers, bool auto_zero_directory_entry_iat) + :offset_from_section_start_(0), + build_original_iat_(true), + save_iat_and_original_iat_rvas_(true), + fill_missing_original_iats_(false), + set_to_pe_headers_(set_to_pe_headers), + zero_directory_entry_iat_(auto_zero_directory_entry_iat), + rewrite_iat_and_original_iat_contents_(false), + auto_strip_last_section_(true) +{} + +//Returns offset from section start where import directory data will be placed +uint32_t import_rebuilder_settings::get_offset_from_section_start() const +{ + return offset_from_section_start_; +} + +//Returns true if Original import address table (IAT) will be rebuilt +bool import_rebuilder_settings::build_original_iat() const +{ + return build_original_iat_; +} + +//Returns true if Original import address and import address tables will not be rebuilt, +//works only if import descriptor IAT (and orig.IAT, if present) RVAs are not zero +bool import_rebuilder_settings::save_iat_and_original_iat_rvas() const +{ + return save_iat_and_original_iat_rvas_; +} + +//Returns true if Original import address and import address tables contents will be rewritten +//works only if import descriptor IAT (and orig.IAT, if present) RVAs are not zero +//and save_iat_and_original_iat_rvas is true +bool import_rebuilder_settings::rewrite_iat_and_original_iat_contents() const +{ + return rewrite_iat_and_original_iat_contents_; +} + +//Returns true if original missing IATs will be rebuilt +//(only if IATs are saved) +bool import_rebuilder_settings::fill_missing_original_iats() const +{ + return fill_missing_original_iats_; +} + +//Returns true if PE headers should be updated automatically after rebuilding of imports +bool import_rebuilder_settings::auto_set_to_pe_headers() const +{ + return set_to_pe_headers_; +} + +//Returns true if IMAGE_DIRECTORY_ENTRY_IAT must be zeroed, works only if auto_set_to_pe_headers = true +bool import_rebuilder_settings::zero_directory_entry_iat() const +{ + return zero_directory_entry_iat_; +} + +//Returns true if the last section should be stripped automatically, if imports are inside it +bool import_rebuilder_settings::auto_strip_last_section_enabled() const +{ + return auto_strip_last_section_; +} + +//Sets offset from section start where import directory data will be placed +void import_rebuilder_settings::set_offset_from_section_start(uint32_t offset) +{ + offset_from_section_start_ = offset; +} + +//Sets if Original import address table (IAT) will be rebuilt +void import_rebuilder_settings::build_original_iat(bool enable) +{ + build_original_iat_ = enable; +} + +//Sets if Original import address and import address tables will not be rebuilt, +//works only if import descriptor IAT (and orig.IAT, if present) RVAs are not zero +void import_rebuilder_settings::save_iat_and_original_iat_rvas(bool enable, bool enable_rewrite_iat_and_original_iat_contents) +{ + save_iat_and_original_iat_rvas_ = enable; + if(save_iat_and_original_iat_rvas_) + rewrite_iat_and_original_iat_contents_ = enable_rewrite_iat_and_original_iat_contents; + else + rewrite_iat_and_original_iat_contents_ = false; +} + +//Sets if original missing IATs will be rebuilt +//(only if IATs are saved) +void import_rebuilder_settings::fill_missing_original_iats(bool enable) +{ + fill_missing_original_iats_ = enable; +} + +//Sets if PE headers should be updated automatically after rebuilding of imports +void import_rebuilder_settings::auto_set_to_pe_headers(bool enable) +{ + set_to_pe_headers_ = enable; +} + +//Sets if IMAGE_DIRECTORY_ENTRY_IAT must be zeroed, works only if auto_set_to_pe_headers = true +void import_rebuilder_settings::zero_directory_entry_iat(bool enable) +{ + zero_directory_entry_iat_ = enable; +} + +//Sets if the last section should be stripped automatically, if imports are inside it, default true +void import_rebuilder_settings::enable_auto_strip_last_section(bool enable) +{ + auto_strip_last_section_ = enable; +} + +//Default constructor +imported_function::imported_function() + :hint_(0), ordinal_(0), iat_va_(0) +{} + +//Returns name of function +const std::string& imported_function::get_name() const +{ + return name_; +} + +//Returns true if imported function has name (and hint) +bool imported_function::has_name() const +{ + return !name_.empty(); +} + +//Returns hint +uint16_t imported_function::get_hint() const +{ + return hint_; +} + +//Returns ordinal of function +uint16_t imported_function::get_ordinal() const +{ + return ordinal_; +} + +//Returns IAT entry VA (usable if image has both IAT and original IAT and is bound) +uint64_t imported_function::get_iat_va() const +{ + return iat_va_; +} + +//Sets name of function +void imported_function::set_name(const std::string& name) +{ + name_ = name; +} + +//Sets hint +void imported_function::set_hint(uint16_t hint) +{ + hint_ = hint; +} + +//Sets ordinal +void imported_function::set_ordinal(uint16_t ordinal) +{ + ordinal_ = ordinal; +} + +//Sets IAT entry VA (usable if image has both IAT and original IAT and is bound) +void imported_function::set_iat_va(uint64_t va) +{ + iat_va_ = va; +} + +//Default constructor +import_library::import_library() + :rva_to_iat_(0), rva_to_original_iat_(0), timestamp_(0) +{} + +//Returns name of library +const std::string& import_library::get_name() const +{ + return name_; +} + +//Returns RVA to Import Address Table (IAT) +uint32_t import_library::get_rva_to_iat() const +{ + return rva_to_iat_; +} + +//Returns RVA to Original Import Address Table (Original IAT) +uint32_t import_library::get_rva_to_original_iat() const +{ + return rva_to_original_iat_; +} + +//Returns timestamp +uint32_t import_library::get_timestamp() const +{ + return timestamp_; +} + +//Sets name of library +void import_library::set_name(const std::string& name) +{ + name_ = name; +} + +//Sets RVA to Import Address Table (IAT) +void import_library::set_rva_to_iat(uint32_t rva_to_iat) +{ + rva_to_iat_ = rva_to_iat; +} + +//Sets RVA to Original Import Address Table (Original IAT) +void import_library::set_rva_to_original_iat(uint32_t rva_to_original_iat) +{ + rva_to_original_iat_ = rva_to_original_iat; +} + +//Sets timestamp +void import_library::set_timestamp(uint32_t timestamp) +{ + timestamp_ = timestamp; +} + +//Returns imported functions list +const import_library::imported_list& import_library::get_imported_functions() const +{ + return imports_; +} + +//Adds imported function +void import_library::add_import(const imported_function& func) +{ + imports_.push_back(func); +} + +//Clears imported functions list +void import_library::clear_imports() +{ + imports_.clear(); +} + +const imported_functions_list get_imported_functions(const pe_base& pe) +{ + return (pe.get_pe_type() == pe_type_32 ? + get_imported_functions_base<pe_types_class_32>(pe) + : get_imported_functions_base<pe_types_class_64>(pe)); +} + +const image_directory rebuild_imports(pe_base& pe, const imported_functions_list& imports, section& import_section, const import_rebuilder_settings& import_settings) +{ + return (pe.get_pe_type() == pe_type_32 ? + rebuild_imports_base<pe_types_class_32>(pe, imports, import_section, import_settings) + : rebuild_imports_base<pe_types_class_64>(pe, imports, import_section, import_settings)); +} + +//Returns imported functions list with related libraries info +template<typename PEClassType> +const imported_functions_list get_imported_functions_base(const pe_base& pe) +{ + imported_functions_list ret; + + //If image has no imports, return empty array + if(!pe.has_imports()) + return ret; + + unsigned long current_descriptor_pos = pe.get_directory_rva(image_directory_entry_import); + //Get first IMAGE_IMPORT_DESCRIPTOR + image_import_descriptor import_descriptor = pe.section_data_from_rva<image_import_descriptor>(current_descriptor_pos, section_data_virtual, true); + + //Iterate them until we reach zero-element + //We don't need to check correctness of this, because exception will be thrown + //inside of loop if we go outsize of section + while(import_descriptor.Name) + { + //Get imported library information + import_library lib; + + unsigned long max_name_length; + //Get byte count that we have for library name + if((max_name_length = pe.section_data_length_from_rva(import_descriptor.Name, import_descriptor.Name, section_data_virtual, true)) < 2) + throw pe_exception("Incorrect import directory", pe_exception::incorrect_import_directory); + + //Get DLL name pointer + const char* dll_name = pe.section_data_from_rva(import_descriptor.Name, section_data_virtual, true); + + //Check for null-termination + if(!pe_utils::is_null_terminated(dll_name, max_name_length)) + throw pe_exception("Incorrect import directory", pe_exception::incorrect_import_directory); + + //Set library name + lib.set_name(dll_name); + //Set library timestamp + lib.set_timestamp(import_descriptor.TimeDateStamp); + //Set library RVA to IAT and original IAT + lib.set_rva_to_iat(import_descriptor.FirstThunk); + lib.set_rva_to_original_iat(import_descriptor.OriginalFirstThunk); + + //Get RVA to IAT (it must be filled by loader when loading PE) + uint32_t current_thunk_rva = import_descriptor.FirstThunk; + typename PEClassType::BaseSize import_address_table = pe.section_data_from_rva<typename PEClassType::BaseSize>(current_thunk_rva, section_data_virtual, true); + + //Get RVA to original IAT (lookup table), which must handle imported functions names + //Some linkers leave this pointer zero-filled + //Such image is valid, but it is not possible to restore imported functions names + //afted image was loaded, because IAT becomes the only one table + //containing both function names and function RVAs after loading + uint32_t current_original_thunk_rva = import_descriptor.OriginalFirstThunk; + typename PEClassType::BaseSize import_lookup_table = current_original_thunk_rva == 0 ? import_address_table : pe.section_data_from_rva<typename PEClassType::BaseSize>(current_original_thunk_rva, section_data_virtual, true); + if(current_original_thunk_rva == 0) + current_original_thunk_rva = current_thunk_rva; + + //List all imported functions for current DLL + if(import_lookup_table != 0 && import_address_table != 0) + { + while(true) + { + //Imported function description + imported_function func; + + //Get VA from IAT + typename PEClassType::BaseSize address = pe.section_data_from_rva<typename PEClassType::BaseSize>(current_thunk_rva, section_data_virtual, true); + //Move pointer + current_thunk_rva += sizeof(typename PEClassType::BaseSize); + + //Jump to next DLL if we finished with this one + if(!address) + break; + + func.set_iat_va(address); + + //Get VA from original IAT + typename PEClassType::BaseSize lookup = pe.section_data_from_rva<typename PEClassType::BaseSize>(current_original_thunk_rva, section_data_virtual, true); + //Move pointer + current_original_thunk_rva += sizeof(typename PEClassType::BaseSize); + + //Check if function is imported by ordinal + if((lookup & PEClassType::ImportSnapFlag) != 0) + { + //Set function ordinal + func.set_ordinal(static_cast<uint16_t>(lookup & 0xffff)); + } + else + { + //Get byte count that we have for function name + if(lookup > static_cast<uint32_t>(-1) - sizeof(uint16_t)) + throw pe_exception("Incorrect import directory", pe_exception::incorrect_import_directory); + + //Get maximum available length of function name + if((max_name_length = pe.section_data_length_from_rva(static_cast<uint32_t>(lookup + sizeof(uint16_t)), static_cast<uint32_t>(lookup + sizeof(uint16_t)), section_data_virtual, true)) < 2) + throw pe_exception("Incorrect import directory", pe_exception::incorrect_import_directory); + + //Get imported function name + const char* func_name = pe.section_data_from_rva(static_cast<uint32_t>(lookup + sizeof(uint16_t)), section_data_virtual, true); + + //Check for null-termination + if(!pe_utils::is_null_terminated(func_name, max_name_length)) + throw pe_exception("Incorrect import directory", pe_exception::incorrect_import_directory); + + //HINT in import table is ORDINAL in export table + uint16_t hint = pe.section_data_from_rva<uint16_t>(static_cast<uint32_t>(lookup), section_data_virtual, true); + + //Save hint and name + func.set_name(func_name); + func.set_hint(hint); + } + + //Add function to list + lib.add_import(func); + } + } + + //Check possible overflow + if(!pe_utils::is_sum_safe(current_descriptor_pos, sizeof(image_import_descriptor))) + throw pe_exception("Incorrect import directory", pe_exception::incorrect_import_directory); + + //Go to next library + current_descriptor_pos += sizeof(image_import_descriptor); + import_descriptor = pe.section_data_from_rva<image_import_descriptor>(current_descriptor_pos, section_data_virtual, true); + + //Save import information + ret.push_back(lib); + } + + //Return resulting list + return ret; +} + + +//Simple import directory rebuilder +//You can get all image imports with get_imported_functions() function +//You can use returned value to, for example, add new imported library with some functions +//to the end of list of imported libraries +//To keep PE file working, rebuild its imports with save_iat_and_original_iat_rvas = true (default) +//Don't add new imported functions to existing imported library entries, because this can cause +//rewriting of some used memory (or other IAT/orig.IAT fields) by system loader +//The safest way is just adding import libraries with functions to the end of imported_functions_list array +template<typename PEClassType> +const image_directory rebuild_imports_base(pe_base& pe, const imported_functions_list& imports, section& import_section, const import_rebuilder_settings& import_settings) +{ + //Check that import_section is attached to this PE image + if(!pe.section_attached(import_section)) + throw pe_exception("Import section must be attached to PE file", pe_exception::section_is_not_attached); + + uint32_t needed_size = 0; //Calculate needed size for import structures and strings + uint32_t needed_size_for_strings = 0; //Calculate needed size for import strings (library and function names and hints) + uint32_t size_of_iat = 0; //Size of IAT structures + + needed_size += static_cast<uint32_t>((1 /* ending null descriptor */ + imports.size()) * sizeof(image_import_descriptor)); + + //Enumerate imported functions + for(imported_functions_list::const_iterator it = imports.begin(); it != imports.end(); ++it) + { + needed_size_for_strings += static_cast<uint32_t>((*it).get_name().length() + 1 /* nullbyte */); + + const import_library::imported_list& funcs = (*it).get_imported_functions(); + + //IMAGE_THUNK_DATA + size_of_iat += static_cast<uint32_t>(sizeof(typename PEClassType::BaseSize) * (1 /*ending null */ + funcs.size())); + + //Enumerate all imported functions in library + for(import_library::imported_list::const_iterator f = funcs.begin(); f != funcs.end(); ++f) + { + if((*f).has_name()) + needed_size_for_strings += static_cast<uint32_t>((*f).get_name().length() + 1 /* nullbyte */ + sizeof(uint16_t) /* hint */); + } + } + + if(import_settings.build_original_iat() || import_settings.fill_missing_original_iats()) + needed_size += size_of_iat * 2; //We'll have two similar-sized IATs if we're building original IAT + else + needed_size += size_of_iat; + + needed_size += sizeof(typename PEClassType::BaseSize); //Maximum align for IAT and original IAT + + //Total needed size for import structures and strings + needed_size += needed_size_for_strings; + + //Check if import_section is last one. If it's not, check if there's enough place for import data + if(&import_section != &*(pe.get_image_sections().end() - 1) && + (import_section.empty() || pe_utils::align_up(import_section.get_size_of_raw_data(), pe.get_file_alignment()) < needed_size + import_settings.get_offset_from_section_start())) + throw pe_exception("Insufficient space for import directory", pe_exception::insufficient_space); + + std::string& raw_data = import_section.get_raw_data(); + + //This will be done only if image_section is the last section of image or for section with unaligned raw length of data + if(raw_data.length() < needed_size + import_settings.get_offset_from_section_start()) + raw_data.resize(needed_size + import_settings.get_offset_from_section_start()); //Expand section raw data + + uint32_t current_string_pointer = import_settings.get_offset_from_section_start();/* we will paste structures after strings */ + + //Position for IAT + uint32_t current_pos_for_iat = pe_utils::align_up(static_cast<uint32_t>(needed_size_for_strings + import_settings.get_offset_from_section_start() + (1 + imports.size()) * sizeof(image_import_descriptor)), sizeof(typename PEClassType::BaseSize)); + //Position for original IAT + uint32_t current_pos_for_original_iat = current_pos_for_iat + size_of_iat; + //Position for import descriptors + uint32_t current_pos_for_descriptors = needed_size_for_strings + import_settings.get_offset_from_section_start(); + + //Build imports + for(imported_functions_list::const_iterator it = imports.begin(); it != imports.end(); ++it) + { + //Create import descriptor + image_import_descriptor descr; + memset(&descr, 0, sizeof(descr)); + descr.TimeDateStamp = (*it).get_timestamp(); //Restore timestamp + descr.Name = pe.rva_from_section_offset(import_section, current_string_pointer); //Library name RVA + + //If we should save IAT for current import descriptor + bool save_iats_for_this_descriptor = import_settings.save_iat_and_original_iat_rvas() && (*it).get_rva_to_iat() != 0; + //If we should write original IAT + bool write_original_iat = (!save_iats_for_this_descriptor && import_settings.build_original_iat()) || import_settings.fill_missing_original_iats(); + + //If we should rewrite saved original IAT for current import descriptor (without changing its position) + bool rewrite_saved_original_iat = save_iats_for_this_descriptor && import_settings.rewrite_iat_and_original_iat_contents() && import_settings.build_original_iat(); + //If we should rewrite saved IAT for current import descriptor (without changing its position) + bool rewrite_saved_iat = save_iats_for_this_descriptor && import_settings.rewrite_iat_and_original_iat_contents() && (*it).get_rva_to_iat() != 0; + + //Helper values if we're rewriting existing IAT or orig.IAT + uint32_t original_first_thunk = 0; + uint32_t first_thunk = 0; + + if(save_iats_for_this_descriptor) + { + //If there's no original IAT and we're asked to rebuild missing original IATs + if(!(*it).get_rva_to_original_iat() && import_settings.fill_missing_original_iats()) + descr.OriginalFirstThunk = import_settings.build_original_iat() ? pe.rva_from_section_offset(import_section, current_pos_for_original_iat) : 0; + else + descr.OriginalFirstThunk = import_settings.build_original_iat() ? (*it).get_rva_to_original_iat() : 0; + + descr.FirstThunk = (*it).get_rva_to_iat(); + + original_first_thunk = descr.OriginalFirstThunk; + first_thunk = descr.FirstThunk; + + if(rewrite_saved_original_iat) + { + if((*it).get_rva_to_original_iat()) + write_original_iat = true; + else + rewrite_saved_original_iat = false; + } + + if(rewrite_saved_iat) + save_iats_for_this_descriptor = false; + } + else + { + //We are creating new IAT and original IAT (if needed) + descr.OriginalFirstThunk = import_settings.build_original_iat() ? pe.rva_from_section_offset(import_section, current_pos_for_original_iat) : 0; + descr.FirstThunk = pe.rva_from_section_offset(import_section, current_pos_for_iat); + } + + //Save import descriptor + memcpy(&raw_data[current_pos_for_descriptors], &descr, sizeof(descr)); + current_pos_for_descriptors += sizeof(descr); + + //Save library name + memcpy(&raw_data[current_string_pointer], (*it).get_name().c_str(), (*it).get_name().length() + 1 /* nullbyte */); + current_string_pointer += static_cast<uint32_t>((*it).get_name().length() + 1 /* nullbyte */); + + //List all imported functions + const import_library::imported_list& funcs = (*it).get_imported_functions(); + for(import_library::imported_list::const_iterator f = funcs.begin(); f != funcs.end(); ++f) + { + if((*f).has_name()) //If function is imported by name + { + //Get RVA of IMAGE_IMPORT_BY_NAME + typename PEClassType::BaseSize rva_of_named_import = pe.rva_from_section_offset(import_section, current_string_pointer); + + if(!save_iats_for_this_descriptor) + { + if(write_original_iat) + { + //We're creating original IATs - so we can write to IAT saved VA (because IMAGE_IMPORT_BY_NAME will be read + //by PE loader from original IAT) + typename PEClassType::BaseSize iat_value = static_cast<typename PEClassType::BaseSize>((*f).get_iat_va()); + + if(rewrite_saved_iat) + { + if(pe.section_data_length_from_rva(first_thunk, first_thunk, section_data_raw, true) <= sizeof(iat_value)) + throw pe_exception("Insufficient space inside initial IAT", pe_exception::insufficient_space); + + memcpy(pe.section_data_from_rva(first_thunk, true), &iat_value, sizeof(iat_value)); + + first_thunk += sizeof(iat_value); + } + else + { + memcpy(&raw_data[current_pos_for_iat], &iat_value, sizeof(iat_value)); + current_pos_for_iat += sizeof(rva_of_named_import); + } + } + else + { + //Else - write to IAT RVA of IMAGE_IMPORT_BY_NAME + if(rewrite_saved_iat) + { + if(pe.section_data_length_from_rva(first_thunk, first_thunk, section_data_raw, true) <= sizeof(rva_of_named_import)) + throw pe_exception("Insufficient space inside initial IAT", pe_exception::insufficient_space); + + memcpy(pe.section_data_from_rva(first_thunk, true), &rva_of_named_import, sizeof(rva_of_named_import)); + + first_thunk += sizeof(rva_of_named_import); + } + else + { + memcpy(&raw_data[current_pos_for_iat], &rva_of_named_import, sizeof(rva_of_named_import)); + current_pos_for_iat += sizeof(rva_of_named_import); + } + } + } + + if(write_original_iat) + { + if(rewrite_saved_original_iat) + { + if(pe.section_data_length_from_rva(original_first_thunk, original_first_thunk, section_data_raw, true) <= sizeof(rva_of_named_import)) + throw pe_exception("Insufficient space inside initial original IAT", pe_exception::insufficient_space); + + memcpy(pe.section_data_from_rva(original_first_thunk, true), &rva_of_named_import, sizeof(rva_of_named_import)); + + original_first_thunk += sizeof(rva_of_named_import); + } + else + { + //We're creating original IATs + memcpy(&raw_data[current_pos_for_original_iat], &rva_of_named_import, sizeof(rva_of_named_import)); + current_pos_for_original_iat += sizeof(rva_of_named_import); + } + } + + //Write IMAGE_IMPORT_BY_NAME (WORD hint + string function name) + uint16_t hint = (*f).get_hint(); + memcpy(&raw_data[current_string_pointer], &hint, sizeof(hint)); + memcpy(&raw_data[current_string_pointer + sizeof(uint16_t)], (*f).get_name().c_str(), (*f).get_name().length() + 1 /* nullbyte */); + current_string_pointer += static_cast<uint32_t>((*f).get_name().length() + 1 /* nullbyte */ + sizeof(uint16_t) /* hint */); + } + else //Function is imported by ordinal + { + uint16_t ordinal = (*f).get_ordinal(); + typename PEClassType::BaseSize thunk_value = ordinal; + thunk_value |= PEClassType::ImportSnapFlag; //Imported by ordinal + + if(!save_iats_for_this_descriptor) + { + if(write_original_iat) + { + //We're creating original IATs - so we can wtire to IAT saved VA (because ordinal will be read + //by PE loader from original IAT) + typename PEClassType::BaseSize iat_value = static_cast<typename PEClassType::BaseSize>((*f).get_iat_va()); + if(rewrite_saved_iat) + { + if(pe.section_data_length_from_rva(first_thunk, first_thunk, section_data_raw, true) <= sizeof(iat_value)) + throw pe_exception("Insufficient space inside initial IAT", pe_exception::insufficient_space); + + memcpy(pe.section_data_from_rva(first_thunk, true), &iat_value, sizeof(iat_value)); + + first_thunk += sizeof(iat_value); + } + else + { + memcpy(&raw_data[current_pos_for_iat], &iat_value, sizeof(iat_value)); + current_pos_for_iat += sizeof(thunk_value); + } + } + else + { + //Else - write ordinal to IAT + if(rewrite_saved_iat) + { + if(pe.section_data_length_from_rva(first_thunk, first_thunk, section_data_raw, true) <= sizeof(thunk_value)) + throw pe_exception("Insufficient space inside initial IAT", pe_exception::insufficient_space); + + memcpy(pe.section_data_from_rva(first_thunk, true), &thunk_value, sizeof(thunk_value)); + + first_thunk += sizeof(thunk_value); + } + else + { + memcpy(&raw_data[current_pos_for_iat], &thunk_value, sizeof(thunk_value)); + } + } + } + + //We're writing ordinal to original IAT slot + if(write_original_iat) + { + if(rewrite_saved_original_iat) + { + if(pe.section_data_length_from_rva(original_first_thunk, original_first_thunk, section_data_raw, true) <= sizeof(thunk_value)) + throw pe_exception("Insufficient space inside initial original IAT", pe_exception::insufficient_space); + + memcpy(pe.section_data_from_rva(original_first_thunk, true), &thunk_value, sizeof(thunk_value)); + + original_first_thunk += sizeof(thunk_value); + } + else + { + memcpy(&raw_data[current_pos_for_original_iat], &thunk_value, sizeof(thunk_value)); + current_pos_for_original_iat += sizeof(thunk_value); + } + } + } + } + + if(!save_iats_for_this_descriptor) + { + //Ending null thunks + typename PEClassType::BaseSize thunk_value = 0; + + if(rewrite_saved_iat) + { + if(pe.section_data_length_from_rva(first_thunk, first_thunk, section_data_raw, true) <= sizeof(thunk_value)) + throw pe_exception("Insufficient space inside initial IAT", pe_exception::insufficient_space); + + memcpy(pe.section_data_from_rva(first_thunk, true), &thunk_value, sizeof(thunk_value)); + + first_thunk += sizeof(thunk_value); + } + else + { + memcpy(&raw_data[current_pos_for_iat], &thunk_value, sizeof(thunk_value)); + current_pos_for_iat += sizeof(thunk_value); + } + } + + if(write_original_iat) + { + //Ending null thunks + typename PEClassType::BaseSize thunk_value = 0; + + if(rewrite_saved_original_iat) + { + if(pe.section_data_length_from_rva(original_first_thunk, original_first_thunk, section_data_raw, true) <= sizeof(thunk_value)) + throw pe_exception("Insufficient space inside initial original IAT", pe_exception::insufficient_space); + + memcpy(pe.section_data_from_rva(original_first_thunk, true), &thunk_value, sizeof(thunk_value)); + + original_first_thunk += sizeof(thunk_value); + } + else + { + memcpy(&raw_data[current_pos_for_original_iat], &thunk_value, sizeof(thunk_value)); + current_pos_for_original_iat += sizeof(thunk_value); + } + } + } + + { + //Null ending descriptor + image_import_descriptor descr; + memset(&descr, 0, sizeof(descr)); + memcpy(&raw_data[current_pos_for_descriptors], &descr, sizeof(descr)); + } + + //Strip data a little, if we saved some place + //We're allocating more space than needed, if present original IAT and IAT are saved + raw_data.resize(current_pos_for_original_iat); + + //Adjust section raw and virtual sizes + pe.recalculate_section_sizes(import_section, import_settings.auto_strip_last_section_enabled()); + + //Return information about rebuilt import directory + image_directory ret(pe.rva_from_section_offset(import_section, import_settings.get_offset_from_section_start() + needed_size_for_strings), needed_size - needed_size_for_strings); + + //If auto-rewrite of PE headers is required + if(import_settings.auto_set_to_pe_headers()) + { + pe.set_directory_rva(image_directory_entry_import, ret.get_rva()); + pe.set_directory_size(image_directory_entry_import, ret.get_size()); + + //If we are requested to zero IMAGE_DIRECTORY_ENTRY_IAT also + if(import_settings.zero_directory_entry_iat()) + { + pe.set_directory_rva(image_directory_entry_iat, 0); + pe.set_directory_size(image_directory_entry_iat, 0); + } + } + + return ret; +} +} diff --git a/tools/pe_bliss/pe_imports.h b/tools/pe_bliss/pe_imports.h new file mode 100644 index 0000000000..681b5b59bd --- /dev/null +++ b/tools/pe_bliss/pe_imports.h @@ -0,0 +1,208 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <vector> +#include <string> +#include "pe_structures.h" +#include "pe_directory.h" +#include "pe_base.h" + +namespace pe_bliss +{ +//Class representing imported function +class imported_function +{ +public: + //Default constructor + imported_function(); + + //Returns true if imported function has name (and hint) + bool has_name() const; + //Returns name of function + const std::string& get_name() const; + //Returns hint + uint16_t get_hint() const; + //Returns ordinal of function + uint16_t get_ordinal() const; + + //Returns IAT entry VA (usable if image has both IAT and original IAT and is bound) + uint64_t get_iat_va() const; + +public: //Setters do not change everything inside image, they are used by PE class + //You also can use them to rebuild image imports + //Sets name of function + void set_name(const std::string& name); + //Sets hint + void set_hint(uint16_t hint); + //Sets ordinal + void set_ordinal(uint16_t ordinal); + + //Sets IAT entry VA (usable if image has both IAT and original IAT and is bound) + void set_iat_va(uint64_t rva); + +private: + std::string name_; //Function name + uint16_t hint_; //Hint + uint16_t ordinal_; //Ordinal + uint64_t iat_va_; +}; + +//Class representing imported library information +class import_library +{ +public: + typedef std::vector<imported_function> imported_list; + +public: + //Default constructor + import_library(); + + //Returns name of library + const std::string& get_name() const; + //Returns RVA to Import Address Table (IAT) + uint32_t get_rva_to_iat() const; + //Returns RVA to Original Import Address Table (Original IAT) + uint32_t get_rva_to_original_iat() const; + //Returns timestamp + uint32_t get_timestamp() const; + + //Returns imported functions list + const imported_list& get_imported_functions() const; + +public: //Setters do not change everything inside image, they are used by PE class + //You also can use them to rebuild image imports + //Sets name of library + void set_name(const std::string& name); + //Sets RVA to Import Address Table (IAT) + void set_rva_to_iat(uint32_t rva_to_iat); + //Sets RVA to Original Import Address Table (Original IAT) + void set_rva_to_original_iat(uint32_t rva_to_original_iat); + //Sets timestamp + void set_timestamp(uint32_t timestamp); + + //Adds imported function + void add_import(const imported_function& func); + //Clears imported functions list + void clear_imports(); + +private: + std::string name_; //Library name + uint32_t rva_to_iat_; //RVA to IAT + uint32_t rva_to_original_iat_; //RVA to original IAT + uint32_t timestamp_; //DLL TimeStamp + + imported_list imports_; +}; + +//Simple import directory rebuilder +//Class representing import rebuilder advanced settings +class import_rebuilder_settings +{ +public: + //Default constructor + //Default constructor + //If set_to_pe_headers = true, IMAGE_DIRECTORY_ENTRY_IMPORT entry will be reset + //to new value after import rebuilding + //If auto_zero_directory_entry_iat = true, IMAGE_DIRECTORY_ENTRY_IAT will be set to zero + //IMAGE_DIRECTORY_ENTRY_IAT is used by loader to temporarily make section, where IMAGE_DIRECTORY_ENTRY_IAT RVA points, writeable + //to be able to modify IAT thunks + explicit import_rebuilder_settings(bool set_to_pe_headers = true, bool auto_zero_directory_entry_iat = false); + + //Returns offset from section start where import directory data will be placed + uint32_t get_offset_from_section_start() const; + //Returns true if Original import address table (IAT) will be rebuilt + bool build_original_iat() const; + + //Returns true if Original import address and import address tables will not be rebuilt, + //works only if import descriptor IAT (and orig.IAT, if present) RVAs are not zero + bool save_iat_and_original_iat_rvas() const; + //Returns true if Original import address and import address tables contents will be rewritten + //works only if import descriptor IAT (and orig.IAT, if present) RVAs are not zero + //and save_iat_and_original_iat_rvas is true + bool rewrite_iat_and_original_iat_contents() const; + + //Returns true if original missing IATs will be rebuilt + //(only if IATs are saved) + bool fill_missing_original_iats() const; + //Returns true if PE headers should be updated automatically after rebuilding of imports + bool auto_set_to_pe_headers() const; + //Returns true if IMAGE_DIRECTORY_ENTRY_IAT must be zeroed, works only if auto_set_to_pe_headers = true + bool zero_directory_entry_iat() const; + + //Returns true if the last section should be stripped automatically, if imports are inside it + bool auto_strip_last_section_enabled() const; + +public: //Setters + //Sets offset from section start where import directory data will be placed + void set_offset_from_section_start(uint32_t offset); + //Sets if Original import address table (IAT) will be rebuilt + void build_original_iat(bool enable); + //Sets if Original import address and import address tables will not be rebuilt, + //works only if import descriptor IAT (and orig.IAT, if present) RVAs are not zero + //enable_rewrite_iat_and_original_iat_contents sets if Original import address and import address tables contents will be rewritten + //works only if import descriptor IAT (and orig.IAT, if present) RVAs are not zero + //and save_iat_and_original_iat_rvas is true + void save_iat_and_original_iat_rvas(bool enable, bool enable_rewrite_iat_and_original_iat_contents = false); + //Sets if original missing IATs will be rebuilt + //(only if IATs are saved) + void fill_missing_original_iats(bool enable); + //Sets if PE headers should be updated automatically after rebuilding of imports + void auto_set_to_pe_headers(bool enable); + //Sets if IMAGE_DIRECTORY_ENTRY_IAT must be zeroed, works only if auto_set_to_pe_headers = true + void zero_directory_entry_iat(bool enable); + + //Sets if the last section should be stripped automatically, if imports are inside it, default true + void enable_auto_strip_last_section(bool enable); + +private: + uint32_t offset_from_section_start_; + bool build_original_iat_; + bool save_iat_and_original_iat_rvas_; + bool fill_missing_original_iats_; + bool set_to_pe_headers_; + bool zero_directory_entry_iat_; + bool rewrite_iat_and_original_iat_contents_; + bool auto_strip_last_section_; +}; + +typedef std::vector<import_library> imported_functions_list; + + +//Returns imported functions list with related libraries info +const imported_functions_list get_imported_functions(const pe_base& pe); + +template<typename PEClassType> +const imported_functions_list get_imported_functions_base(const pe_base& pe); + + +//You can get all image imports with get_imported_functions() function +//You can use returned value to, for example, add new imported library with some functions +//to the end of list of imported libraries +//To keep PE file working, rebuild its imports with save_iat_and_original_iat_rvas = true (default) +//Don't add new imported functions to existing imported library entries, because this can cause +//rewriting of some used memory (or other IAT/orig.IAT fields) by system loader +//The safest way is just adding import libraries with functions to the end of imported_functions_list array +const image_directory rebuild_imports(pe_base& pe, const imported_functions_list& imports, section& import_section, const import_rebuilder_settings& import_settings = import_rebuilder_settings()); + +template<typename PEClassType> +const image_directory rebuild_imports_base(pe_base& pe, const imported_functions_list& imports, section& import_section, const import_rebuilder_settings& import_settings = import_rebuilder_settings()); +} diff --git a/tools/pe_bliss/pe_load_config.cpp b/tools/pe_bliss/pe_load_config.cpp new file mode 100644 index 0000000000..c05895fecd --- /dev/null +++ b/tools/pe_bliss/pe_load_config.cpp @@ -0,0 +1,557 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <algorithm> +#include <string.h> +#include "pe_load_config.h" +#include "pe_properties_generic.h" + +namespace pe_bliss +{ +using namespace pe_win; + +//IMAGE CONFIG +//Default constructor +image_config_info::image_config_info() + :time_stamp_(0), + major_version_(0), minor_version_(0), + global_flags_clear_(0), global_flags_set_(0), + critical_section_default_timeout_(0), + decommit_free_block_threshold_(0), decommit_total_free_threshold_(0), + lock_prefix_table_va_(0), + max_allocation_size_(0), + virtual_memory_threshold_(0), + process_affinity_mask_(0), + process_heap_flags_(0), + service_pack_version_(0), + edit_list_va_(0), + security_cookie_va_(0), + se_handler_table_va_(0), + se_handler_count_(0) +{} + +//Constructors from PE structures +template<typename ConfigStructure> +image_config_info::image_config_info(const ConfigStructure& info) + :time_stamp_(info.TimeDateStamp), + major_version_(info.MajorVersion), minor_version_(info.MinorVersion), + global_flags_clear_(info.GlobalFlagsClear), global_flags_set_(info.GlobalFlagsSet), + critical_section_default_timeout_(info.CriticalSectionDefaultTimeout), + decommit_free_block_threshold_(info.DeCommitFreeBlockThreshold), decommit_total_free_threshold_(info.DeCommitTotalFreeThreshold), + lock_prefix_table_va_(info.LockPrefixTable), + max_allocation_size_(info.MaximumAllocationSize), + virtual_memory_threshold_(info.VirtualMemoryThreshold), + process_affinity_mask_(info.ProcessAffinityMask), + process_heap_flags_(info.ProcessHeapFlags), + service_pack_version_(info.CSDVersion), + edit_list_va_(info.EditList), + security_cookie_va_(info.SecurityCookie), + se_handler_table_va_(info.SEHandlerTable), + se_handler_count_(info.SEHandlerCount) +{} + +//Instantiate template constructor with needed structures +template image_config_info::image_config_info(const image_load_config_directory32& info); +template image_config_info::image_config_info(const image_load_config_directory64& info); + +//Returns the date and time stamp value +uint32_t image_config_info::get_time_stamp() const +{ + return time_stamp_; +} + +//Returns major version number +uint16_t image_config_info::get_major_version() const +{ + return major_version_; +} + +//Returns minor version number +uint16_t image_config_info::get_minor_version() const +{ + return minor_version_; +} + +//Returns clear global flags +uint32_t image_config_info::get_global_flags_clear() const +{ + return global_flags_clear_; +} + +//Returns set global flags +uint32_t image_config_info::get_global_flags_set() const +{ + return global_flags_set_; +} + +//Returns critical section default timeout +uint32_t image_config_info::get_critical_section_default_timeout() const +{ + return critical_section_default_timeout_; +} + +//Get the size of the minimum block that +//must be freed before it is freed (de-committed), in bytes +uint64_t image_config_info::get_decommit_free_block_threshold() const +{ + return decommit_free_block_threshold_; +} + +//Returns the size of the minimum total memory +//that must be freed in the process heap before it is freed (de-committed), in bytes +uint64_t image_config_info::get_decommit_total_free_threshold() const +{ + return decommit_total_free_threshold_; +} + +//Returns VA of a list of addresses where the LOCK prefix is used +uint64_t image_config_info::get_lock_prefix_table_va() const +{ + return lock_prefix_table_va_; +} + +//Returns the maximum allocation size, in bytes +uint64_t image_config_info::get_max_allocation_size() const +{ + return max_allocation_size_; +} + +//Returns the maximum block size that can be allocated from heap segments, in bytes +uint64_t image_config_info::get_virtual_memory_threshold() const +{ + return virtual_memory_threshold_; +} + +//Returns process affinity mask +uint64_t image_config_info::get_process_affinity_mask() const +{ + return process_affinity_mask_; +} + +//Returns process heap flags +uint32_t image_config_info::get_process_heap_flags() const +{ + return process_heap_flags_; +} + +//Returns service pack version (CSDVersion) +uint16_t image_config_info::get_service_pack_version() const +{ + return service_pack_version_; +} + +//Returns VA of edit list (reserved by system) +uint64_t image_config_info::get_edit_list_va() const +{ + return edit_list_va_; +} + +//Returns a pointer to a cookie that is used by Visual C++ or GS implementation +uint64_t image_config_info::get_security_cookie_va() const +{ + return security_cookie_va_; +} + +//Returns VA of the sorted table of RVAs of each valid, unique handler in the image +uint64_t image_config_info::get_se_handler_table_va() const +{ + return se_handler_table_va_; +} + +//Returns the count of unique handlers in the table +uint64_t image_config_info::get_se_handler_count() const +{ + return se_handler_count_; +} + +//Returns SE Handler RVA list +const image_config_info::se_handler_list& image_config_info::get_se_handler_rvas() const +{ + return se_handlers_; +} + +//Returns Lock Prefix RVA list +const image_config_info::lock_prefix_rva_list& image_config_info::get_lock_prefix_rvas() const +{ + return lock_prefixes_; +} + +//Adds SE Handler RVA to list +void image_config_info::add_se_handler_rva(uint32_t rva) +{ + se_handlers_.push_back(rva); +} + +//Clears SE Handler list +void image_config_info::clear_se_handler_list() +{ + se_handlers_.clear(); +} + +//Adds Lock Prefix RVA to list +void image_config_info::add_lock_prefix_rva(uint32_t rva) +{ + lock_prefixes_.push_back(rva); +} + +//Clears Lock Prefix list +void image_config_info::clear_lock_prefix_list() +{ + lock_prefixes_.clear(); +} + +//Sets the date and time stamp value +void image_config_info::set_time_stamp(uint32_t time_stamp) +{ + time_stamp_ = time_stamp; +} + +//Sets major version number +void image_config_info::set_major_version(uint16_t major_version) +{ + major_version_ = major_version; +} + +//Sets minor version number +void image_config_info::set_minor_version(uint16_t minor_version) +{ + minor_version_ = minor_version; +} + +//Sets clear global flags +void image_config_info::set_global_flags_clear(uint32_t global_flags_clear) +{ + global_flags_clear_ = global_flags_clear; +} + +//Sets set global flags +void image_config_info::set_global_flags_set(uint32_t global_flags_set) +{ + global_flags_set_ = global_flags_set; +} + +//Sets critical section default timeout +void image_config_info::set_critical_section_default_timeout(uint32_t critical_section_default_timeout) +{ + critical_section_default_timeout_ = critical_section_default_timeout; +} + +//Sets the size of the minimum block that +//must be freed before it is freed (de-committed), in bytes +void image_config_info::set_decommit_free_block_threshold(uint64_t decommit_free_block_threshold) +{ + decommit_free_block_threshold_ = decommit_free_block_threshold; +} + +//Sets the size of the minimum total memory +//that must be freed in the process heap before it is freed (de-committed), in bytes +void image_config_info::set_decommit_total_free_threshold(uint64_t decommit_total_free_threshold) +{ + decommit_total_free_threshold_ = decommit_total_free_threshold; +} + +//Sets VA of a list of addresses where the LOCK prefix is used +//If you rebuild this list, VA will be re-assigned automatically +void image_config_info::set_lock_prefix_table_va(uint64_t lock_prefix_table_va) +{ + lock_prefix_table_va_ = lock_prefix_table_va; +} + +//Sets the maximum allocation size, in bytes +void image_config_info::set_max_allocation_size(uint64_t max_allocation_size) +{ + max_allocation_size_ = max_allocation_size; +} + +//Sets the maximum block size that can be allocated from heap segments, in bytes +void image_config_info::set_virtual_memory_threshold(uint64_t virtual_memory_threshold) +{ + virtual_memory_threshold_ = virtual_memory_threshold; +} + +//Sets process affinity mask +void image_config_info::set_process_affinity_mask(uint64_t process_affinity_mask) +{ + process_affinity_mask_ = process_affinity_mask; +} + +//Sets process heap flags +void image_config_info::set_process_heap_flags(uint32_t process_heap_flags) +{ + process_heap_flags_ = process_heap_flags; +} + +//Sets service pack version (CSDVersion) +void image_config_info::set_service_pack_version(uint16_t service_pack_version) +{ + service_pack_version_ = service_pack_version; +} + +//Sets VA of edit list (reserved by system) +void image_config_info::set_edit_list_va(uint64_t edit_list_va) +{ + edit_list_va_ = edit_list_va; +} + +//Sets a pointer to a cookie that is used by Visual C++ or GS implementation +void image_config_info::set_security_cookie_va(uint64_t security_cookie_va) +{ + security_cookie_va_ = security_cookie_va; +} + +//Sets VA of the sorted table of RVAs of each valid, unique handler in the image +//If you rebuild this list, VA will be re-assigned automatically +void image_config_info::set_se_handler_table_va(uint64_t se_handler_table_va) +{ + se_handler_table_va_ = se_handler_table_va; +} + +//Returns SE Handler RVA list +image_config_info::se_handler_list& image_config_info::get_se_handler_rvas() +{ + return se_handlers_; +} + +//Returns Lock Prefix RVA list +image_config_info::lock_prefix_rva_list& image_config_info::get_lock_prefix_rvas() +{ + return lock_prefixes_; +} + +//Returns image config info +//If image does not have config info, throws an exception +const image_config_info get_image_config(const pe_base& pe) +{ + return pe.get_pe_type() == pe_type_32 + ? get_image_config_base<pe_types_class_32>(pe) + : get_image_config_base<pe_types_class_64>(pe); +} + +//Image config rebuilder +const image_directory rebuild_image_config(pe_base& pe, const image_config_info& info, section& image_config_section, uint32_t offset_from_section_start, bool write_se_handlers, bool write_lock_prefixes, bool save_to_pe_header, bool auto_strip_last_section) +{ + return pe.get_pe_type() == pe_type_32 + ? rebuild_image_config_base<pe_types_class_32>(pe, info, image_config_section, offset_from_section_start, write_se_handlers, write_lock_prefixes, save_to_pe_header, auto_strip_last_section) + : rebuild_image_config_base<pe_types_class_64>(pe, info, image_config_section, offset_from_section_start, write_se_handlers, write_lock_prefixes, save_to_pe_header, auto_strip_last_section); +} + + +//Returns image config info +//If image does not have config info, throws an exception +template<typename PEClassType> +const image_config_info get_image_config_base(const pe_base& pe) +{ + //Check if image has config directory + if(!pe.has_config()) + throw pe_exception("Image does not have load config directory", pe_exception::directory_does_not_exist); + + //Get load config structure + typename PEClassType::ConfigStruct config_info = pe.section_data_from_rva<typename PEClassType::ConfigStruct>(pe.get_directory_rva(image_directory_entry_load_config), section_data_virtual); + + //Check size of config directory + if(config_info.Size != sizeof(config_info)) + throw pe_exception("Incorrect (or old) load config directory", pe_exception::incorrect_config_directory); + + //Fill return structure + image_config_info ret(config_info); + + //Check possible overflow + if(config_info.SEHandlerCount >= pe_utils::max_dword / sizeof(uint32_t) + || config_info.SEHandlerTable >= static_cast<typename PEClassType::BaseSize>(-1) - config_info.SEHandlerCount * sizeof(uint32_t)) + throw pe_exception("Incorrect load config directory", pe_exception::incorrect_config_directory); + + //Read sorted SE handler RVA list (if any) + for(typename PEClassType::BaseSize i = 0; i != config_info.SEHandlerCount; ++i) + ret.add_se_handler_rva(pe.section_data_from_va<uint32_t>(static_cast<typename PEClassType::BaseSize>(config_info.SEHandlerTable + i * sizeof(uint32_t)))); + + if(config_info.LockPrefixTable) + { + //Read Lock Prefix VA list (if any) + unsigned long current = 0; + while(true) + { + typename PEClassType::BaseSize lock_prefix_va = pe.section_data_from_va<typename PEClassType::BaseSize>(static_cast<typename PEClassType::BaseSize>(config_info.LockPrefixTable + current * sizeof(typename PEClassType::BaseSize))); + if(!lock_prefix_va) + break; + + ret.add_lock_prefix_rva(pe.va_to_rva(lock_prefix_va)); + + ++current; + } + } + + return ret; +} + +//Image config directory rebuilder +//auto_strip_last_section - if true and TLS are placed in the last section, it will be automatically stripped +//If write_se_handlers = true, SE Handlers list will be written just after image config directory structure +//If write_lock_prefixes = true, Lock Prefixes address list will be written just after image config directory structure +template<typename PEClassType> +const image_directory rebuild_image_config_base(pe_base& pe, const image_config_info& info, section& image_config_section, uint32_t offset_from_section_start, bool write_se_handlers, bool write_lock_prefixes, bool save_to_pe_header, bool auto_strip_last_section) +{ + //Check that image_config_section is attached to this PE image + if(!pe.section_attached(image_config_section)) + throw pe_exception("Image Config section must be attached to PE file", pe_exception::section_is_not_attached); + + uint32_t alignment = pe_utils::align_up(offset_from_section_start, sizeof(typename PEClassType::BaseSize)) - offset_from_section_start; + + uint32_t needed_size = sizeof(typename PEClassType::ConfigStruct); //Calculate needed size for Image Config table + + uint32_t image_config_data_pos = offset_from_section_start + alignment; + + uint32_t current_pos_of_se_handlers = 0; + uint32_t current_pos_of_lock_prefixes = 0; + + if(write_se_handlers) + { + current_pos_of_se_handlers = needed_size + image_config_data_pos; + needed_size += static_cast<uint32_t>(info.get_se_handler_rvas().size()) * sizeof(uint32_t); //RVAs of SE Handlers + } + + if(write_lock_prefixes) + { + current_pos_of_lock_prefixes = needed_size + image_config_data_pos; + needed_size += static_cast<uint32_t>((info.get_lock_prefix_rvas().size() + 1) * sizeof(typename PEClassType::BaseSize)); //VAs of Lock Prefixes (and ending null element) + } + + //Check if image_config_section is last one. If it's not, check if there's enough place for Image Config data + if(&image_config_section != &*(pe.get_image_sections().end() - 1) && + (image_config_section.empty() || pe_utils::align_up(image_config_section.get_size_of_raw_data(), pe.get_file_alignment()) < needed_size + image_config_data_pos)) + throw pe_exception("Insufficient space for TLS directory", pe_exception::insufficient_space); + + std::string& raw_data = image_config_section.get_raw_data(); + + //This will be done only if image_config_section is the last section of image or for section with unaligned raw length of data + if(raw_data.length() < needed_size + image_config_data_pos) + raw_data.resize(needed_size + image_config_data_pos); //Expand section raw data + + //Create and fill Image Config structure + typename PEClassType::ConfigStruct image_config_section_struct = {0}; + image_config_section_struct.Size = sizeof(image_config_section_struct); + image_config_section_struct.TimeDateStamp = info.get_time_stamp(); + image_config_section_struct.MajorVersion = info.get_major_version(); + image_config_section_struct.MinorVersion = info.get_minor_version(); + image_config_section_struct.GlobalFlagsClear = info.get_global_flags_clear(); + image_config_section_struct.GlobalFlagsSet = info.get_global_flags_set(); + image_config_section_struct.CriticalSectionDefaultTimeout = info.get_critical_section_default_timeout(); + image_config_section_struct.DeCommitFreeBlockThreshold = static_cast<typename PEClassType::BaseSize>(info.get_decommit_free_block_threshold()); + image_config_section_struct.DeCommitTotalFreeThreshold = static_cast<typename PEClassType::BaseSize>(info.get_decommit_total_free_threshold()); + image_config_section_struct.MaximumAllocationSize = static_cast<typename PEClassType::BaseSize>(info.get_max_allocation_size()); + image_config_section_struct.VirtualMemoryThreshold = static_cast<typename PEClassType::BaseSize>(info.get_virtual_memory_threshold()); + image_config_section_struct.ProcessHeapFlags = info.get_process_heap_flags(); + image_config_section_struct.ProcessAffinityMask = static_cast<typename PEClassType::BaseSize>(info.get_process_affinity_mask()); + image_config_section_struct.CSDVersion = info.get_service_pack_version(); + image_config_section_struct.EditList = static_cast<typename PEClassType::BaseSize>(info.get_edit_list_va()); + image_config_section_struct.SecurityCookie = static_cast<typename PEClassType::BaseSize>(info.get_security_cookie_va()); + image_config_section_struct.SEHandlerCount = static_cast<typename PEClassType::BaseSize>(info.get_se_handler_rvas().size()); + + + if(write_se_handlers) + { + if(info.get_se_handler_rvas().empty()) + { + write_se_handlers = false; + image_config_section_struct.SEHandlerTable = 0; + } + else + { + typename PEClassType::BaseSize va; + pe.rva_to_va(pe.rva_from_section_offset(image_config_section, current_pos_of_se_handlers), va); + image_config_section_struct.SEHandlerTable = va; + } + } + else + { + image_config_section_struct.SEHandlerTable = static_cast<typename PEClassType::BaseSize>(info.get_se_handler_table_va()); + } + + if(write_lock_prefixes) + { + if(info.get_lock_prefix_rvas().empty()) + { + write_lock_prefixes = false; + image_config_section_struct.LockPrefixTable = 0; + } + else + { + typename PEClassType::BaseSize va; + pe.rva_to_va(pe.rva_from_section_offset(image_config_section, current_pos_of_lock_prefixes), va); + image_config_section_struct.LockPrefixTable = va; + } + } + else + { + image_config_section_struct.LockPrefixTable = static_cast<typename PEClassType::BaseSize>(info.get_lock_prefix_table_va()); + } + + //Write image config section + memcpy(&raw_data[image_config_data_pos], &image_config_section_struct, sizeof(image_config_section_struct)); + + if(write_se_handlers) + { + //Sort SE Handlers list + image_config_info::se_handler_list sorted_list = info.get_se_handler_rvas(); + std::sort(sorted_list.begin(), sorted_list.end()); + + //Write SE Handlers table + for(image_config_info::se_handler_list::const_iterator it = sorted_list.begin(); it != sorted_list.end(); ++it) + { + uint32_t se_handler_rva = *it; + memcpy(&raw_data[current_pos_of_se_handlers], &se_handler_rva, sizeof(se_handler_rva)); + current_pos_of_se_handlers += sizeof(se_handler_rva); + } + } + + if(write_lock_prefixes) + { + //Write Lock Prefixes VA list + for(image_config_info::lock_prefix_rva_list::const_iterator it = info.get_lock_prefix_rvas().begin(); it != info.get_lock_prefix_rvas().end(); ++it) + { + typename PEClassType::BaseSize lock_prefix_va; + pe.rva_to_va(*it, lock_prefix_va); + memcpy(&raw_data[current_pos_of_lock_prefixes], &lock_prefix_va, sizeof(lock_prefix_va)); + current_pos_of_lock_prefixes += sizeof(lock_prefix_va); + } + + { + //Ending null VA + typename PEClassType::BaseSize lock_prefix_va = 0; + memcpy(&raw_data[current_pos_of_lock_prefixes], &lock_prefix_va, sizeof(lock_prefix_va)); + } + } + + //Adjust section raw and virtual sizes + pe.recalculate_section_sizes(image_config_section, auto_strip_last_section); + + image_directory ret(pe.rva_from_section_offset(image_config_section, image_config_data_pos), sizeof(typename PEClassType::ConfigStruct)); + + //If auto-rewrite of PE headers is required + if(save_to_pe_header) + { + pe.set_directory_rva(image_directory_entry_load_config, ret.get_rva()); + pe.set_directory_size(image_directory_entry_load_config, ret.get_size()); + } + + return ret; +} + +} diff --git a/tools/pe_bliss/pe_load_config.h b/tools/pe_bliss/pe_load_config.h new file mode 100644 index 0000000000..cb24072de7 --- /dev/null +++ b/tools/pe_bliss/pe_load_config.h @@ -0,0 +1,184 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <vector> +#include "pe_structures.h" +#include "pe_base.h" +#include "pe_directory.h" + +namespace pe_bliss +{ +//Class representing image configuration information +class image_config_info +{ +public: + typedef std::vector<uint32_t> se_handler_list; + typedef std::vector<uint32_t> lock_prefix_rva_list; + +public: + //Default constructor + image_config_info(); + //Constructors from PE structures (no checks) + template<typename ConfigStructure> + explicit image_config_info(const ConfigStructure& info); + + //Returns the date and time stamp value + uint32_t get_time_stamp() const; + //Returns major version number + uint16_t get_major_version() const; + //Returns minor version number + uint16_t get_minor_version() const; + //Returns clear global flags + uint32_t get_global_flags_clear() const; + //Returns set global flags + uint32_t get_global_flags_set() const; + //Returns critical section default timeout + uint32_t get_critical_section_default_timeout() const; + //Get the size of the minimum block that + //must be freed before it is freed (de-committed), in bytes + uint64_t get_decommit_free_block_threshold() const; + //Returns the size of the minimum total memory + //that must be freed in the process heap before it is freed (de-committed), in bytes + uint64_t get_decommit_total_free_threshold() const; + //Returns VA of a list of addresses where the LOCK prefix is used + uint64_t get_lock_prefix_table_va() const; + //Returns the maximum allocation size, in bytes + uint64_t get_max_allocation_size() const; + //Returns the maximum block size that can be allocated from heap segments, in bytes + uint64_t get_virtual_memory_threshold() const; + //Returns process affinity mask + uint64_t get_process_affinity_mask() const; + //Returns process heap flags + uint32_t get_process_heap_flags() const; + //Returns service pack version (CSDVersion) + uint16_t get_service_pack_version() const; + //Returns VA of edit list (reserved by system) + uint64_t get_edit_list_va() const; + //Returns a pointer to a cookie that is used by Visual C++ or GS implementation + uint64_t get_security_cookie_va() const; + //Returns VA of the sorted table of RVAs of each valid, unique handler in the image + uint64_t get_se_handler_table_va() const; + //Returns the count of unique handlers in the table + uint64_t get_se_handler_count() const; + + //Returns SE Handler RVA list + const se_handler_list& get_se_handler_rvas() const; + + //Returns Lock Prefix RVA list + const lock_prefix_rva_list& get_lock_prefix_rvas() const; + +public: //These functions do not change everything inside image, they are used by PE class + //Also you can use these functions to rebuild image config directory + + //Adds SE Handler RVA to list + void add_se_handler_rva(uint32_t rva); + //Clears SE Handler list + void clear_se_handler_list(); + + //Adds Lock Prefix RVA to list + void add_lock_prefix_rva(uint32_t rva); + //Clears Lock Prefix list + void clear_lock_prefix_list(); + + //Sets the date and time stamp value + void set_time_stamp(uint32_t time_stamp); + //Sets major version number + void set_major_version(uint16_t major_version); + //Sets minor version number + void set_minor_version(uint16_t minor_version); + //Sets clear global flags + void set_global_flags_clear(uint32_t global_flags_clear); + //Sets set global flags + void set_global_flags_set(uint32_t global_flags_set); + //Sets critical section default timeout + void set_critical_section_default_timeout(uint32_t critical_section_default_timeout); + //Sets the size of the minimum block that + //must be freed before it is freed (de-committed), in bytes + void set_decommit_free_block_threshold(uint64_t decommit_free_block_threshold); + //Sets the size of the minimum total memory + //that must be freed in the process heap before it is freed (de-committed), in bytes + void set_decommit_total_free_threshold(uint64_t decommit_total_free_threshold); + //Sets VA of a list of addresses where the LOCK prefix is used + //If you rebuild this list, VA will be re-assigned automatically + void set_lock_prefix_table_va(uint64_t lock_prefix_table_va); + //Sets the maximum allocation size, in bytes + void set_max_allocation_size(uint64_t max_allocation_size); + //Sets the maximum block size that can be allocated from heap segments, in bytes + void set_virtual_memory_threshold(uint64_t virtual_memory_threshold); + //Sets process affinity mask + void set_process_affinity_mask(uint64_t process_affinity_mask); + //Sets process heap flags + void set_process_heap_flags(uint32_t process_heap_flags); + //Sets service pack version (CSDVersion) + void set_service_pack_version(uint16_t service_pack_version); + //Sets VA of edit list (reserved by system) + void set_edit_list_va(uint64_t edit_list_va); + //Sets a pointer to a cookie that is used by Visual C++ or GS implementation + void set_security_cookie_va(uint64_t security_cookie_va); + //Sets VA of the sorted table of RVAs of each valid, unique handler in the image + //If you rebuild this list, VA will be re-assigned automatically + void set_se_handler_table_va(uint64_t se_handler_table_va); + + //Returns SE Handler RVA list + se_handler_list& get_se_handler_rvas(); + + //Returns Lock Prefix RVA list + lock_prefix_rva_list& get_lock_prefix_rvas(); + +private: + uint32_t time_stamp_; + uint16_t major_version_, minor_version_; + uint32_t global_flags_clear_, global_flags_set_; + uint32_t critical_section_default_timeout_; + uint64_t decommit_free_block_threshold_, decommit_total_free_threshold_; + uint64_t lock_prefix_table_va_; + uint64_t max_allocation_size_; + uint64_t virtual_memory_threshold_; + uint64_t process_affinity_mask_; + uint32_t process_heap_flags_; + uint16_t service_pack_version_; + uint64_t edit_list_va_; + uint64_t security_cookie_va_; + uint64_t se_handler_table_va_; + uint64_t se_handler_count_; + + se_handler_list se_handlers_; + lock_prefix_rva_list lock_prefixes_; +}; + +//Returns image config info +//If image does not have config info, throws an exception +const image_config_info get_image_config(const pe_base& pe); + +template<typename PEClassType> +const image_config_info get_image_config_base(const pe_base& pe); + + +//Image config directory rebuilder +//auto_strip_last_section - if true and TLS are placed in the last section, it will be automatically stripped +//If write_se_handlers = true, SE Handlers list will be written just after image config directory structure +//If write_lock_prefixes = true, Lock Prefixes address list will be written just after image config directory structure +const image_directory rebuild_image_config(pe_base& pe, const image_config_info& info, section& image_config_section, uint32_t offset_from_section_start = 0, bool write_se_handlers = true, bool write_lock_prefixes = true, bool save_to_pe_header = true, bool auto_strip_last_section = true); + +template<typename PEClassType> +const image_directory rebuild_image_config_base(pe_base& pe, const image_config_info& info, section& image_config_section, uint32_t offset_from_section_start = 0, bool write_se_handlers = true, bool write_lock_prefixes = true, bool save_to_pe_header = true, bool auto_strip_last_section = true); +} diff --git a/tools/pe_bliss/pe_properties.cpp b/tools/pe_bliss/pe_properties.cpp new file mode 100644 index 0000000000..8d1c2eac43 --- /dev/null +++ b/tools/pe_bliss/pe_properties.cpp @@ -0,0 +1,41 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include "pe_properties.h" + +namespace pe_bliss +{ +//Destructor +pe_properties::~pe_properties() +{} + +//Clears PE characteristics flag +void pe_properties::clear_characteristics_flags(uint16_t flags) +{ + set_characteristics(get_characteristics() & ~flags); +} + +//Sets PE characteristics flag +void pe_properties::set_characteristics_flags(uint16_t flags) +{ + set_characteristics(get_characteristics() | flags); +} +} diff --git a/tools/pe_bliss/pe_properties.h b/tools/pe_bliss/pe_properties.h new file mode 100644 index 0000000000..1db163e8b1 --- /dev/null +++ b/tools/pe_bliss/pe_properties.h @@ -0,0 +1,236 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <memory> +#include "pe_structures.h" + +namespace pe_bliss +{ +class pe_properties +{ +public: //Constructors + virtual std::auto_ptr<pe_properties> duplicate() const = 0; + + //Fills properly PE structures + virtual void create_pe(uint32_t section_alignment, uint16_t subsystem) = 0; + +public: + //Destructor + virtual ~pe_properties(); + + +public: //DIRECTORIES + //Returns true if directory exists + virtual bool directory_exists(uint32_t id) const = 0; + + //Removes directory + virtual void remove_directory(uint32_t id) = 0; + + //Returns directory RVA + virtual uint32_t get_directory_rva(uint32_t id) const = 0; + //Returns directory size + virtual uint32_t get_directory_size(uint32_t id) const = 0; + + //Sets directory RVA (just a value of PE header, no moving occurs) + virtual void set_directory_rva(uint32_t id, uint32_t rva) = 0; + //Sets directory size (just a value of PE header, no moving occurs) + virtual void set_directory_size(uint32_t id, uint32_t size) = 0; + + //Strips only zero DATA_DIRECTORY entries to count = min_count + //Returns resulting number of data directories + //strip_iat_directory - if true, even not empty IAT directory will be stripped + virtual uint32_t strip_data_directories(uint32_t min_count = 1, bool strip_iat_directory = true) = 0; + + +public: //IMAGE + //Returns PE type of this image + virtual pe_type get_pe_type() const = 0; + + +public: //PE HEADER + //Returns image base for PE32 and PE64 respectively + virtual uint32_t get_image_base_32() const = 0; + virtual uint64_t get_image_base_64() const = 0; + + //Sets new image base for PE32 + virtual void set_image_base(uint32_t base) = 0; + //Sets new image base for PE32/PE+ + virtual void set_image_base_64(uint64_t base) = 0; + + //Returns image entry point + virtual uint32_t get_ep() const = 0; + //Sets image entry point + virtual void set_ep(uint32_t new_ep) = 0; + + //Returns file alignment + virtual uint32_t get_file_alignment() const = 0; + //Returns section alignment + virtual uint32_t get_section_alignment() const = 0; + + //Sets heap size commit for PE32 and PE64 respectively + virtual void set_heap_size_commit(uint32_t size) = 0; + virtual void set_heap_size_commit(uint64_t size) = 0; + //Sets heap size reserve for PE32 and PE64 respectively + virtual void set_heap_size_reserve(uint32_t size) = 0; + virtual void set_heap_size_reserve(uint64_t size) = 0; + //Sets stack size commit for PE32 and PE64 respectively + virtual void set_stack_size_commit(uint32_t size) = 0; + virtual void set_stack_size_commit(uint64_t size) = 0; + //Sets stack size reserve for PE32 and PE64 respectively + virtual void set_stack_size_reserve(uint32_t size) = 0; + virtual void set_stack_size_reserve(uint64_t size) = 0; + + //Returns heap size commit for PE32 and PE64 respectively + virtual uint32_t get_heap_size_commit_32() const = 0; + virtual uint64_t get_heap_size_commit_64() const = 0; + //Returns heap size reserve for PE32 and PE64 respectively + virtual uint32_t get_heap_size_reserve_32() const = 0; + virtual uint64_t get_heap_size_reserve_64() const = 0; + //Returns stack size commit for PE32 and PE64 respectively + virtual uint32_t get_stack_size_commit_32() const = 0; + virtual uint64_t get_stack_size_commit_64() const = 0; + //Returns stack size reserve for PE32 and PE64 respectively + virtual uint32_t get_stack_size_reserve_32() const = 0; + virtual uint64_t get_stack_size_reserve_64() const = 0; + + //Returns virtual size of image + virtual uint32_t get_size_of_image() const = 0; + + //Returns number of RVA and sizes (number of DATA_DIRECTORY entries) + virtual uint32_t get_number_of_rvas_and_sizes() const = 0; + //Sets number of RVA and sizes (number of DATA_DIRECTORY entries) + virtual void set_number_of_rvas_and_sizes(uint32_t number) = 0; + + //Returns PE characteristics + virtual uint16_t get_characteristics() const = 0; + //Sets PE characteristics + virtual void set_characteristics(uint16_t ch) = 0; + + //Clears PE characteristics flag + void clear_characteristics_flags(uint16_t flags); + //Sets PE characteristics flag + void set_characteristics_flags(uint16_t flags); + + //Returns size of headers + virtual uint32_t get_size_of_headers() const = 0; + + //Returns subsystem + virtual uint16_t get_subsystem() const = 0; + + //Sets subsystem + virtual void set_subsystem(uint16_t subsystem) = 0; + + //Returns size of optional header + virtual uint16_t get_size_of_optional_header() const = 0; + + //Returns PE signature + virtual uint32_t get_pe_signature() const = 0; + + //Returns PE magic value + virtual uint32_t get_magic() const = 0; + + //Returns checksum of PE file from header + virtual uint32_t get_checksum() const = 0; + + //Sets checksum of PE file + virtual void set_checksum(uint32_t checksum) = 0; + + //Returns timestamp of PE file from header + virtual uint32_t get_time_date_stamp() const = 0; + + //Sets timestamp of PE file + virtual void set_time_date_stamp(uint32_t timestamp) = 0; + + //Returns Machine field value of PE file from header + virtual uint16_t get_machine() const = 0; + + //Sets Machine field value of PE file + virtual void set_machine(uint16_t machine) = 0; + + //Returns DLL Characteristics + virtual uint16_t get_dll_characteristics() const = 0; + + //Sets DLL Characteristics + virtual void set_dll_characteristics(uint16_t characteristics) = 0; + + //Sets required operation system version + virtual void set_os_version(uint16_t major, uint16_t minor) = 0; + + //Returns required operation system version (minor word) + virtual uint16_t get_minor_os_version() const = 0; + + //Returns required operation system version (major word) + virtual uint16_t get_major_os_version() const = 0; + + //Sets required subsystem version + virtual void set_subsystem_version(uint16_t major, uint16_t minor) = 0; + + //Returns required subsystem version (minor word) + virtual uint16_t get_minor_subsystem_version() const = 0; + + //Returns required subsystem version (major word) + virtual uint16_t get_major_subsystem_version() const = 0; + +public: //ADDRESS CONVERTIONS + //Virtual Address (VA) to Relative Virtual Address (RVA) convertions + //for PE32 and PE64 respectively + //bound_check checks integer overflow + virtual uint32_t va_to_rva(uint32_t va, bool bound_check = true) const = 0; + virtual uint32_t va_to_rva(uint64_t va, bool bound_check = true) const = 0; + + //Relative Virtual Address (RVA) to Virtual Address (VA) convertions + //for PE32 and PE64 respectively + virtual uint32_t rva_to_va_32(uint32_t rva) const = 0; + virtual uint64_t rva_to_va_64(uint32_t rva) const = 0; + + +public: //SECTIONS + //Returns number of sections + virtual uint16_t get_number_of_sections() const = 0; + +public: + //Sets number of sections + virtual void set_number_of_sections(uint16_t number) = 0; + //Sets virtual size of image + virtual void set_size_of_image(uint32_t size) = 0; + //Sets size of headers + virtual void set_size_of_headers(uint32_t size) = 0; + //Sets size of optional headers + virtual void set_size_of_optional_header(uint16_t size) = 0; + //Returns nt headers data pointer + virtual char* get_nt_headers_ptr() = 0; + //Returns nt headers data pointer + virtual const char* get_nt_headers_ptr() const = 0; + //Returns size of NT header + virtual uint32_t get_sizeof_nt_header() const = 0; + //Returns size of optional headers + virtual uint32_t get_sizeof_opt_headers() const = 0; + //Sets file alignment (no checks) + virtual void set_file_alignment_unchecked(uint32_t alignment) = 0; + //Sets base of code + virtual void set_base_of_code(uint32_t base) = 0; + //Returns base of code + virtual uint32_t get_base_of_code() const = 0; + //Returns needed PE magic for PE or PE+ (from template parameters) + virtual uint32_t get_needed_magic() const = 0; +}; +} diff --git a/tools/pe_bliss/pe_properties_generic.cpp b/tools/pe_bliss/pe_properties_generic.cpp new file mode 100644 index 0000000000..bcf6f2047d --- /dev/null +++ b/tools/pe_bliss/pe_properties_generic.cpp @@ -0,0 +1,645 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <string.h> +#include "pe_properties_generic.h" +#include "pe_exception.h" +#include "utils.h" + +namespace pe_bliss +{ +using namespace pe_win; + +//Constructor +template<typename PEClassType> +std::auto_ptr<pe_properties> pe_properties_generic<PEClassType>::duplicate() const +{ + return std::auto_ptr<pe_properties>(new pe_properties_generic<PEClassType>(*this)); +} + +//Fills properly PE structures +template<typename PEClassType> +void pe_properties_generic<PEClassType>::create_pe(uint32_t section_alignment, uint16_t subsystem) +{ + memset(&nt_headers_, 0, sizeof(nt_headers_)); + nt_headers_.Signature = 0x4550; //"PE" + nt_headers_.FileHeader.Machine = 0x14C; //i386 + nt_headers_.FileHeader.SizeOfOptionalHeader = sizeof(nt_headers_.OptionalHeader); + nt_headers_.OptionalHeader.Magic = PEClassType::Id; + nt_headers_.OptionalHeader.ImageBase = 0x400000; + nt_headers_.OptionalHeader.SectionAlignment = section_alignment; + nt_headers_.OptionalHeader.FileAlignment = 0x200; + nt_headers_.OptionalHeader.SizeOfHeaders = 1024; + nt_headers_.OptionalHeader.Subsystem = subsystem; + nt_headers_.OptionalHeader.SizeOfHeapReserve = 0x100000; + nt_headers_.OptionalHeader.SizeOfHeapCommit = 0x1000; + nt_headers_.OptionalHeader.SizeOfStackReserve = 0x100000; + nt_headers_.OptionalHeader.SizeOfStackCommit = 0x1000; + nt_headers_.OptionalHeader.NumberOfRvaAndSizes = 0x10; +} + +//Duplicate +template<typename PEClassType> +pe_properties_generic<PEClassType>::~pe_properties_generic() +{} + +//Returns true if directory exists +template<typename PEClassType> +bool pe_properties_generic<PEClassType>::directory_exists(uint32_t id) const +{ + return (nt_headers_.OptionalHeader.NumberOfRvaAndSizes - 1) >= id && + nt_headers_.OptionalHeader.DataDirectory[id].VirtualAddress; +} + +//Removes directory +template<typename PEClassType> +void pe_properties_generic<PEClassType>::remove_directory(uint32_t id) +{ + if(directory_exists(id)) + { + nt_headers_.OptionalHeader.DataDirectory[id].VirtualAddress = 0; + nt_headers_.OptionalHeader.DataDirectory[id].Size = 0; + + if(id == image_directory_entry_basereloc) + { + set_characteristics_flags(image_file_relocs_stripped); + set_dll_characteristics(get_dll_characteristics() & ~image_dllcharacteristics_dynamic_base); + } + else if(id == image_directory_entry_export) + { + clear_characteristics_flags(image_file_dll); + } + } +} + +//Returns directory RVA +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_directory_rva(uint32_t id) const +{ + //Check if directory exists + if(nt_headers_.OptionalHeader.NumberOfRvaAndSizes <= id) + throw pe_exception("Specified directory does not exist", pe_exception::directory_does_not_exist); + + return nt_headers_.OptionalHeader.DataDirectory[id].VirtualAddress; +} + +//Returns directory size +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_directory_rva(uint32_t id, uint32_t va) +{ + //Check if directory exists + if(nt_headers_.OptionalHeader.NumberOfRvaAndSizes <= id) + throw pe_exception("Specified directory does not exist", pe_exception::directory_does_not_exist); + + nt_headers_.OptionalHeader.DataDirectory[id].VirtualAddress = va; +} + +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_directory_size(uint32_t id, uint32_t size) +{ + //Check if directory exists + if(nt_headers_.OptionalHeader.NumberOfRvaAndSizes <= id) + throw pe_exception("Specified directory does not exist", pe_exception::directory_does_not_exist); + + nt_headers_.OptionalHeader.DataDirectory[id].Size = size; +} + +//Returns directory size +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_directory_size(uint32_t id) const +{ + //Check if directory exists + if(nt_headers_.OptionalHeader.NumberOfRvaAndSizes <= id) + throw pe_exception("Specified directory does not exist", pe_exception::directory_does_not_exist); + + return nt_headers_.OptionalHeader.DataDirectory[id].Size; +} + +//Strips only zero DATA_DIRECTORY entries to count = min_count +//Returns resulting number of data directories +//strip_iat_directory - if true, even not empty IAT directory will be stripped +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::strip_data_directories(uint32_t min_count, bool strip_iat_directory) +{ + int i = nt_headers_.OptionalHeader.NumberOfRvaAndSizes - 1; + + //Enumerate all data directories from the end + for(; i >= 0; i--) + { + //If directory exists, break + if(nt_headers_.OptionalHeader.DataDirectory[i].VirtualAddress && (static_cast<uint32_t>(i) != image_directory_entry_iat || !strip_iat_directory)) + break; + + if(i <= static_cast<int>(min_count) - 2) + break; + } + + if(i == image_numberof_directory_entries - 1) + return image_numberof_directory_entries; + + //Return new number of data directories + return nt_headers_.OptionalHeader.NumberOfRvaAndSizes = i + 1; +} + +//Returns image base for PE32 +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_image_base_32() const +{ + return static_cast<uint32_t>(nt_headers_.OptionalHeader.ImageBase); +} + +//Returns image base for PE32/PE64 +template<typename PEClassType> +uint64_t pe_properties_generic<PEClassType>::get_image_base_64() const +{ + return static_cast<uint64_t>(nt_headers_.OptionalHeader.ImageBase); +} + +//Sets new image base +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_image_base(uint32_t base) +{ + nt_headers_.OptionalHeader.ImageBase = base; +} + +//Sets new image base +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_image_base_64(uint64_t base) +{ + nt_headers_.OptionalHeader.ImageBase = static_cast<typename PEClassType::BaseSize>(base); +} + +//Returns image entry point +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_ep() const +{ + return nt_headers_.OptionalHeader.AddressOfEntryPoint; +} + +//Sets image entry point +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_ep(uint32_t new_ep) +{ + nt_headers_.OptionalHeader.AddressOfEntryPoint = new_ep; +} + +//Returns file alignment +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_file_alignment() const +{ + return nt_headers_.OptionalHeader.FileAlignment; +} + +//Returns section alignment +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_section_alignment() const +{ + return nt_headers_.OptionalHeader.SectionAlignment; +} + +//Sets heap size commit for PE32 +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_heap_size_commit(uint32_t size) +{ + nt_headers_.OptionalHeader.SizeOfHeapCommit = static_cast<typename PEClassType::BaseSize>(size); +} + +//Sets heap size commit for PE32/PE64 +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_heap_size_commit(uint64_t size) +{ + nt_headers_.OptionalHeader.SizeOfHeapCommit = static_cast<typename PEClassType::BaseSize>(size); +} + +//Sets heap size reserve for PE32 +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_heap_size_reserve(uint32_t size) +{ + nt_headers_.OptionalHeader.SizeOfHeapReserve = static_cast<typename PEClassType::BaseSize>(size); +} + +//Sets heap size reserve for PE32/PE64 +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_heap_size_reserve(uint64_t size) +{ + nt_headers_.OptionalHeader.SizeOfHeapReserve = static_cast<typename PEClassType::BaseSize>(size); +} + +//Sets stack size commit for PE32 +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_stack_size_commit(uint32_t size) +{ + nt_headers_.OptionalHeader.SizeOfStackCommit = static_cast<typename PEClassType::BaseSize>(size); +} + +//Sets stack size commit for PE32/PE64 +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_stack_size_commit(uint64_t size) +{ + nt_headers_.OptionalHeader.SizeOfStackCommit = static_cast<typename PEClassType::BaseSize>(size); +} + +//Sets stack size reserve for PE32 +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_stack_size_reserve(uint32_t size) +{ + nt_headers_.OptionalHeader.SizeOfStackReserve = static_cast<typename PEClassType::BaseSize>(size); +} + +//Sets stack size reserve for PE32/PE64 +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_stack_size_reserve(uint64_t size) +{ + nt_headers_.OptionalHeader.SizeOfStackReserve = static_cast<typename PEClassType::BaseSize>(size); +} + +//Returns heap size commit for PE32 +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_heap_size_commit_32() const +{ + return static_cast<uint32_t>(nt_headers_.OptionalHeader.SizeOfHeapCommit); +} + +//Returns heap size commit for PE32/PE64 +template<typename PEClassType> +uint64_t pe_properties_generic<PEClassType>::get_heap_size_commit_64() const +{ + return static_cast<uint64_t>(nt_headers_.OptionalHeader.SizeOfHeapCommit); +} + +//Returns heap size reserve for PE32 +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_heap_size_reserve_32() const +{ + return static_cast<uint32_t>(nt_headers_.OptionalHeader.SizeOfHeapReserve); +} + +//Returns heap size reserve for PE32/PE64 +template<typename PEClassType> +uint64_t pe_properties_generic<PEClassType>::get_heap_size_reserve_64() const +{ + return static_cast<uint64_t>(nt_headers_.OptionalHeader.SizeOfHeapReserve); +} + +//Returns stack size commit for PE32 +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_stack_size_commit_32() const +{ + return static_cast<uint32_t>(nt_headers_.OptionalHeader.SizeOfStackCommit); +} + +//Returns stack size commit for PE32/PE64 +template<typename PEClassType> +uint64_t pe_properties_generic<PEClassType>::get_stack_size_commit_64() const +{ + return static_cast<uint64_t>(nt_headers_.OptionalHeader.SizeOfStackCommit); +} + +//Returns stack size reserve for PE32 +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_stack_size_reserve_32() const +{ + return static_cast<uint32_t>(nt_headers_.OptionalHeader.SizeOfStackReserve); +} + +//Returns stack size reserve for PE32/PE64 +template<typename PEClassType> +uint64_t pe_properties_generic<PEClassType>::get_stack_size_reserve_64() const +{ + return static_cast<uint64_t>(nt_headers_.OptionalHeader.SizeOfStackReserve); +} + +//Returns virtual size of image +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_size_of_image() const +{ + return nt_headers_.OptionalHeader.SizeOfImage; +} + +//Returns number of RVA and sizes (number of DATA_DIRECTORY entries) +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_number_of_rvas_and_sizes() const +{ + return nt_headers_.OptionalHeader.NumberOfRvaAndSizes; +} + +//Sets number of RVA and sizes (number of DATA_DIRECTORY entries) +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_number_of_rvas_and_sizes(uint32_t number) +{ + nt_headers_.OptionalHeader.NumberOfRvaAndSizes = number; +} + +//Returns PE characteristics +template<typename PEClassType> +uint16_t pe_properties_generic<PEClassType>::get_characteristics() const +{ + return nt_headers_.FileHeader.Characteristics; +} + +//Returns checksum of PE file from header +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_checksum() const +{ + return nt_headers_.OptionalHeader.CheckSum; +} + +//Sets checksum of PE file +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_checksum(uint32_t checksum) +{ + nt_headers_.OptionalHeader.CheckSum = checksum; +} + +//Returns DLL Characteristics +template<typename PEClassType> +uint16_t pe_properties_generic<PEClassType>::get_dll_characteristics() const +{ + return nt_headers_.OptionalHeader.DllCharacteristics; +} + +//Returns timestamp of PE file from header +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_time_date_stamp() const +{ + return nt_headers_.FileHeader.TimeDateStamp; +} + +//Sets timestamp of PE file +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_time_date_stamp(uint32_t timestamp) +{ + nt_headers_.FileHeader.TimeDateStamp = timestamp; +} + +//Sets DLL Characteristics +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_dll_characteristics(uint16_t characteristics) +{ + nt_headers_.OptionalHeader.DllCharacteristics = characteristics; +} + +//Returns Machine field value of PE file from header +template<typename PEClassType> +uint16_t pe_properties_generic<PEClassType>::get_machine() const +{ + return nt_headers_.FileHeader.Machine; +} + +//Sets Machine field value of PE file +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_machine(uint16_t machine) +{ + nt_headers_.FileHeader.Machine = machine; +} + +//Sets PE characteristics +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_characteristics(uint16_t ch) +{ + nt_headers_.FileHeader.Characteristics = ch; +} + +//Returns size of headers +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_size_of_headers() const +{ + return nt_headers_.OptionalHeader.SizeOfHeaders; +} + +//Returns subsystem +template<typename PEClassType> +uint16_t pe_properties_generic<PEClassType>::get_subsystem() const +{ + return nt_headers_.OptionalHeader.Subsystem; +} + +//Sets subsystem +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_subsystem(uint16_t subsystem) +{ + nt_headers_.OptionalHeader.Subsystem = subsystem; +} + +//Returns size of optional header +template<typename PEClassType> +uint16_t pe_properties_generic<PEClassType>::get_size_of_optional_header() const +{ + return nt_headers_.FileHeader.SizeOfOptionalHeader; +} + +//Returns PE signature +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_pe_signature() const +{ + return nt_headers_.Signature; +} + +//Returns PE magic value +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_magic() const +{ + return nt_headers_.OptionalHeader.Magic; +} + +//Sets required operation system version +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_os_version(uint16_t major, uint16_t minor) +{ + nt_headers_.OptionalHeader.MinorOperatingSystemVersion = minor; + nt_headers_.OptionalHeader.MajorOperatingSystemVersion = major; +} + +//Returns required operation system version (minor word) +template<typename PEClassType> +uint16_t pe_properties_generic<PEClassType>::get_minor_os_version() const +{ + return nt_headers_.OptionalHeader.MinorOperatingSystemVersion; +} + +//Returns required operation system version (major word) +template<typename PEClassType> +uint16_t pe_properties_generic<PEClassType>::get_major_os_version() const +{ + return nt_headers_.OptionalHeader.MajorOperatingSystemVersion; +} + +//Sets required subsystem version +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_subsystem_version(uint16_t major, uint16_t minor) +{ + nt_headers_.OptionalHeader.MinorSubsystemVersion = minor; + nt_headers_.OptionalHeader.MajorSubsystemVersion = major; +} + +//Returns required subsystem version (minor word) +template<typename PEClassType> +uint16_t pe_properties_generic<PEClassType>::get_minor_subsystem_version() const +{ + return nt_headers_.OptionalHeader.MinorSubsystemVersion; +} + +//Returns required subsystem version (major word) +template<typename PEClassType> +uint16_t pe_properties_generic<PEClassType>::get_major_subsystem_version() const +{ + return nt_headers_.OptionalHeader.MajorSubsystemVersion; +} + +//Virtual Address (VA) to Relative Virtual Address (RVA) convertions for PE32 +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::va_to_rva(uint32_t va, bool bound_check) const +{ + if(bound_check && static_cast<uint64_t>(va) - nt_headers_.OptionalHeader.ImageBase > pe_utils::max_dword) + throw pe_exception("Incorrect address conversion", pe_exception::incorrect_address_conversion); + + return static_cast<uint32_t>(va - nt_headers_.OptionalHeader.ImageBase); +} + +//Virtual Address (VA) to Relative Virtual Address (RVA) convertions for PE32/PE64 +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::va_to_rva(uint64_t va, bool bound_check) const +{ + if(bound_check && va - nt_headers_.OptionalHeader.ImageBase > pe_utils::max_dword) + throw pe_exception("Incorrect address conversion", pe_exception::incorrect_address_conversion); + + return static_cast<uint32_t>(va - nt_headers_.OptionalHeader.ImageBase); +} + +//Relative Virtual Address (RVA) to Virtual Address (VA) convertions for PE32 +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::rva_to_va_32(uint32_t rva) const +{ + if(!pe_utils::is_sum_safe(rva, static_cast<uint32_t>(nt_headers_.OptionalHeader.ImageBase))) + throw pe_exception("Incorrect address conversion", pe_exception::incorrect_address_conversion); + + return static_cast<uint32_t>(rva + nt_headers_.OptionalHeader.ImageBase); +} + +//Relative Virtual Address (RVA) to Virtual Address (VA) convertions for PE32/PE64 +template<typename PEClassType> +uint64_t pe_properties_generic<PEClassType>::rva_to_va_64(uint32_t rva) const +{ + return static_cast<uint64_t>(rva) + nt_headers_.OptionalHeader.ImageBase; +} + +//Returns number of sections +template<typename PEClassType> +uint16_t pe_properties_generic<PEClassType>::get_number_of_sections() const +{ + return nt_headers_.FileHeader.NumberOfSections; +} + +//Sets number of sections +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_number_of_sections(uint16_t number) +{ + nt_headers_.FileHeader.NumberOfSections = number; +} + +//Sets virtual size of image +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_size_of_image(uint32_t size) +{ + nt_headers_.OptionalHeader.SizeOfImage = size; +} + +//Sets size of headers +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_size_of_headers(uint32_t size) +{ + nt_headers_.OptionalHeader.SizeOfHeaders = size; +} + +//Sets size of optional headers +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_size_of_optional_header(uint16_t size) +{ + nt_headers_.FileHeader.SizeOfOptionalHeader = size; +} + +//Returns nt headers data pointer +template<typename PEClassType> +char* pe_properties_generic<PEClassType>::get_nt_headers_ptr() +{ + return reinterpret_cast<char*>(&nt_headers_); +} + +//Returns nt headers data pointer +template<typename PEClassType> +const char* pe_properties_generic<PEClassType>::get_nt_headers_ptr() const +{ + return reinterpret_cast<const char*>(&nt_headers_); +} + +//Returns size of NT header +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_sizeof_nt_header() const +{ + return sizeof(typename PEClassType::NtHeaders); +} + +//Returns size of optional headers +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_sizeof_opt_headers() const +{ + return sizeof(typename PEClassType::OptHeaders); +} + +//Sets file alignment (no checks) +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_file_alignment_unchecked(uint32_t alignment) +{ + nt_headers_.OptionalHeader.FileAlignment = alignment; +} + +//Sets base of code +template<typename PEClassType> +void pe_properties_generic<PEClassType>::set_base_of_code(uint32_t base) +{ + nt_headers_.OptionalHeader.BaseOfCode = base; +} + +//Returns base of code +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_base_of_code() const +{ + return nt_headers_.OptionalHeader.BaseOfCode; +} + +//Returns needed PE magic for PE or PE+ (from template parameters) +template<typename PEClassType> +uint32_t pe_properties_generic<PEClassType>::get_needed_magic() const +{ + return PEClassType::Id; +} + +//Returns PE type of this image +template<typename PEClassType> +pe_type pe_properties_generic<PEClassType>::get_pe_type() const +{ + return PEClassType::Id == image_nt_optional_hdr32_magic ? pe_type_32 : pe_type_64; +} + +//Two used instantiations for PE32 (PE) and PE64 (PE+) +template class pe_properties_generic<pe_types_class_32>; +template class pe_properties_generic<pe_types_class_64>; +} diff --git a/tools/pe_bliss/pe_properties_generic.h b/tools/pe_bliss/pe_properties_generic.h new file mode 100644 index 0000000000..4ff906803c --- /dev/null +++ b/tools/pe_bliss/pe_properties_generic.h @@ -0,0 +1,277 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include "pe_properties.h" + +namespace pe_bliss +{ +//Helper class to reduce code size and ease its editing +template< + typename NtHeadersType, + typename OptHeadersType, + uint16_t IdVal, + typename BaseSizeType, + BaseSizeType ImportSnapFlagVal, + typename TLSStructType, + typename ConfigStructType> +class pe_types +{ +public: + typedef NtHeadersType NtHeaders; //NT HEADERS type + typedef OptHeadersType OptHeaders; //NT OPTIONAL HEADER type + typedef BaseSizeType BaseSize; //Base size of different values: DWORD or ULONGLONG + typedef TLSStructType TLSStruct; //TLS structure type + typedef ConfigStructType ConfigStruct; //Configuration structure type + + static const uint16_t Id = IdVal; //Magic of PE or PE+ + static const BaseSize ImportSnapFlag = ImportSnapFlagVal; //Import snap flag value +}; + +//Portable Executable derived class for PE and PE+ +//Describes PE/PE+ dependent things +template<typename PEClassType> +class pe_properties_generic : public pe_properties +{ +public: //Constructor + virtual std::auto_ptr<pe_properties> duplicate() const; + + //Fills properly PE structures + virtual void create_pe(uint32_t section_alignment, uint16_t subsystem); + +public: + //Destructor + virtual ~pe_properties_generic(); + + +public: //DIRECTORIES + //Returns true if directory exists + virtual bool directory_exists(uint32_t id) const; + + //Removes directory + virtual void remove_directory(uint32_t id); + + //Returns directory RVA + virtual uint32_t get_directory_rva(uint32_t id) const; + //Returns directory size + virtual uint32_t get_directory_size(uint32_t id) const; + + //Sets directory RVA (just a value of PE header, no moving occurs) + virtual void set_directory_rva(uint32_t id, uint32_t rva); + //Sets directory size (just a value of PE header, no moving occurs) + virtual void set_directory_size(uint32_t id, uint32_t size); + + //Strips only zero DATA_DIRECTORY entries to count = min_count + //Returns resulting number of data directories + //strip_iat_directory - if true, even not empty IAT directory will be stripped + virtual uint32_t strip_data_directories(uint32_t min_count = 1, bool strip_iat_directory = true); + + +public: //IMAGE + //Returns PE type of this image + virtual pe_type get_pe_type() const; + + +public: //PE HEADER + //Returns image base for PE32 and PE64 respectively + virtual uint32_t get_image_base_32() const; + virtual uint64_t get_image_base_64() const; + + //Sets new image base for PE32 + virtual void set_image_base(uint32_t base); + //Sets new image base for PE32/PE+ + virtual void set_image_base_64(uint64_t base); + + //Returns image entry point + virtual uint32_t get_ep() const; + //Sets image entry point + virtual void set_ep(uint32_t new_ep); + + //Returns file alignment + virtual uint32_t get_file_alignment() const; + //Returns section alignment + virtual uint32_t get_section_alignment() const; + + //Sets heap size commit for PE32 and PE64 respectively + virtual void set_heap_size_commit(uint32_t size); + virtual void set_heap_size_commit(uint64_t size); + //Sets heap size reserve for PE32 and PE64 respectively + virtual void set_heap_size_reserve(uint32_t size); + virtual void set_heap_size_reserve(uint64_t size); + //Sets stack size commit for PE32 and PE64 respectively + virtual void set_stack_size_commit(uint32_t size); + virtual void set_stack_size_commit(uint64_t size); + //Sets stack size reserve for PE32 and PE64 respectively + virtual void set_stack_size_reserve(uint32_t size); + virtual void set_stack_size_reserve(uint64_t size); + + //Returns heap size commit for PE32 and PE64 respectively + virtual uint32_t get_heap_size_commit_32() const; + virtual uint64_t get_heap_size_commit_64() const; + //Returns heap size reserve for PE32 and PE64 respectively + virtual uint32_t get_heap_size_reserve_32() const; + virtual uint64_t get_heap_size_reserve_64() const; + //Returns stack size commit for PE32 and PE64 respectively + virtual uint32_t get_stack_size_commit_32() const; + virtual uint64_t get_stack_size_commit_64() const; + //Returns stack size reserve for PE32 and PE64 respectively + virtual uint32_t get_stack_size_reserve_32() const; + virtual uint64_t get_stack_size_reserve_64() const; + + //Returns virtual size of image + virtual uint32_t get_size_of_image() const; + + //Returns number of RVA and sizes (number of DATA_DIRECTORY entries) + virtual uint32_t get_number_of_rvas_and_sizes() const; + //Sets number of RVA and sizes (number of DATA_DIRECTORY entries) + virtual void set_number_of_rvas_and_sizes(uint32_t number); + + //Returns PE characteristics + virtual uint16_t get_characteristics() const; + //Sets PE characteristics + virtual void set_characteristics(uint16_t ch); + + //Returns size of headers + virtual uint32_t get_size_of_headers() const; + + //Returns subsystem + virtual uint16_t get_subsystem() const; + + //Sets subsystem + virtual void set_subsystem(uint16_t subsystem); + + //Returns size of optional header + virtual uint16_t get_size_of_optional_header() const; + + //Returns PE signature + virtual uint32_t get_pe_signature() const; + + //Returns PE magic value + virtual uint32_t get_magic() const; + + //Returns checksum of PE file from header + virtual uint32_t get_checksum() const; + + //Sets checksum of PE file + virtual void set_checksum(uint32_t checksum); + + //Returns timestamp of PE file from header + virtual uint32_t get_time_date_stamp() const; + + //Sets timestamp of PE file + virtual void set_time_date_stamp(uint32_t timestamp); + + //Returns Machine field value of PE file from header + virtual uint16_t get_machine() const; + + //Sets Machine field value of PE file + virtual void set_machine(uint16_t machine); + + //Returns DLL Characteristics + virtual uint16_t get_dll_characteristics() const; + + //Sets DLL Characteristics + virtual void set_dll_characteristics(uint16_t characteristics); + + //Sets required operation system version + virtual void set_os_version(uint16_t major, uint16_t minor); + + //Returns required operation system version (minor word) + virtual uint16_t get_minor_os_version() const; + + //Returns required operation system version (major word) + virtual uint16_t get_major_os_version() const; + + //Sets required subsystem version + virtual void set_subsystem_version(uint16_t major, uint16_t minor); + + //Returns required subsystem version (minor word) + virtual uint16_t get_minor_subsystem_version() const; + + //Returns required subsystem version (major word) + virtual uint16_t get_major_subsystem_version() const; + +public: //ADDRESS CONVERTIONS + //Virtual Address (VA) to Relative Virtual Address (RVA) convertions + //for PE32 and PE64 respectively + //bound_check checks integer overflow + virtual uint32_t va_to_rva(uint32_t va, bool bound_check = true) const; + virtual uint32_t va_to_rva(uint64_t va, bool bound_check = true) const; + + //Relative Virtual Address (RVA) to Virtual Address (VA) convertions + //for PE32 and PE64 respectively + virtual uint32_t rva_to_va_32(uint32_t rva) const; + virtual uint64_t rva_to_va_64(uint32_t rva) const; + + +public: //SECTIONS + //Returns number of sections + virtual uint16_t get_number_of_sections() const; + +protected: + typename PEClassType::NtHeaders nt_headers_; //NT headers (PE32 or PE64) + +public: + //Sets number of sections + virtual void set_number_of_sections(uint16_t number); + //Sets virtual size of image + virtual void set_size_of_image(uint32_t size); + //Sets size of headers + virtual void set_size_of_headers(uint32_t size); + //Sets size of optional headers + virtual void set_size_of_optional_header(uint16_t size); + //Returns nt headers data pointer + virtual char* get_nt_headers_ptr(); + //Returns nt headers data pointer + virtual const char* get_nt_headers_ptr() const; + //Returns size of NT header + virtual uint32_t get_sizeof_nt_header() const; + //Returns size of optional headers + virtual uint32_t get_sizeof_opt_headers() const; + //Sets file alignment (no checks) + virtual void set_file_alignment_unchecked(uint32_t alignment); + //Sets base of code + virtual void set_base_of_code(uint32_t base); + //Returns base of code + virtual uint32_t get_base_of_code() const; + //Returns needed PE magic for PE or PE+ (from template parameters) + virtual uint32_t get_needed_magic() const; +}; + +//Two used typedefs for PE32 (PE) and PE64 (PE+) +typedef pe_types<pe_win::image_nt_headers32, + pe_win::image_optional_header32, + pe_win::image_nt_optional_hdr32_magic, + uint32_t, + pe_win::image_ordinal_flag32, + pe_win::image_tls_directory32, + pe_win::image_load_config_directory32> pe_types_class_32; + +typedef pe_types<pe_win::image_nt_headers64, + pe_win::image_optional_header64, + pe_win::image_nt_optional_hdr64_magic, + uint64_t, + pe_win::image_ordinal_flag64, + pe_win::image_tls_directory64, + pe_win::image_load_config_directory64> pe_types_class_64; + +typedef pe_properties_generic<pe_types_class_32> pe_properties_32; +typedef pe_properties_generic<pe_types_class_64> pe_properties_64; +} diff --git a/tools/pe_bliss/pe_rebuilder.cpp b/tools/pe_bliss/pe_rebuilder.cpp new file mode 100644 index 0000000000..faf5803b8c --- /dev/null +++ b/tools/pe_bliss/pe_rebuilder.cpp @@ -0,0 +1,214 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include "pe_rebuilder.h" +#include "pe_base.h" +#include "pe_structures.h" +#include "pe_exception.h" + +namespace pe_bliss +{ +using namespace pe_win; + +//Rebuilds PE image headers +//If strip_dos_header is true, DOS headers partially will be used for PE headers +//If change_size_of_headers == true, SizeOfHeaders will be recalculated automatically +//If save_bound_import == true, existing bound import directory will be saved correctly (because some compilers and bind.exe put it to PE headers) +void rebuild_pe(pe_base& pe, image_dos_header& dos_header, bool strip_dos_header, bool change_size_of_headers, bool save_bound_import) +{ + dos_header = pe.get_dos_header(); + + if(strip_dos_header) + { + //Strip stub overlay + pe.strip_stub_overlay(); + //BaseOfCode NT Headers field now overlaps + //e_lfanew field, so we're acrually setting + //e_lfanew with this call + pe.set_base_of_code(8 * sizeof(uint16_t)); + } + else + { + //Set start of PE headers + dos_header.e_lfanew = sizeof(image_dos_header) + + pe_utils::align_up(static_cast<uint32_t>(pe.get_stub_overlay().size()), sizeof(uint32_t)); + } + + section_list& sections = pe.get_image_sections(); + + //Calculate pointer to section data + size_t ptr_to_section_data = (strip_dos_header ? 8 * sizeof(uint16_t) : sizeof(image_dos_header)) + pe.get_sizeof_nt_header() + + pe_utils::align_up(pe.get_stub_overlay().size(), sizeof(uint32_t)) + - sizeof(image_data_directory) * (image_numberof_directory_entries - pe.get_number_of_rvas_and_sizes()) + + sections.size() * sizeof(image_section_header); + + if(save_bound_import && pe.has_bound_import()) + { + //It will be aligned to DWORD, because we're aligning to DWORD everything above it + pe.set_directory_rva(image_directory_entry_bound_import, static_cast<uint32_t>(ptr_to_section_data)); + ptr_to_section_data += pe.get_directory_size(image_directory_entry_bound_import); + } + + ptr_to_section_data = pe_utils::align_up(ptr_to_section_data, pe.get_file_alignment()); + + //Set size of headers and size of optional header + if(change_size_of_headers) + { + if(!pe.get_image_sections().empty()) + { + if(static_cast<uint32_t>(ptr_to_section_data) > (*sections.begin()).get_virtual_address()) + throw pe_exception("Headers of PE file are too long. Try to strip STUB or don't build bound import", pe_exception::cannot_rebuild_image); + } + + pe.set_size_of_headers(static_cast<uint32_t>(ptr_to_section_data)); + } + + //Set number of sections in PE header + pe.update_number_of_sections(); + + pe.update_image_size(); + + pe.set_size_of_optional_header(static_cast<uint16_t>(pe.get_sizeof_opt_headers() + - sizeof(image_data_directory) * (image_numberof_directory_entries - pe.get_number_of_rvas_and_sizes()))); + + //Recalculate pointer to raw data according to section list + for(section_list::iterator it = sections.begin(); it != sections.end(); ++it) + { + //Save section headers PointerToRawData + (*it).set_pointer_to_raw_data(static_cast<uint32_t>(ptr_to_section_data)); + ptr_to_section_data += (*it).get_aligned_raw_size(pe.get_file_alignment()); + } +} + +//Rebuild PE image and write it to "out" ostream +//If strip_dos_header is true, DOS headers partially will be used for PE headers +//If change_size_of_headers == true, SizeOfHeaders will be recalculated automatically +//If save_bound_import == true, existing bound import directory will be saved correctly (because some compilers and bind.exe put it to PE headers) +void rebuild_pe(pe_base& pe, std::ostream& out, bool strip_dos_header, bool change_size_of_headers, bool save_bound_import) +{ + if(out.bad()) + throw pe_exception("Stream is bad", pe_exception::stream_is_bad); + + if(save_bound_import && pe.has_bound_import()) + { + if(pe.section_data_length_from_rva(pe.get_directory_rva(image_directory_entry_bound_import), pe.get_directory_rva(image_directory_entry_bound_import), section_data_raw, true) + < pe.get_directory_size(image_directory_entry_bound_import)) + throw pe_exception("Incorrect bound import directory", pe_exception::incorrect_bound_import_directory); + } + + //Change ostream state + out.exceptions(std::ios::goodbit); + out.clear(); + + uint32_t original_bound_import_rva = pe.has_bound_import() ? pe.get_directory_rva(image_directory_entry_bound_import) : 0; + if(original_bound_import_rva && original_bound_import_rva > pe.get_size_of_headers()) + { + //No need to do anything with bound import directory + //if it is placed inside of any section, not headers + original_bound_import_rva = 0; + save_bound_import = false; + } + + { + image_dos_header dos_header; + + //Rebuild PE image headers + rebuild_pe(pe, dos_header, strip_dos_header, change_size_of_headers, save_bound_import); + + //Write DOS header + out.write(reinterpret_cast<const char*>(&dos_header), strip_dos_header ? 8 * sizeof(uint16_t) : sizeof(image_dos_header)); + } + + //If we have stub overlay, write it too + { + const std::string& stub = pe.get_stub_overlay(); + if(stub.size()) + { + out.write(stub.data(), stub.size()); + size_t aligned_size = pe_utils::align_up(stub.size(), sizeof(uint32_t)); + //Align PE header, which is right after rich overlay + while(aligned_size > stub.size()) + { + out.put('\0'); + --aligned_size; + } + } + } + + //Write NT headers + out.write(static_cast<const pe_base&>(pe).get_nt_headers_ptr(), pe.get_sizeof_nt_header() + - sizeof(image_data_directory) * (image_numberof_directory_entries - pe.get_number_of_rvas_and_sizes())); + + //Write section headers + const section_list& sections = pe.get_image_sections(); + for(section_list::const_iterator it = sections.begin(); it != sections.end(); ++it) + { + if(it == sections.end() - 1) //If last section encountered + { + image_section_header header((*it).get_raw_header()); + header.SizeOfRawData = static_cast<uint32_t>((*it).get_raw_data().length()); //Set non-aligned actual data length for it + out.write(reinterpret_cast<const char*>(&header), sizeof(image_section_header)); + } + else + { + out.write(reinterpret_cast<const char*>(&(*it).get_raw_header()), sizeof(image_section_header)); + } + } + + //Write bound import data if requested + if(save_bound_import && pe.has_bound_import()) + { + out.write(pe.section_data_from_rva(original_bound_import_rva, section_data_raw, true), + pe.get_directory_size(image_directory_entry_bound_import)); + } + + //Write section data finally + for(section_list::const_iterator it = sections.begin(); it != sections.end(); ++it) + { + const section& s = *it; + + std::streamoff wpos = out.tellp(); + + //Fill unused overlay data between sections with null bytes + for(unsigned int i = 0; i < s.get_pointer_to_raw_data() - wpos; i++) + out.put(0); + + //Write raw section data + out.write(s.get_raw_data().data(), s.get_raw_data().length()); + } +} + +//Rebuild PE image and write it to "out" file +//If strip_dos_header is true, DOS headers partially will be used for PE headers +//If change_size_of_headers == true, SizeOfHeaders will be recalculated automatically +//If save_bound_import == true, existing bound import directory will be saved correctly (because some compilers and bind.exe put it to PE headers) +void rebuild_pe(pe_base& pe, const char* out, bool strip_dos_header, bool change_size_of_headers, bool save_bound_import) +{ + std::ofstream pe_file(out, std::ios::out | std::ios::binary | std::ios::trunc); + if(!pe_file) + { + throw pe_exception("Error in open file.", pe_exception::stream_is_bad); + } + rebuild_pe(pe, pe_file, strip_dos_header, change_size_of_headers, save_bound_import); +} + + +} diff --git a/tools/pe_bliss/pe_rebuilder.h b/tools/pe_bliss/pe_rebuilder.h new file mode 100644 index 0000000000..319807e5c9 --- /dev/null +++ b/tools/pe_bliss/pe_rebuilder.h @@ -0,0 +1,40 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <ostream> +#include <fstream> + +namespace pe_bliss +{ +class pe_base; +//Rebuilds PE image, writes resulting image to ostream "out". If strip_dos_header == true, DOS header will be stripped a little +//If change_size_of_headers == true, SizeOfHeaders will be recalculated automatically +//If save_bound_import == true, existing bound import directory will be saved correctly (because some compilers and bind.exe put it to PE headers) +void rebuild_pe(pe_base& pe, std::ostream& out, bool strip_dos_header = false, bool change_size_of_headers = true, bool save_bound_import = true); + +//Rebuild PE image and write it to "out" file +//If strip_dos_header is true, DOS headers partially will be used for PE headers +//If change_size_of_headers == true, SizeOfHeaders will be recalculated automatically +//If save_bound_import == true, existing bound import directory will be saved correctly (because some compilers and bind.exe put it to PE headers) +void rebuild_pe(pe_base& pe, const char* out, bool strip_dos_header = false, bool change_size_of_headers = true, bool save_bound_import = true); + +} diff --git a/tools/pe_bliss/pe_relocations.cpp b/tools/pe_bliss/pe_relocations.cpp new file mode 100644 index 0000000000..d5357dd219 --- /dev/null +++ b/tools/pe_bliss/pe_relocations.cpp @@ -0,0 +1,320 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <string.h> +#include "pe_relocations.h" +#include "pe_properties_generic.h" + +namespace pe_bliss +{ +using namespace pe_win; + +//RELOCATIONS +//Default constructor +relocation_entry::relocation_entry() + :rva_(0), type_(0) +{} + +//Constructor from relocation item (WORD) +relocation_entry::relocation_entry(uint16_t relocation_value) + :rva_(relocation_value & ((1 << 12) - 1)), type_(relocation_value >> 12) +{} + +//Constructor from relative rva and relocation type +relocation_entry::relocation_entry(uint16_t rrva, uint16_t type) + :rva_(rrva), type_(type) +{} + +//Returns RVA of relocation +uint16_t relocation_entry::get_rva() const +{ + return rva_; +} + +//Returns type of relocation +uint16_t relocation_entry::get_type() const +{ + return type_; +} + +//Sets RVA of relocation +void relocation_entry::set_rva(uint16_t rva) +{ + rva_ = rva; +} + +//Sets type of relocation +void relocation_entry::set_type(uint16_t type) +{ + type_ = type; +} + +//Returns relocation item (rrva + type) +uint16_t relocation_entry::get_item() const +{ + return rva_ | (type_ << 12); +} + +//Sets relocation item (rrva + type) +void relocation_entry::set_item(uint16_t item) +{ + rva_ = item & ((1 << 12) - 1); + type_ = item >> 12; +} + +//Returns relocation list +const relocation_table::relocation_list& relocation_table::get_relocations() const +{ + return relocations_; +} + +//Adds relocation to table +void relocation_table::add_relocation(const relocation_entry& entry) +{ + relocations_.push_back(entry); +} + +//Default constructor +relocation_table::relocation_table() + :rva_(0) +{} + +//Constructor from RVA of relocation table +relocation_table::relocation_table(uint32_t rva) + :rva_(rva) +{} + +//Returns RVA of block +uint32_t relocation_table::get_rva() const +{ + return rva_; +} + +//Sets RVA of block +void relocation_table::set_rva(uint32_t rva) +{ + rva_ = rva; +} + +//Returns changeable relocation list +relocation_table::relocation_list& relocation_table::get_relocations() +{ + return relocations_; +} + +//Get relocation list of pe file, supports one-word sized relocations only +//If list_absolute_entries = true, IMAGE_REL_BASED_ABSOLUTE will be listed +const relocation_table_list get_relocations(const pe_base& pe, bool list_absolute_entries) +{ + relocation_table_list ret; + + //If image does not have relocations + if(!pe.has_reloc()) + return ret; + + //Check the length in bytes of the section containing relocation directory + if(pe.section_data_length_from_rva(pe.get_directory_rva(image_directory_entry_basereloc), + pe.get_directory_rva(image_directory_entry_basereloc), section_data_virtual, true) + < sizeof(image_base_relocation)) + throw pe_exception("Incorrect relocation directory", pe_exception::incorrect_relocation_directory); + + unsigned long current_pos = pe.get_directory_rva(image_directory_entry_basereloc); + //First IMAGE_BASE_RELOCATION table + image_base_relocation reloc_table = pe.section_data_from_rva<image_base_relocation>(current_pos, section_data_virtual, true); + + if(reloc_table.SizeOfBlock % 2) + throw pe_exception("Incorrect relocation directory", pe_exception::incorrect_relocation_directory); + + unsigned long reloc_size = pe.get_directory_size(image_directory_entry_basereloc); + unsigned long read_size = 0; + + //reloc_table.VirtualAddress is not checked (not so important) + while(reloc_table.SizeOfBlock && read_size < reloc_size) + { + //Create relocation table + relocation_table table; + //Save RVA + table.set_rva(reloc_table.VirtualAddress); + + if(!pe_utils::is_sum_safe(current_pos, reloc_table.SizeOfBlock)) + throw pe_exception("Incorrect relocation directory", pe_exception::incorrect_relocation_directory); + + //List all relocations + for(unsigned long i = sizeof(image_base_relocation); i < reloc_table.SizeOfBlock; i += sizeof(uint16_t)) + { + relocation_entry entry(pe.section_data_from_rva<uint16_t>(current_pos + i, section_data_virtual, true)); + if(list_absolute_entries || entry.get_type() != image_rel_based_absolute) + table.add_relocation(entry); + } + + //Save table + ret.push_back(table); + + //Go to next relocation block + if(!pe_utils::is_sum_safe(current_pos, reloc_table.SizeOfBlock)) + throw pe_exception("Incorrect relocation directory", pe_exception::incorrect_relocation_directory); + + current_pos += reloc_table.SizeOfBlock; + read_size += reloc_table.SizeOfBlock; + reloc_table = pe.section_data_from_rva<image_base_relocation>(current_pos, section_data_virtual, true); + } + + return ret; +} + +//Simple relocations rebuilder +//To keep PE file working, don't remove any of existing relocations in +//relocation_table_list returned by a call to get_relocations() function +//auto_strip_last_section - if true and relocations are placed in the last section, it will be automatically stripped +//offset_from_section_start - offset from the beginning of reloc_section, where relocations data will be situated +//If save_to_pe_header is true, PE header will be modified automatically +const image_directory rebuild_relocations(pe_base& pe, const relocation_table_list& relocs, section& reloc_section, uint32_t offset_from_section_start, bool save_to_pe_header, bool auto_strip_last_section) +{ + //Check that reloc_section is attached to this PE image + if(!pe.section_attached(reloc_section)) + throw pe_exception("Relocations section must be attached to PE file", pe_exception::section_is_not_attached); + + uint32_t current_reloc_data_pos = pe_utils::align_up(offset_from_section_start, sizeof(uint32_t)); + + uint32_t needed_size = current_reloc_data_pos - offset_from_section_start; //Calculate needed size for relocation tables + uint32_t size_delta = needed_size; + + uint32_t start_reloc_pos = current_reloc_data_pos; + + //Enumerate relocation tables + for(relocation_table_list::const_iterator it = relocs.begin(); it != relocs.end(); ++it) + { + needed_size += static_cast<uint32_t>((*it).get_relocations().size() * sizeof(uint16_t) /* relocations */ + sizeof(image_base_relocation) /* table header */); + //End of each table will be DWORD-aligned + if((start_reloc_pos + needed_size - size_delta) % sizeof(uint32_t)) + needed_size += sizeof(uint16_t); //Align it with IMAGE_REL_BASED_ABSOLUTE relocation + } + + //Check if reloc_section is last one. If it's not, check if there's enough place for relocations data + if(&reloc_section != &*(pe.get_image_sections().end() - 1) && + (reloc_section.empty() || pe_utils::align_up(reloc_section.get_size_of_raw_data(), pe.get_file_alignment()) < needed_size + current_reloc_data_pos)) + throw pe_exception("Insufficient space for relocations directory", pe_exception::insufficient_space); + + std::string& raw_data = reloc_section.get_raw_data(); + + //This will be done only if reloc_section is the last section of image or for section with unaligned raw length of data + if(raw_data.length() < needed_size + current_reloc_data_pos) + raw_data.resize(needed_size + current_reloc_data_pos); //Expand section raw data + + //Enumerate relocation tables + for(relocation_table_list::const_iterator it = relocs.begin(); it != relocs.end(); ++it) + { + //Create relocation table header + image_base_relocation reloc; + reloc.VirtualAddress = (*it).get_rva(); + const relocation_table::relocation_list& reloc_list = (*it).get_relocations(); + reloc.SizeOfBlock = static_cast<uint32_t>(sizeof(image_base_relocation) + sizeof(uint16_t) * reloc_list.size()); + if((reloc_list.size() * sizeof(uint16_t)) % sizeof(uint32_t)) //If we must align end of relocation table + reloc.SizeOfBlock += sizeof(uint16_t); + + memcpy(&raw_data[current_reloc_data_pos], &reloc, sizeof(reloc)); + current_reloc_data_pos += sizeof(reloc); + + //Enumerate relocations in table + for(relocation_table::relocation_list::const_iterator r = reloc_list.begin(); r != reloc_list.end(); ++r) + { + //Save relocations + uint16_t reloc_value = (*r).get_item(); + memcpy(&raw_data[current_reloc_data_pos], &reloc_value, sizeof(reloc_value)); + current_reloc_data_pos += sizeof(reloc_value); + } + + if(current_reloc_data_pos % sizeof(uint32_t)) //If end of table is not DWORD-aligned + { + memset(&raw_data[current_reloc_data_pos], 0, sizeof(uint16_t)); //Align it with IMAGE_REL_BASED_ABSOLUTE relocation + current_reloc_data_pos += sizeof(uint16_t); + } + } + + image_directory ret(pe.rva_from_section_offset(reloc_section, start_reloc_pos), needed_size - size_delta); + + //Adjust section raw and virtual sizes + pe.recalculate_section_sizes(reloc_section, auto_strip_last_section); + + //If auto-rewrite of PE headers is required + if(save_to_pe_header) + { + pe.set_directory_rva(image_directory_entry_basereloc, ret.get_rva()); + pe.set_directory_size(image_directory_entry_basereloc, ret.get_size()); + + pe.clear_characteristics_flags(image_file_relocs_stripped); + pe.set_dll_characteristics(pe.get_dll_characteristics() | image_dllcharacteristics_dynamic_base); + } + + return ret; +} + +//Recalculates image base with the help of relocation tables +void rebase_image(pe_base& pe, const relocation_table_list& tables, uint64_t new_base) +{ + pe.get_pe_type() == pe_type_32 + ? rebase_image_base<pe_types_class_32>(pe, tables, new_base) + : rebase_image_base<pe_types_class_64>(pe, tables, new_base); +} + +//RELOCATIONS +//Recalculates image base with the help of relocation tables +//Recalculates VAs of DWORDS/QWORDS in image according to relocations +//Notice: if you move some critical structures like TLS, image relocations will not fix new +//positions of TLS VAs. Instead, some bytes that now doesn't belong to TLS will be fixed. +//It is recommended to rebase image in the very beginning and move all structures afterwards. +template<typename PEClassType> +void rebase_image_base(pe_base& pe, const relocation_table_list& tables, uint64_t new_base) +{ + //Get current image base value + typename PEClassType::BaseSize image_base; + pe.get_image_base(image_base); + + //ImageBase difference + typename PEClassType::BaseSize base_rel = static_cast<typename PEClassType::BaseSize>(static_cast<int64_t>(new_base) - image_base); + + //We need to fix addresses from relocation tables + //Enumerate relocation tables + for(relocation_table_list::const_iterator it = tables.begin(); it != tables.end(); ++it) + { + const relocation_table::relocation_list& relocs = (*it).get_relocations(); + + uint32_t base_rva = (*it).get_rva(); + + //Enumerate relocations + for(relocation_table::relocation_list::const_iterator rel = relocs.begin(); rel != relocs.end(); ++rel) + { + //Skip ABSOLUTE entries + if((*rel).get_type() == pe_win::image_rel_based_absolute) + continue; + + //Recalculate value by RVA and rewrite it + uint32_t current_rva = base_rva + (*rel).get_rva(); + typename PEClassType::BaseSize value = pe.section_data_from_rva<typename PEClassType::BaseSize>(current_rva, section_data_raw, true); + value += base_rel; + memcpy(pe.section_data_from_rva(current_rva, true), &value, sizeof(value)); + } + } + + //Finally, save new image base + pe.set_image_base_64(new_base); +} +} diff --git a/tools/pe_bliss/pe_relocations.h b/tools/pe_bliss/pe_relocations.h new file mode 100644 index 0000000000..1bc8b2a405 --- /dev/null +++ b/tools/pe_bliss/pe_relocations.h @@ -0,0 +1,122 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <vector> +#include "pe_structures.h" +#include "pe_base.h" +#include "pe_directory.h" + +namespace pe_bliss +{ +//Class representing relocation entry +//RVA of relocation is not actually RVA, but +//(real RVA) - (RVA of table) +class relocation_entry +{ +public: + //Default constructor + relocation_entry(); + //Constructor from relocation item (WORD) + explicit relocation_entry(uint16_t relocation_value); + //Constructor from relative rva and relocation type + relocation_entry(uint16_t rrva, uint16_t type); + + //Returns RVA of relocation (actually, relative RVA from relocation table RVA) + uint16_t get_rva() const; + //Returns type of relocation + uint16_t get_type() const; + + //Returns relocation item (rrva + type) + uint16_t get_item() const; + +public: //Setters do not change everything inside image, they are used by PE class + //You can also use them to rebuild relocations using rebuild_relocations() + + //Sets RVA of relocation (actually, relative RVA from relocation table RVA) + void set_rva(uint16_t rva); + //Sets type of relocation + void set_type(uint16_t type); + + //Sets relocation item (rrva + type) + void set_item(uint16_t item); + +private: + uint16_t rva_; + uint16_t type_; +}; + +//Class representing relocation table +class relocation_table +{ +public: + typedef std::vector<relocation_entry> relocation_list; + +public: + //Default constructor + relocation_table(); + //Constructor from RVA of relocation table + explicit relocation_table(uint32_t rva); + + //Returns relocation list + const relocation_list& get_relocations() const; + //Returns RVA of block + uint32_t get_rva() const; + +public: //These functions do not change everything inside image, they are used by PE class + //You can also use them to rebuild relocations using rebuild_relocations() + + //Adds relocation to table + void add_relocation(const relocation_entry& entry); + //Returns changeable relocation list + relocation_list& get_relocations(); + //Sets RVA of block + void set_rva(uint32_t rva); + +private: + uint32_t rva_; + relocation_list relocations_; +}; + +typedef std::vector<relocation_table> relocation_table_list; + +//Get relocation list of pe file, supports one-word sized relocations only +//If list_absolute_entries = true, IMAGE_REL_BASED_ABSOLUTE will be listed +const relocation_table_list get_relocations(const pe_base& pe, bool list_absolute_entries = false); + +//Simple relocations rebuilder +//To keep PE file working, don't remove any of existing relocations in +//relocation_table_list returned by a call to get_relocations() function +//auto_strip_last_section - if true and relocations are placed in the last section, it will be automatically stripped +//offset_from_section_start - offset from the beginning of reloc_section, where relocations data will be situated +//If save_to_pe_header is true, PE header will be modified automatically +const image_directory rebuild_relocations(pe_base& pe, const relocation_table_list& relocs, section& reloc_section, uint32_t offset_from_section_start = 0, bool save_to_pe_header = true, bool auto_strip_last_section = true); + +//Recalculates image base with the help of relocation tables +//Recalculates VAs of DWORDS/QWORDS in image according to relocations +//Notice: if you move some critical structures like TLS, image relocations will not fix new +//positions of TLS VAs. Instead, some bytes that now doesn't belong to TLS will be fixed. +//It is recommended to rebase image in the very beginning and move all structures afterwards. +void rebase_image(pe_base& pe, const relocation_table_list& tables, uint64_t new_base); + +template<typename PEClassType> +void rebase_image_base(pe_base& pe, const relocation_table_list& tables, uint64_t new_base); +} diff --git a/tools/pe_bliss/pe_resource_manager.cpp b/tools/pe_bliss/pe_resource_manager.cpp new file mode 100644 index 0000000000..0ee7840ff0 --- /dev/null +++ b/tools/pe_bliss/pe_resource_manager.cpp @@ -0,0 +1,286 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <algorithm> +#include <sstream> +#include <iomanip> +#include <math.h> +#include <string.h> +#include "pe_resource_manager.h" +#include "resource_internal.h" + +namespace pe_bliss +{ +using namespace pe_win; + +//Constructor from root resource directory +pe_resource_manager::pe_resource_manager(resource_directory& root_directory) + :pe_resource_viewer(root_directory), root_dir_edit_(root_directory) +{} + +resource_directory& pe_resource_manager::get_root_directory() +{ + return root_dir_edit_; +} + +//Removes all resources of given type or root name +//If there's more than one directory entry of a given type, only the +//first one will be deleted (that's an unusual situation) +//Returns true if resource was deleted +bool pe_resource_manager::remove_resource_type(resource_type type) +{ + //Search for resource type + resource_directory::entry_list& entries = root_dir_edit_.get_entry_list(); + resource_directory::entry_list::iterator it = std::find_if(entries.begin(), entries.end(), resource_directory::id_entry_finder(type)); + if(it != entries.end()) + { + //Remove it, if found + entries.erase(it); + return true; + } + + return false; +} + +bool pe_resource_manager::remove_resource(const std::wstring& root_name) +{ + //Search for resource type + resource_directory::entry_list& entries = root_dir_edit_.get_entry_list(); + resource_directory::entry_list::iterator it = std::find_if(entries.begin(), entries.end(), resource_directory::name_entry_finder(root_name)); + if(it != entries.end()) + { + //Remove it, if found + entries.erase(it); + return true; + } + + return false; +} + +//Helper to remove resource +bool pe_resource_manager::remove_resource(const resource_directory::entry_finder& root_finder, const resource_directory::entry_finder& finder) +{ + //Search for resource type + resource_directory::entry_list& entries_type = root_dir_edit_.get_entry_list(); + resource_directory::entry_list::iterator it_type = std::find_if(entries_type.begin(), entries_type.end(), root_finder); + if(it_type != entries_type.end()) + { + //Search for resource name/ID with "finder" + resource_directory::entry_list& entries_name = (*it_type).get_resource_directory().get_entry_list(); + resource_directory::entry_list::iterator it_name = std::find_if(entries_name.begin(), entries_name.end(), finder); + if(it_name != entries_name.end()) + { + //Erase resource, if found + entries_name.erase(it_name); + if(entries_name.empty()) + entries_type.erase(it_type); + + return true; + } + } + + return false; +} + +//Removes all resource languages by resource type/root name and name +//Deletes only one entry of given type and name +//Returns true if resource was deleted +bool pe_resource_manager::remove_resource(resource_type type, const std::wstring& name) +{ + return remove_resource(resource_directory::entry_finder(type), resource_directory::entry_finder(name)); +} + +bool pe_resource_manager::remove_resource(const std::wstring& root_name, const std::wstring& name) +{ + return remove_resource(resource_directory::entry_finder(root_name), resource_directory::entry_finder(name)); +} + +//Removes all resource languages by resource type/root name and ID +//Deletes only one entry of given type and ID +//Returns true if resource was deleted +bool pe_resource_manager::remove_resource(resource_type type, uint32_t id) +{ + return remove_resource(resource_directory::entry_finder(type), resource_directory::entry_finder(id)); +} + +bool pe_resource_manager::remove_resource(const std::wstring& root_name, uint32_t id) +{ + return remove_resource(resource_directory::entry_finder(root_name), resource_directory::entry_finder(id)); +} + +//Helper to remove resource +bool pe_resource_manager::remove_resource(const resource_directory::entry_finder& root_finder, const resource_directory::entry_finder& finder, uint32_t language) +{ + //Search for resource type + resource_directory::entry_list& entries_type = root_dir_edit_.get_entry_list(); + resource_directory::entry_list::iterator it_type = std::find_if(entries_type.begin(), entries_type.end(), root_finder); + if(it_type != entries_type.end()) + { + //Search for resource name/ID with "finder" + resource_directory::entry_list& entries_name = (*it_type).get_resource_directory().get_entry_list(); + resource_directory::entry_list::iterator it_name = std::find_if(entries_name.begin(), entries_name.end(), finder); + if(it_name != entries_name.end()) + { + //Search for resource language + resource_directory::entry_list& entries_lang = (*it_name).get_resource_directory().get_entry_list(); + resource_directory::entry_list::iterator it_lang = std::find_if(entries_lang.begin(), entries_lang.end(), resource_directory::id_entry_finder(language)); + if(it_lang != entries_lang.end()) + { + //Erase resource, if found + entries_lang.erase(it_lang); + if(entries_lang.empty()) + { + entries_name.erase(it_name); + if(entries_name.empty()) + entries_type.erase(it_type); + } + + return true; + } + } + } + + return false; +} + +//Removes resource language by resource type/root name and name +//Deletes only one entry of given type, name and language +//Returns true if resource was deleted +bool pe_resource_manager::remove_resource(resource_type type, const std::wstring& name, uint32_t language) +{ + return remove_resource(resource_directory::entry_finder(type), resource_directory::entry_finder(name), language); +} + +bool pe_resource_manager::remove_resource(const std::wstring& root_name, const std::wstring& name, uint32_t language) +{ + return remove_resource(resource_directory::entry_finder(root_name), resource_directory::entry_finder(name), language); +} + +//Removes recource language by resource type/root name and ID +//Deletes only one entry of given type, ID and language +//Returns true if resource was deleted +bool pe_resource_manager::remove_resource(resource_type type, uint32_t id, uint32_t language) +{ + return remove_resource(resource_directory::entry_finder(type), resource_directory::entry_finder(id), language); +} + +bool pe_resource_manager::remove_resource(const std::wstring& root_name, uint32_t id, uint32_t language) +{ + return remove_resource(resource_directory::entry_finder(root_name), resource_directory::entry_finder(id), language); +} + +//Helper to add/replace resource +void pe_resource_manager::add_resource(const std::string& data, resource_type type, resource_directory_entry& new_entry, const resource_directory::entry_finder& finder, uint32_t language, uint32_t codepage, uint32_t timestamp) +{ + resource_directory_entry new_type_entry; + new_type_entry.set_id(type); + + add_resource(data, new_type_entry, resource_directory::entry_finder(type), new_entry, finder, language, codepage, timestamp); +} + +//Helper to add/replace resource +void pe_resource_manager::add_resource(const std::string& data, const std::wstring& root_name, resource_directory_entry& new_entry, const resource_directory::entry_finder& finder, uint32_t language, uint32_t codepage, uint32_t timestamp) +{ + resource_directory_entry new_type_entry; + new_type_entry.set_name(root_name); + + add_resource(data, new_type_entry, resource_directory::entry_finder(root_name), new_entry, finder, language, codepage, timestamp); +} + +//Helper to add/replace resource +void pe_resource_manager::add_resource(const std::string& data, resource_directory_entry& new_root_entry, const resource_directory::entry_finder& root_finder, resource_directory_entry& new_entry, const resource_directory::entry_finder& finder, uint32_t language, uint32_t codepage, uint32_t timestamp) +{ + //Search for resource type + resource_directory::entry_list* entries = &root_dir_edit_.get_entry_list(); + resource_directory::entry_list::iterator it = std::find_if(entries->begin(), entries->end(), root_finder); + if(it == entries->end()) + { + //Add resource type directory, if it was not found + resource_directory dir; + dir.set_timestamp(timestamp); + new_root_entry.add_resource_directory(dir); + entries->push_back(new_root_entry); + it = entries->end() - 1; + } + + //Search for resource name/ID directory with "finder" + entries = &(*it).get_resource_directory().get_entry_list(); + it = std::find_if(entries->begin(), entries->end(), finder); + if(it == entries->end()) + { + //Add resource name/ID directory, if it was not found + resource_directory dir; + dir.set_timestamp(timestamp); + new_entry.add_resource_directory(dir); + entries->push_back(new_entry); + it = entries->end() - 1; + } + + //Search for data resource entry by language + entries = &(*it).get_resource_directory().get_entry_list(); + it = std::find_if(entries->begin(), entries->end(), resource_directory::id_entry_finder(language)); + if(it != entries->end()) + entries->erase(it); //Erase it, if found + + //Add new data entry + resource_directory_entry new_dir_data_entry; + resource_data_entry data_dir(data, codepage); + new_dir_data_entry.add_data_entry(data_dir); + new_dir_data_entry.set_id(language); + entries->push_back(new_dir_data_entry); +} + +//Adds resource. If resource already exists, replaces it +void pe_resource_manager::add_resource(const std::string& data, resource_type type, const std::wstring& name, uint32_t language, uint32_t codepage, uint32_t timestamp) +{ + resource_directory_entry new_entry; + new_entry.set_name(name); + + add_resource(data, type, new_entry, resource_directory::entry_finder(name), language, codepage, timestamp); +} + +//Adds resource. If resource already exists, replaces it +void pe_resource_manager::add_resource(const std::string& data, const std::wstring& root_name, const std::wstring& name, uint32_t language, uint32_t codepage, uint32_t timestamp) +{ + resource_directory_entry new_entry; + new_entry.set_name(name); + + add_resource(data, root_name, new_entry, resource_directory::entry_finder(name), language, codepage, timestamp); +} + +//Adds resource. If resource already exists, replaces it +void pe_resource_manager::add_resource(const std::string& data, resource_type type, uint32_t id, uint32_t language, uint32_t codepage, uint32_t timestamp) +{ + resource_directory_entry new_entry; + new_entry.set_id(id); + + add_resource(data, type, new_entry, resource_directory::entry_finder(id), language, codepage, timestamp); +} + +//Adds resource. If resource already exists, replaces it +void pe_resource_manager::add_resource(const std::string& data, const std::wstring& root_name, uint32_t id, uint32_t language, uint32_t codepage, uint32_t timestamp) +{ + resource_directory_entry new_entry; + new_entry.set_id(id); + + add_resource(data, root_name, new_entry, resource_directory::entry_finder(id), language, codepage, timestamp); +} +} diff --git a/tools/pe_bliss/pe_resource_manager.h b/tools/pe_bliss/pe_resource_manager.h new file mode 100644 index 0000000000..85d7f44a8a --- /dev/null +++ b/tools/pe_bliss/pe_resource_manager.h @@ -0,0 +1,113 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <map> +#include <sstream> +#include <string> +#include <memory> +#include "pe_base.h" +#include "pe_structures.h" +#include "pe_resources.h" +#include "message_table.h" +#include "file_version_info.h" +#include "pe_resource_viewer.h" +#include "resource_data_info.h" + +namespace pe_bliss +{ +//Derived class to edit PE resources +class pe_resource_manager : public pe_resource_viewer +{ +public: + //Constructor from root resource directory + explicit pe_resource_manager(resource_directory& root_directory); + + resource_directory& get_root_directory(); + +public: //Resource editing + //Removes all resources of given type or root name + //If there's more than one directory entry of a given type, only the + //first one will be deleted (that's an unusual situation) + //Returns true if resource was deleted + bool remove_resource_type(resource_type type); + bool remove_resource(const std::wstring& root_name); + + //Removes all resource languages by resource type/root name and name + //Deletes only one entry of given type and name + //Returns true if resource was deleted + bool remove_resource(resource_type type, const std::wstring& name); + bool remove_resource(const std::wstring& root_name, const std::wstring& name); + //Removes all resource languages by resource type/root name and ID + //Deletes only one entry of given type and ID + //Returns true if resource was deleted + bool remove_resource(resource_type type, uint32_t id); + bool remove_resource(const std::wstring& root_name, uint32_t id); + + //Removes resource language by resource type/root name and name + //Deletes only one entry of given type, name and language + //Returns true if resource was deleted + bool remove_resource(resource_type type, const std::wstring& name, uint32_t language); + bool remove_resource(const std::wstring& root_name, const std::wstring& name, uint32_t language); + //Removes recource language by resource type/root name and ID + //Deletes only one entry of given type, ID and language + //Returns true if resource was deleted + bool remove_resource(resource_type type, uint32_t id, uint32_t language); + bool remove_resource(const std::wstring& root_name, uint32_t id, uint32_t language); + + //Adds resource. If resource already exists, replaces it + //timestamp will be used for directories that will be added + void add_resource(const std::string& data, resource_type type, const std::wstring& name, uint32_t language, uint32_t codepage = 0, uint32_t timestamp = 0); + void add_resource(const std::string& data, const std::wstring& root_name, const std::wstring& name, uint32_t language, uint32_t codepage = 0, uint32_t timestamp = 0); + //Adds resource. If resource already exists, replaces it + //timestamp will be used for directories that will be added + void add_resource(const std::string& data, resource_type type, uint32_t id, uint32_t language, uint32_t codepage = 0, uint32_t timestamp = 0); + void add_resource(const std::string& data, const std::wstring& root_name, uint32_t id, uint32_t language, uint32_t codepage = 0, uint32_t timestamp = 0); + +public: + //Helpers to add/replace resource + void add_resource(const std::string& data, resource_type type, + resource_directory_entry& new_entry, + const resource_directory::entry_finder& finder, + uint32_t language, uint32_t codepage, uint32_t timestamp); + + void add_resource(const std::string& data, const std::wstring& root_name, + resource_directory_entry& new_entry, + const resource_directory::entry_finder& finder, + uint32_t language, uint32_t codepage, uint32_t timestamp); + + void add_resource(const std::string& data, resource_directory_entry& new_root_entry, + const resource_directory::entry_finder& root_finder, + resource_directory_entry& new_entry, + const resource_directory::entry_finder& finder, + uint32_t language, uint32_t codepage, uint32_t timestamp); + +private: + //Root resource directory. We're not copying it, because it might be heavy + resource_directory& root_dir_edit_; + + //Helper to remove resource + bool remove_resource(const resource_directory::entry_finder& root_finder, const resource_directory::entry_finder& finder); + + //Helper to remove resource + bool remove_resource(const resource_directory::entry_finder& root_finder, const resource_directory::entry_finder& finder, uint32_t language); +}; +} diff --git a/tools/pe_bliss/pe_resource_viewer.cpp b/tools/pe_bliss/pe_resource_viewer.cpp new file mode 100644 index 0000000000..712cc28d9b --- /dev/null +++ b/tools/pe_bliss/pe_resource_viewer.cpp @@ -0,0 +1,382 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <algorithm> +#include <cmath> +#include "pe_resource_viewer.h" +#include "pe_structures.h" + +namespace pe_bliss +{ +using namespace pe_win; + +//Constructor from root resource_directory +pe_resource_viewer::pe_resource_viewer(const resource_directory& root_directory) + :root_dir_(root_directory) +{} + +const resource_directory& pe_resource_viewer::get_root_directory() const +{ + return root_dir_; +} + +//Finder helpers +bool pe_resource_viewer::has_name::operator()(const resource_directory_entry& entry) const +{ + return entry.is_named(); +} + +bool pe_resource_viewer::has_id::operator()(const resource_directory_entry& entry) const +{ + return !entry.is_named(); +} + +//Lists resource types existing in PE file (non-named only) +const pe_resource_viewer::resource_type_list pe_resource_viewer::list_resource_types() const +{ + resource_type_list ret; + + //Get root directory entries list + const resource_directory::entry_list& entries = root_dir_.get_entry_list(); + for(resource_directory::entry_list::const_iterator it = entries.begin(); it != entries.end(); ++it) + { + //List all non-named items + if(!(*it).is_named()) + ret.push_back((*it).get_id()); + } + + return ret; +} + +//Returns true if resource type exists +bool pe_resource_viewer::resource_exists(resource_type type) const +{ + const resource_directory::entry_list& entries = root_dir_.get_entry_list(); + return std::find_if(entries.begin(), entries.end(), resource_directory::id_entry_finder(type)) != entries.end(); +} + +//Returns true if resource name exists +bool pe_resource_viewer::resource_exists(const std::wstring& root_name) const +{ + const resource_directory::entry_list& entries = root_dir_.get_entry_list(); + return std::find_if(entries.begin(), entries.end(), resource_directory::name_entry_finder(root_name)) != entries.end(); +} + +//Helper function to get name list from entry list +const pe_resource_viewer::resource_name_list pe_resource_viewer::get_name_list(const resource_directory::entry_list& entries) +{ + resource_name_list ret; + + for(resource_directory::entry_list::const_iterator it = entries.begin(); it != entries.end(); ++it) + { + //List all named items + if((*it).is_named()) + ret.push_back((*it).get_name()); + } + + return ret; +} + +//Helper function to get ID list from entry list +const pe_resource_viewer::resource_id_list pe_resource_viewer::get_id_list(const resource_directory::entry_list& entries) +{ + resource_id_list ret; + + for(resource_directory::entry_list::const_iterator it = entries.begin(); it != entries.end(); ++it) + { + //List all non-named items + if(!(*it).is_named()) + ret.push_back((*it).get_id()); + } + + return ret; +} + +//Lists resource names existing in PE file by resource type +const pe_resource_viewer::resource_name_list pe_resource_viewer::list_resource_names(resource_type type) const +{ + return get_name_list(root_dir_.entry_by_id(type).get_resource_directory().get_entry_list()); +} + +//Lists resource names existing in PE file by resource name +const pe_resource_viewer::resource_name_list pe_resource_viewer::list_resource_names(const std::wstring& root_name) const +{ + return get_name_list(root_dir_.entry_by_name(root_name).get_resource_directory().get_entry_list()); +} + +//Lists resource IDs existing in PE file by resource type +const pe_resource_viewer::resource_id_list pe_resource_viewer::list_resource_ids(resource_type type) const +{ + return get_id_list(root_dir_.entry_by_id(type).get_resource_directory().get_entry_list()); +} + +//Lists resource IDs existing in PE file by resource name +const pe_resource_viewer::resource_id_list pe_resource_viewer::list_resource_ids(const std::wstring& root_name) const +{ + return get_id_list(root_dir_.entry_by_name(root_name).get_resource_directory().get_entry_list()); +} + +//Returns resource count by type +unsigned long pe_resource_viewer::get_resource_count(resource_type type) const +{ + return static_cast<unsigned long>( + root_dir_ //Type directory + .entry_by_id(type) + .get_resource_directory() //Name/ID directory + .get_entry_list() + .size()); +} + +//Returns resource count by name +unsigned long pe_resource_viewer::get_resource_count(const std::wstring& root_name) const +{ + return static_cast<unsigned long>( + root_dir_ //Type directory + .entry_by_name(root_name) + .get_resource_directory() //Name/ID directory + .get_entry_list() + .size()); +} + +//Returns language count of resource by resource type and name +unsigned long pe_resource_viewer::get_language_count(resource_type type, const std::wstring& name) const +{ + const resource_directory::entry_list& entries = + root_dir_ //Type directory + .entry_by_id(type) + .get_resource_directory() //Name/ID directory + .entry_by_name(name) + .get_resource_directory() //Language directory + .get_entry_list(); + + return static_cast<unsigned long>(std::count_if(entries.begin(), entries.end(), has_id())); +} + +//Returns language count of resource by resource names +unsigned long pe_resource_viewer::get_language_count(const std::wstring& root_name, const std::wstring& name) const +{ + const resource_directory::entry_list& entries = + root_dir_ //Type directory + .entry_by_name(root_name) + .get_resource_directory() //Name/ID directory + .entry_by_name(name) + .get_resource_directory() //Language directory + .get_entry_list(); + + return static_cast<unsigned long>(std::count_if(entries.begin(), entries.end(), has_id())); +} + +//Returns language count of resource by resource type and ID +unsigned long pe_resource_viewer::get_language_count(resource_type type, uint32_t id) const +{ + const resource_directory::entry_list& entries = + root_dir_ //Type directory + .entry_by_id(type) + .get_resource_directory() //Name/ID directory + .entry_by_id(id) + .get_resource_directory() //Language directory + .get_entry_list(); + + return static_cast<unsigned long>(std::count_if(entries.begin(), entries.end(), has_id())); +} + +//Returns language count of resource by resource name and ID +unsigned long pe_resource_viewer::get_language_count(const std::wstring& root_name, uint32_t id) const +{ + const resource_directory::entry_list& entries = + root_dir_ //Type directory + .entry_by_name(root_name) + .get_resource_directory() //Name/ID directory + .entry_by_id(id) + .get_resource_directory() //Language directory + .get_entry_list(); + + return static_cast<unsigned long>(std::count_if(entries.begin(), entries.end(), has_id())); +} + +//Lists resource languages by resource type and name +const pe_resource_viewer::resource_language_list pe_resource_viewer::list_resource_languages(resource_type type, const std::wstring& name) const +{ + const resource_directory::entry_list& entries = + root_dir_ //Type directory + .entry_by_id(type) + .get_resource_directory() //Name/ID directory + .entry_by_name(name) + .get_resource_directory() //Language directory + .get_entry_list(); + + return get_id_list(entries); +} + +//Lists resource languages by resource names +const pe_resource_viewer::resource_language_list pe_resource_viewer::list_resource_languages(const std::wstring& root_name, const std::wstring& name) const +{ + const resource_directory::entry_list& entries = + root_dir_ //Type directory + .entry_by_name(root_name) + .get_resource_directory() //Name/ID directory + .entry_by_name(name) + .get_resource_directory() //Language directory + .get_entry_list(); + + return get_id_list(entries); +} + +//Lists resource languages by resource type and ID +const pe_resource_viewer::resource_language_list pe_resource_viewer::list_resource_languages(resource_type type, uint32_t id) const +{ + const resource_directory::entry_list& entries = + root_dir_ //Type directory + .entry_by_id(type) + .get_resource_directory() //Name/ID directory + .entry_by_id(id) + .get_resource_directory() //Language directory + .get_entry_list(); + + return get_id_list(entries); +} + +//Lists resource languages by resource name and ID +const pe_resource_viewer::resource_language_list pe_resource_viewer::list_resource_languages(const std::wstring& root_name, uint32_t id) const +{ + const resource_directory::entry_list& entries = + root_dir_ //Type directory + .entry_by_name(root_name) + .get_resource_directory() //Name/ID directory + .entry_by_id(id) + .get_resource_directory() //Language directory + .get_entry_list(); + + return get_id_list(entries); +} + +//Returns raw resource data by type, name and language +const resource_data_info pe_resource_viewer::get_resource_data_by_name(uint32_t language, resource_type type, const std::wstring& name) const +{ + return resource_data_info(root_dir_ //Type directory + .entry_by_id(type) + .get_resource_directory() //Name/ID directory + .entry_by_name(name) + .get_resource_directory() //Language directory + .entry_by_id(language) + .get_data_entry()); //Data directory +} + +//Returns raw resource data by root name, name and language +const resource_data_info pe_resource_viewer::get_resource_data_by_name(uint32_t language, const std::wstring& root_name, const std::wstring& name) const +{ + return resource_data_info(root_dir_ //Type directory + .entry_by_name(root_name) + .get_resource_directory() //Name/ID directory + .entry_by_name(name) + .get_resource_directory() //Language directory + .entry_by_id(language) + .get_data_entry()); //Data directory +} + +//Returns raw resource data by type, ID and language +const resource_data_info pe_resource_viewer::get_resource_data_by_id(uint32_t language, resource_type type, uint32_t id) const +{ + return resource_data_info(root_dir_ //Type directory + .entry_by_id(type) + .get_resource_directory() //Name/ID directory + .entry_by_id(id) + .get_resource_directory() //Language directory + .entry_by_id(language) + .get_data_entry()); //Data directory +} + +//Returns raw resource data by root name, ID and language +const resource_data_info pe_resource_viewer::get_resource_data_by_id(uint32_t language, const std::wstring& root_name, uint32_t id) const +{ + return resource_data_info(root_dir_ //Type directory + .entry_by_name(root_name) + .get_resource_directory() //Name/ID directory + .entry_by_id(id) + .get_resource_directory() //Language directory + .entry_by_id(language) + .get_data_entry()); //Data directory +} + +//Returns raw resource data by type, name and index in language directory (instead of language) +const resource_data_info pe_resource_viewer::get_resource_data_by_name(resource_type type, const std::wstring& name, uint32_t index) const +{ + const resource_directory::entry_list& entries = root_dir_ //Type directory + .entry_by_id(type) + .get_resource_directory() //Name/ID directory + .entry_by_name(name) + .get_resource_directory() //Language directory + .get_entry_list(); + + if(entries.size() <= index) + throw pe_exception("Resource data entry not found", pe_exception::resource_data_entry_not_found); + + return resource_data_info(entries.at(index).get_data_entry()); //Data directory +} + +//Returns raw resource data by root name, name and index in language directory (instead of language) +const resource_data_info pe_resource_viewer::get_resource_data_by_name(const std::wstring& root_name, const std::wstring& name, uint32_t index) const +{ + const resource_directory::entry_list& entries = root_dir_ //Type directory + .entry_by_name(root_name) + .get_resource_directory() //Name/ID directory + .entry_by_name(name) + .get_resource_directory() //Language directory + .get_entry_list(); + + if(entries.size() <= index) + throw pe_exception("Resource data entry not found", pe_exception::resource_data_entry_not_found); + + return resource_data_info(entries.at(index).get_data_entry()); //Data directory +} + +//Returns raw resource data by type, ID and index in language directory (instead of language) +const resource_data_info pe_resource_viewer::get_resource_data_by_id(resource_type type, uint32_t id, uint32_t index) const +{ + const resource_directory::entry_list& entries = root_dir_ //Type directory + .entry_by_id(type) + .get_resource_directory() //Name/ID directory + .entry_by_id(id) + .get_resource_directory() //Language directory + .get_entry_list(); + + if(entries.size() <= index) + throw pe_exception("Resource data entry not found", pe_exception::resource_data_entry_not_found); + + return resource_data_info(entries.at(index).get_data_entry()); //Data directory +} + +//Returns raw resource data by root name, ID and index in language directory (instead of language) +const resource_data_info pe_resource_viewer::get_resource_data_by_id(const std::wstring& root_name, uint32_t id, uint32_t index) const +{ + const resource_directory::entry_list& entries = root_dir_ //Type directory + .entry_by_name(root_name) + .get_resource_directory() //Name/ID directory + .entry_by_id(id) + .get_resource_directory() //Language directory + .get_entry_list(); + + if(entries.size() <= index) + throw pe_exception("Resource data entry not found", pe_exception::resource_data_entry_not_found); + + return resource_data_info(entries.at(index).get_data_entry()); //Data directory +} +} diff --git a/tools/pe_bliss/pe_resource_viewer.h b/tools/pe_bliss/pe_resource_viewer.h new file mode 100644 index 0000000000..e585da6a87 --- /dev/null +++ b/tools/pe_bliss/pe_resource_viewer.h @@ -0,0 +1,153 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <map> +#include <string> +#include "pe_structures.h" +#include "pe_resources.h" +#include "message_table.h" +#include "resource_data_info.h" + +namespace pe_bliss +{ + //PE resource manager allows to read resources from PE files +class pe_resource_viewer +{ +public: + //Resource type enumeration + enum resource_type + { + resource_cursor = 1, + resource_bitmap = 2, + resource_icon = 3, + resource_menu = 4, + resource_dialog = 5, + resource_string = 6, + resource_fontdir = 7, + resource_font = 8, + resource_accelerator = 9, + resource_rcdata = 10, + resource_message_table = 11, + resource_cursor_group = 12, + resource_icon_group = 14, + resource_version = 16, + resource_dlginclude = 17, + resource_plugplay = 19, + resource_vxd = 20, + resource_anicursor = 21, + resource_aniicon = 22, + resource_html = 23, + resource_manifest = 24 + }; + +public: + //Some useful typedefs + typedef std::vector<uint32_t> resource_type_list; + typedef std::vector<uint32_t> resource_id_list; + typedef std::vector<std::wstring> resource_name_list; + typedef std::vector<uint32_t> resource_language_list; + +public: + //Constructor from root resource_directory from PE file + explicit pe_resource_viewer(const resource_directory& root_directory); + + const resource_directory& get_root_directory() const; + + //Lists resource types existing in PE file (non-named only) + const resource_type_list list_resource_types() const; + //Returns true if resource type exists + bool resource_exists(resource_type type) const; + //Returns true if resource name exists + bool resource_exists(const std::wstring& root_name) const; + + //Lists resource names existing in PE file by resource type + const resource_name_list list_resource_names(resource_type type) const; + //Lists resource names existing in PE file by resource name + const resource_name_list list_resource_names(const std::wstring& root_name) const; + //Lists resource IDs existing in PE file by resource type + const resource_id_list list_resource_ids(resource_type type) const; + //Lists resource IDs existing in PE file by resource name + const resource_id_list list_resource_ids(const std::wstring& root_name) const; + //Returns resource count by type + unsigned long get_resource_count(resource_type type) const; + //Returns resource count by name + unsigned long get_resource_count(const std::wstring& root_name) const; + + //Returns language count of resource by resource type and name + unsigned long get_language_count(resource_type type, const std::wstring& name) const; + //Returns language count of resource by resource names + unsigned long get_language_count(const std::wstring& root_name, const std::wstring& name) const; + //Returns language count of resource by resource type and ID + unsigned long get_language_count(resource_type type, uint32_t id) const; + //Returns language count of resource by resource name and ID + unsigned long get_language_count(const std::wstring& root_name, uint32_t id) const; + //Lists resource languages by resource type and name + const resource_language_list list_resource_languages(resource_type type, const std::wstring& name) const; + //Lists resource languages by resource names + const resource_language_list list_resource_languages(const std::wstring& root_name, const std::wstring& name) const; + //Lists resource languages by resource type and ID + const resource_language_list list_resource_languages(resource_type type, uint32_t id) const; + //Lists resource languages by resource name and ID + const resource_language_list list_resource_languages(const std::wstring& root_name, uint32_t id) const; + + //Returns raw resource data by type, name and language + const resource_data_info get_resource_data_by_name(uint32_t language, resource_type type, const std::wstring& name) const; + //Returns raw resource data by root name, name and language + const resource_data_info get_resource_data_by_name(uint32_t language, const std::wstring& root_name, const std::wstring& name) const; + //Returns raw resource data by type, ID and language + const resource_data_info get_resource_data_by_id(uint32_t language, resource_type type, uint32_t id) const; + //Returns raw resource data by root name, ID and language + const resource_data_info get_resource_data_by_id(uint32_t language, const std::wstring& root_name, uint32_t id) const; + //Returns raw resource data by type, name and index in language directory (instead of language) + const resource_data_info get_resource_data_by_name(resource_type type, const std::wstring& name, uint32_t index = 0) const; + //Returns raw resource data by root name, name and index in language directory (instead of language) + const resource_data_info get_resource_data_by_name(const std::wstring& root_name, const std::wstring& name, uint32_t index = 0) const; + //Returns raw resource data by type, ID and index in language directory (instead of language) + const resource_data_info get_resource_data_by_id(resource_type type, uint32_t id, uint32_t index = 0) const; + //Returns raw resource data by root name, ID and index in language directory (instead of language) + const resource_data_info get_resource_data_by_id(const std::wstring& root_name, uint32_t id, uint32_t index = 0) const; + +protected: + //Root resource directory. We're not copying it, because it might be heavy + const resource_directory& root_dir_; + + //Helper function to get ID list from entry list + static const resource_id_list get_id_list(const resource_directory::entry_list& entries); + //Helper function to get name list from entry list + static const resource_name_list get_name_list(const resource_directory::entry_list& entries); + +protected: + //Helper structure - finder of resource_directory_entry that is named + struct has_name + { + public: + bool operator()(const resource_directory_entry& entry) const; + }; + + //Helper structure - finder of resource_directory_entry that is not named (has id) + struct has_id + { + public: + bool operator()(const resource_directory_entry& entry) const; + }; +}; +} diff --git a/tools/pe_bliss/pe_resources.cpp b/tools/pe_bliss/pe_resources.cpp new file mode 100644 index 0000000000..189aba1f76 --- /dev/null +++ b/tools/pe_bliss/pe_resources.cpp @@ -0,0 +1,726 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <algorithm> +#include <string.h> +#include "pe_resources.h" + +namespace pe_bliss +{ +using namespace pe_win; + +//RESOURCES +//Default constructor +resource_data_entry::resource_data_entry() + :codepage_(0) +{} + +//Constructor from data +resource_data_entry::resource_data_entry(const std::string& data, uint32_t codepage) + :codepage_(codepage), data_(data) +{} + +//Returns resource data codepage +uint32_t resource_data_entry::get_codepage() const +{ + return codepage_; +} + +//Returns resource data +const std::string& resource_data_entry::get_data() const +{ + return data_; +} + +//Sets resource data codepage +void resource_data_entry::set_codepage(uint32_t codepage) +{ + codepage_ = codepage; +} + +//Sets resource data +void resource_data_entry::set_data(const std::string& data) +{ + data_ = data; +} + +//Default constructor +resource_directory_entry::includes::includes() + :data_(0) +{} + +//Default constructor +resource_directory_entry::resource_directory_entry() + :id_(0), includes_data_(false), named_(false) +{} + +//Copy constructor +resource_directory_entry::resource_directory_entry(const resource_directory_entry& other) + :id_(other.id_), name_(other.name_), includes_data_(other.includes_data_), named_(other.named_) +{ + //If union'ed pointer is not zero + if(other.ptr_.data_) + { + if(other.includes_data()) + ptr_.data_ = new resource_data_entry(*other.ptr_.data_); + else + ptr_.dir_ = new resource_directory(*other.ptr_.dir_); + } +} + +//Copy assignment operator +resource_directory_entry& resource_directory_entry::operator=(const resource_directory_entry& other) +{ + release(); + + id_ = other.id_; + name_ = other.name_; + includes_data_ = other.includes_data_; + named_ = other.named_; + + //If other union'ed pointer is not zero + if(other.ptr_.data_) + { + if(other.includes_data()) + ptr_.data_ = new resource_data_entry(*other.ptr_.data_); + else + ptr_.dir_ = new resource_directory(*other.ptr_.dir_); + } + + return *this; +} + +//Destroys included data +void resource_directory_entry::release() +{ + //If union'ed pointer is not zero + if(ptr_.data_) + { + if(includes_data()) + delete ptr_.data_; + else + delete ptr_.dir_; + + ptr_.data_ = 0; + } +} + +//Destructor +resource_directory_entry::~resource_directory_entry() +{ + release(); +} + +//Returns entry ID +uint32_t resource_directory_entry::get_id() const +{ + return id_; +} + +//Returns entry name +const std::wstring& resource_directory_entry::get_name() const +{ + return name_; +} + +//Returns true, if entry has name +//Returns false, if entry has ID +bool resource_directory_entry::is_named() const +{ + return named_; +} + +//Returns true, if entry includes resource_data_entry +//Returns false, if entry includes resource_directory +bool resource_directory_entry::includes_data() const +{ + return includes_data_; +} + +//Returns resource_directory if entry includes it, otherwise throws an exception +const resource_directory& resource_directory_entry::get_resource_directory() const +{ + if(!ptr_.dir_ || includes_data_) + throw pe_exception("Resource directory entry does not contain resource directory", pe_exception::resource_directory_entry_error); + + return *ptr_.dir_; +} + +//Returns resource_data_entry if entry includes it, otherwise throws an exception +const resource_data_entry& resource_directory_entry::get_data_entry() const +{ + if(!ptr_.data_ || !includes_data_) + throw pe_exception("Resource directory entry does not contain resource data entry", pe_exception::resource_directory_entry_error); + + return *ptr_.data_; +} + +//Returns resource_directory if entry includes it, otherwise throws an exception +resource_directory& resource_directory_entry::get_resource_directory() +{ + if(!ptr_.dir_ || includes_data_) + throw pe_exception("Resource directory entry does not contain resource directory", pe_exception::resource_directory_entry_error); + + return *ptr_.dir_; +} + +//Returns resource_data_entry if entry includes it, otherwise throws an exception +resource_data_entry& resource_directory_entry::get_data_entry() +{ + if(!ptr_.data_ || !includes_data_) + throw pe_exception("Resource directory entry does not contain resource data entry", pe_exception::resource_directory_entry_error); + + return *ptr_.data_; +} + +//Sets entry name +void resource_directory_entry::set_name(const std::wstring& name) +{ + name_ = name; + named_ = true; + id_ = 0; +} + +//Sets entry ID +void resource_directory_entry::set_id(uint32_t id) +{ + id_ = id; + named_ = false; + name_.clear(); +} + +//Adds resource_data_entry +void resource_directory_entry::add_data_entry(const resource_data_entry& entry) +{ + release(); + ptr_.data_ = new resource_data_entry(entry); + includes_data_ = true; +} + +//Adds resource_directory +void resource_directory_entry::add_resource_directory(const resource_directory& dir) +{ + release(); + ptr_.dir_ = new resource_directory(dir); + includes_data_ = false; +} + +//Default constructor +resource_directory::resource_directory() + :characteristics_(0), + timestamp_(0), + major_version_(0), minor_version_(0), + number_of_named_entries_(0), number_of_id_entries_(0) +{} + +//Constructor from data +resource_directory::resource_directory(const image_resource_directory& dir) + :characteristics_(dir.Characteristics), + timestamp_(dir.TimeDateStamp), + major_version_(dir.MajorVersion), minor_version_(dir.MinorVersion), + number_of_named_entries_(0), number_of_id_entries_(0) //Set to zero here, calculate on add +{} + +//Returns characteristics of directory +uint32_t resource_directory::get_characteristics() const +{ + return characteristics_; +} + +//Returns date and time stamp of directory +uint32_t resource_directory::get_timestamp() const +{ + return timestamp_; +} + +//Returns major version of directory +uint16_t resource_directory::get_major_version() const +{ + return major_version_; +} + +//Returns minor version of directory +uint16_t resource_directory::get_minor_version() const +{ + return minor_version_; +} + +//Returns number of named entries +uint32_t resource_directory::get_number_of_named_entries() const +{ + return number_of_named_entries_; +} + +//Returns number of ID entries +uint32_t resource_directory::get_number_of_id_entries() const +{ + return number_of_id_entries_; +} + +//Returns resource_directory_entry array +const resource_directory::entry_list& resource_directory::get_entry_list() const +{ + return entries_; +} + +//Returns resource_directory_entry array +resource_directory::entry_list& resource_directory::get_entry_list() +{ + return entries_; +} + +//Adds resource_directory_entry +void resource_directory::add_resource_directory_entry(const resource_directory_entry& entry) +{ + entries_.push_back(entry); + if(entry.is_named()) + ++number_of_named_entries_; + else + ++number_of_id_entries_; +} + +//Clears resource_directory_entry array +void resource_directory::clear_resource_directory_entry_list() +{ + entries_.clear(); + number_of_named_entries_ = 0; + number_of_id_entries_ = 0; +} + +//Sets characteristics of directory +void resource_directory::set_characteristics(uint32_t characteristics) +{ + characteristics_ = characteristics; +} + +//Sets date and time stamp of directory +void resource_directory::set_timestamp(uint32_t timestamp) +{ + timestamp_ = timestamp; +} + +//Sets number of named entries +void resource_directory::set_number_of_named_entries(uint32_t number) +{ + number_of_named_entries_ = number; +} + +//Sets number of ID entries +void resource_directory::set_number_of_id_entries(uint32_t number) +{ + number_of_id_entries_ = number; +} + +//Sets major version of directory +void resource_directory::set_major_version(uint16_t major_version) +{ + major_version_ = major_version; +} + +//Sets minor version of directory +void resource_directory::get_minor_version(uint16_t minor_version) +{ + minor_version_ = minor_version; +} + +//Processes resource directory +const resource_directory process_resource_directory(const pe_base& pe, uint32_t res_rva, uint32_t offset_to_directory, std::set<uint32_t>& processed) +{ + resource_directory ret; + + //Check for resource loops + if(!processed.insert(offset_to_directory).second) + throw pe_exception("Incorrect resource directory", pe_exception::incorrect_resource_directory); + + if(!pe_utils::is_sum_safe(res_rva, offset_to_directory)) + throw pe_exception("Incorrect resource directory", pe_exception::incorrect_resource_directory); + + //Get root IMAGE_RESOURCE_DIRECTORY + image_resource_directory directory = pe.section_data_from_rva<image_resource_directory>(res_rva + offset_to_directory, section_data_virtual, true); + + ret = resource_directory(directory); + + //Check DWORDs for possible overflows + if(!pe_utils::is_sum_safe(directory.NumberOfIdEntries, directory.NumberOfNamedEntries) + || directory.NumberOfIdEntries + directory.NumberOfNamedEntries >= pe_utils::max_dword / sizeof(image_resource_directory_entry) + sizeof(image_resource_directory)) + throw pe_exception("Incorrect resource directory", pe_exception::incorrect_resource_directory); + + if(!pe_utils::is_sum_safe(offset_to_directory, sizeof(image_resource_directory) + (directory.NumberOfIdEntries + directory.NumberOfNamedEntries) * sizeof(image_resource_directory_entry)) + || !pe_utils::is_sum_safe(res_rva, offset_to_directory + sizeof(image_resource_directory) + (directory.NumberOfIdEntries + directory.NumberOfNamedEntries) * sizeof(image_resource_directory_entry))) + throw pe_exception("Incorrect resource directory", pe_exception::incorrect_resource_directory); + + for(unsigned long i = 0; i != static_cast<unsigned long>(directory.NumberOfIdEntries) + directory.NumberOfNamedEntries; ++i) + { + //Read directory entries one by one + image_resource_directory_entry dir_entry = pe.section_data_from_rva<image_resource_directory_entry>( + res_rva + sizeof(image_resource_directory) + i * sizeof(image_resource_directory_entry) + offset_to_directory, section_data_virtual, true); + + //Create directory entry structure + resource_directory_entry entry; + + //If directory is named + if(dir_entry.NameIsString) + { + if(!pe_utils::is_sum_safe(res_rva + sizeof(uint16_t) /* safe */, dir_entry.NameOffset)) + throw pe_exception("Incorrect resource directory", pe_exception::incorrect_resource_directory); + + //get directory name length + uint16_t directory_name_length = pe.section_data_from_rva<uint16_t>(res_rva + dir_entry.NameOffset, section_data_virtual, true); + + //Check name length + if(pe.section_data_length_from_rva(res_rva + dir_entry.NameOffset + sizeof(uint16_t), res_rva + dir_entry.NameOffset + sizeof(uint16_t), section_data_virtual, true) + < directory_name_length) + throw pe_exception("Incorrect resource directory", pe_exception::incorrect_resource_directory); + +#ifdef PE_BLISS_WINDOWS + //Set entry UNICODE name + entry.set_name(std::wstring( + reinterpret_cast<const wchar_t*>(pe.section_data_from_rva(res_rva + dir_entry.NameOffset + sizeof(uint16_t), section_data_virtual, true)), + directory_name_length)); +#else + //Set entry UNICODE name + entry.set_name(pe_utils::from_ucs2(u16string( + reinterpret_cast<const unicode16_t*>(pe.section_data_from_rva(res_rva + dir_entry.NameOffset + sizeof(uint16_t), section_data_virtual, true)), + directory_name_length))); +#endif + } + else + { + //Else - set directory ID + entry.set_id(dir_entry.Id); + } + + //If directory entry has another resource directory + if(dir_entry.DataIsDirectory) + { + entry.add_resource_directory(process_resource_directory(pe, res_rva, dir_entry.OffsetToDirectory, processed)); + } + else + { + //If directory entry has data + image_resource_data_entry data_entry = pe.section_data_from_rva<image_resource_data_entry>( + res_rva + dir_entry.OffsetToData, section_data_virtual, true); + + //Check byte count that stated by data entry + if(pe.section_data_length_from_rva(data_entry.OffsetToData, data_entry.OffsetToData, section_data_virtual, true) < data_entry.Size) + throw pe_exception("Incorrect resource directory", pe_exception::incorrect_resource_directory); + + //Add data entry to directory entry + entry.add_data_entry(resource_data_entry( + std::string(pe.section_data_from_rva(data_entry.OffsetToData, section_data_virtual, true), data_entry.Size), + data_entry.CodePage)); + } + + //Save directory entry + ret.add_resource_directory_entry(entry); + } + + //Return resource directory + return ret; +} + +//Helper function to calculate needed space for resource data +void calculate_resource_data_space(const resource_directory& root, uint32_t aligned_offset_from_section_start, uint32_t& needed_size_for_structures, uint32_t& needed_size_for_strings) +{ + needed_size_for_structures += sizeof(image_resource_directory); + for(resource_directory::entry_list::const_iterator it = root.get_entry_list().begin(); it != root.get_entry_list().end(); ++it) + { + needed_size_for_structures += sizeof(image_resource_directory_entry); + + if((*it).is_named()) + needed_size_for_strings += static_cast<uint32_t>(((*it).get_name().length() + 1) * 2 /* unicode */ + sizeof(uint16_t) /* for string length */); + + if(!(*it).includes_data()) + calculate_resource_data_space((*it).get_resource_directory(), aligned_offset_from_section_start, needed_size_for_structures, needed_size_for_strings); + } +} + +//Helper function to calculate needed space for resource data +void calculate_resource_data_space(const resource_directory& root, uint32_t needed_size_for_structures, uint32_t needed_size_for_strings, uint32_t& needed_size_for_data, uint32_t& current_data_pos) +{ + for(resource_directory::entry_list::const_iterator it = root.get_entry_list().begin(); it != root.get_entry_list().end(); ++it) + { + if((*it).includes_data()) + { + uint32_t data_size = static_cast<uint32_t>((*it).get_data_entry().get_data().length() + + sizeof(image_resource_data_entry) + + (pe_utils::align_up(current_data_pos, sizeof(uint32_t)) - current_data_pos) /* alignment */); + needed_size_for_data += data_size; + current_data_pos += data_size; + } + else + { + calculate_resource_data_space((*it).get_resource_directory(), needed_size_for_structures, needed_size_for_strings, needed_size_for_data, current_data_pos); + } + } +} + +//Helper: sorts resource directory entries +struct entry_sorter +{ +public: + bool operator()(const resource_directory_entry& entry1, const resource_directory_entry& entry2) const; +}; + +//Helper function to rebuild resource directory +void rebuild_resource_directory(pe_base& pe, section& resource_section, resource_directory& root, uint32_t& current_structures_pos, uint32_t& current_data_pos, uint32_t& current_strings_pos, uint32_t offset_from_section_start) +{ + //Create resource directory + image_resource_directory dir = {0}; + dir.Characteristics = root.get_characteristics(); + dir.MajorVersion = root.get_major_version(); + dir.MinorVersion = root.get_minor_version(); + dir.TimeDateStamp = root.get_timestamp(); + + { + resource_directory::entry_list& entries = root.get_entry_list(); + std::sort(entries.begin(), entries.end(), entry_sorter()); + } + + //Calculate number of named and ID entries + for(resource_directory::entry_list::const_iterator it = root.get_entry_list().begin(); it != root.get_entry_list().end(); ++it) + { + if((*it).is_named()) + ++dir.NumberOfNamedEntries; + else + ++dir.NumberOfIdEntries; + } + + std::string& raw_data = resource_section.get_raw_data(); + + //Save resource directory + memcpy(&raw_data[current_structures_pos], &dir, sizeof(dir)); + current_structures_pos += sizeof(dir); + + uint32_t this_current_structures_pos = current_structures_pos; + + current_structures_pos += sizeof(image_resource_directory_entry) * (dir.NumberOfNamedEntries + dir.NumberOfIdEntries); + + //Create all resource directory entries + for(resource_directory::entry_list::iterator it = root.get_entry_list().begin(); it != root.get_entry_list().end(); ++it) + { + image_resource_directory_entry entry; + if((*it).is_named()) + { + entry.Name = 0x80000000 | (current_strings_pos - offset_from_section_start); + uint16_t unicode_length = static_cast<uint16_t>((*it).get_name().length()); + memcpy(&raw_data[current_strings_pos], &unicode_length, sizeof(unicode_length)); + current_strings_pos += sizeof(unicode_length); + +#ifdef PE_BLISS_WINDOWS + memcpy(&raw_data[current_strings_pos], (*it).get_name().c_str(), (*it).get_name().length() * sizeof(uint16_t) + sizeof(uint16_t) /* unicode */); +#else + { + u16string str(pe_utils::to_ucs2((*it).get_name())); + memcpy(&raw_data[current_strings_pos], str.c_str(), (*it).get_name().length() * sizeof(uint16_t) + sizeof(uint16_t) /* unicode */); + } +#endif + + current_strings_pos += static_cast<unsigned long>((*it).get_name().length() * sizeof(uint16_t) + sizeof(uint16_t) /* unicode */); + } + else + { + entry.Name = (*it).get_id(); + } + + if((*it).includes_data()) + { + current_data_pos = pe_utils::align_up(current_data_pos, sizeof(uint32_t)); + image_resource_data_entry data_entry = {0}; + data_entry.CodePage = (*it).get_data_entry().get_codepage(); + data_entry.Size = static_cast<uint32_t>((*it).get_data_entry().get_data().length()); + data_entry.OffsetToData = pe.rva_from_section_offset(resource_section, current_data_pos + sizeof(data_entry)); + + entry.OffsetToData = current_data_pos - offset_from_section_start; + + memcpy(&raw_data[current_data_pos], &data_entry, sizeof(data_entry)); + current_data_pos += sizeof(data_entry); + + memcpy(&raw_data[current_data_pos], (*it).get_data_entry().get_data().data(), data_entry.Size); + current_data_pos += data_entry.Size; + + memcpy(&raw_data[this_current_structures_pos], &entry, sizeof(entry)); + this_current_structures_pos += sizeof(entry); + } + else + { + entry.OffsetToData = 0x80000000 | (current_structures_pos - offset_from_section_start); + + memcpy(&raw_data[this_current_structures_pos], &entry, sizeof(entry)); + this_current_structures_pos += sizeof(entry); + + rebuild_resource_directory(pe, resource_section, (*it).get_resource_directory(), current_structures_pos, current_data_pos, current_strings_pos, offset_from_section_start); + } + } +} + +//Helper function to rebuild resource directory +bool entry_sorter::operator()(const resource_directory_entry& entry1, const resource_directory_entry& entry2) const +{ + if(entry1.is_named() && entry2.is_named()) + return entry1.get_name() < entry2.get_name(); + else if(!entry1.is_named() && !entry2.is_named()) + return entry1.get_id() < entry2.get_id(); + else + return entry1.is_named(); +} + +//Resources rebuilder +//resource_directory - root resource directory +//resources_section - section where resource directory will be placed (must be attached to PE image) +//offset_from_section_start - offset from resources_section raw data start +//resource_directory is non-constant, because it will be sorted +//save_to_pe_headers - if true, new resource directory information will be saved to PE image headers +//auto_strip_last_section - if true and resources are placed in the last section, it will be automatically stripped +//number_of_id_entries and number_of_named_entries for resource directories are recalculated and not used +const image_directory rebuild_resources(pe_base& pe, resource_directory& info, section& resources_section, uint32_t offset_from_section_start, bool save_to_pe_header, bool auto_strip_last_section) +{ + //Check that resources_section is attached to this PE image + if(!pe.section_attached(resources_section)) + throw pe_exception("Resource section must be attached to PE file", pe_exception::section_is_not_attached); + + //Check resource directory correctness + if(info.get_entry_list().empty()) + throw pe_exception("Empty resource directory", pe_exception::incorrect_resource_directory); + + uint32_t aligned_offset_from_section_start = pe_utils::align_up(offset_from_section_start, sizeof(uint32_t)); + uint32_t needed_size_for_structures = aligned_offset_from_section_start - offset_from_section_start; //Calculate needed size for resource tables and data + uint32_t needed_size_for_strings = 0; + uint32_t needed_size_for_data = 0; + + calculate_resource_data_space(info, aligned_offset_from_section_start, needed_size_for_structures, needed_size_for_strings); + + { + uint32_t current_data_pos = aligned_offset_from_section_start + needed_size_for_structures + needed_size_for_strings; + calculate_resource_data_space(info, needed_size_for_structures, needed_size_for_strings, needed_size_for_data, current_data_pos); + } + + uint32_t needed_size = needed_size_for_structures + needed_size_for_strings + needed_size_for_data; + + //Check if resources_section is last one. If it's not, check if there's enough place for resource data + if(&resources_section != &*(pe.get_image_sections().end() - 1) && + (resources_section.empty() || pe_utils::align_up(resources_section.get_size_of_raw_data(), pe.get_file_alignment()) + < needed_size + aligned_offset_from_section_start)) + throw pe_exception("Insufficient space for resource directory", pe_exception::insufficient_space); + + std::string& raw_data = resources_section.get_raw_data(); + + //This will be done only if resources_section is the last section of image or for section with unaligned raw length of data + if(raw_data.length() < needed_size + aligned_offset_from_section_start) + raw_data.resize(needed_size + aligned_offset_from_section_start); //Expand section raw data + + uint32_t current_structures_pos = aligned_offset_from_section_start; + uint32_t current_strings_pos = current_structures_pos + needed_size_for_structures; + uint32_t current_data_pos = current_strings_pos + needed_size_for_strings; + rebuild_resource_directory(pe, resources_section, info, current_structures_pos, current_data_pos, current_strings_pos, aligned_offset_from_section_start); + + //Adjust section raw and virtual sizes + pe.recalculate_section_sizes(resources_section, auto_strip_last_section); + + image_directory ret(pe.rva_from_section_offset(resources_section, aligned_offset_from_section_start), needed_size); + + //If auto-rewrite of PE headers is required + if(save_to_pe_header) + { + pe.set_directory_rva(image_directory_entry_resource, ret.get_rva()); + pe.set_directory_size(image_directory_entry_resource, ret.get_size()); + } + + return ret; +} + +//Returns resources from PE file +const resource_directory get_resources(const pe_base& pe) +{ + resource_directory ret; + + if(!pe.has_resources()) + return ret; + + //Get resource directory RVA + uint32_t res_rva = pe.get_directory_rva(image_directory_entry_resource); + + //Store already processed directories to avoid resource loops + std::set<uint32_t> processed; + + //Process all directories (recursion) + ret = process_resource_directory(pe, res_rva, 0, processed); + + return ret; +} + +//Finds resource_directory_entry by ID +resource_directory::id_entry_finder::id_entry_finder(uint32_t id) + :id_(id) +{} + +bool resource_directory::id_entry_finder::operator()(const resource_directory_entry& entry) const +{ + return !entry.is_named() && entry.get_id() == id_; +} + +//Finds resource_directory_entry by name +resource_directory::name_entry_finder::name_entry_finder(const std::wstring& name) + :name_(name) +{} + +bool resource_directory::name_entry_finder::operator()(const resource_directory_entry& entry) const +{ + return entry.is_named() && entry.get_name() == name_; +} + +//Finds resource_directory_entry by name or ID (universal) +resource_directory::entry_finder::entry_finder(const std::wstring& name) + :name_(name), named_(true) +{} + +resource_directory::entry_finder::entry_finder(uint32_t id) + :id_(id), named_(false) +{} + +bool resource_directory::entry_finder::operator()(const resource_directory_entry& entry) const +{ + if(named_) + return entry.is_named() && entry.get_name() == name_; + else + return !entry.is_named() && entry.get_id() == id_; +} + +//Returns resource_directory_entry by ID. If not found - throws an exception +const resource_directory_entry& resource_directory::entry_by_id(uint32_t id) const +{ + entry_list::const_iterator i = std::find_if(entries_.begin(), entries_.end(), id_entry_finder(id)); + if(i == entries_.end()) + throw pe_exception("Resource directory entry not found", pe_exception::resource_directory_entry_not_found); + + return *i; +} + +//Returns resource_directory_entry by name. If not found - throws an exception +const resource_directory_entry& resource_directory::entry_by_name(const std::wstring& name) const +{ + entry_list::const_iterator i = std::find_if(entries_.begin(), entries_.end(), name_entry_finder(name)); + if(i == entries_.end()) + throw pe_exception("Resource directory entry not found", pe_exception::resource_directory_entry_not_found); + + return *i; +} +} diff --git a/tools/pe_bliss/pe_resources.h b/tools/pe_bliss/pe_resources.h new file mode 100644 index 0000000000..1eb6437563 --- /dev/null +++ b/tools/pe_bliss/pe_resources.h @@ -0,0 +1,245 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <vector> +#include <string> +#include <set> +#include "pe_structures.h" +#include "pe_base.h" +#include "pe_directory.h" + +namespace pe_bliss +{ +//Class representing resource data entry +class resource_data_entry +{ +public: + //Default constructor + resource_data_entry(); + //Constructor from data + resource_data_entry(const std::string& data, uint32_t codepage); + + //Returns resource data codepage + uint32_t get_codepage() const; + //Returns resource data + const std::string& get_data() const; + +public: //These functions do not change everything inside image, they are used by PE class + //You can also use them to rebuild resource directory + + //Sets resource data codepage + void set_codepage(uint32_t codepage); + //Sets resource data + void set_data(const std::string& data); + +private: + uint32_t codepage_; //Resource data codepage + std::string data_; //Resource data +}; + +//Forward declaration +class resource_directory; + +//Class representing resource directory entry +class resource_directory_entry +{ +public: + //Default constructor + resource_directory_entry(); + //Copy constructor + resource_directory_entry(const resource_directory_entry& other); + //Copy assignment operator + resource_directory_entry& operator=(const resource_directory_entry& other); + + //Returns entry ID + uint32_t get_id() const; + //Returns entry name + const std::wstring& get_name() const; + //Returns true, if entry has name + //Returns false, if entry has ID + bool is_named() const; + + //Returns true, if entry includes resource_data_entry + //Returns false, if entry includes resource_directory + bool includes_data() const; + //Returns resource_directory if entry includes it, otherwise throws an exception + const resource_directory& get_resource_directory() const; + //Returns resource_data_entry if entry includes it, otherwise throws an exception + const resource_data_entry& get_data_entry() const; + + //Destructor + ~resource_directory_entry(); + +public: //These functions do not change everything inside image, they are used by PE class + //You can also use them to rebuild resource directory + + //Sets entry name + void set_name(const std::wstring& name); + //Sets entry ID + void set_id(uint32_t id); + + //Returns resource_directory if entry includes it, otherwise throws an exception + resource_directory& get_resource_directory(); + //Returns resource_data_entry if entry includes it, otherwise throws an exception + resource_data_entry& get_data_entry(); + + //Adds resource_data_entry + void add_data_entry(const resource_data_entry& entry); + //Adds resource_directory + void add_resource_directory(const resource_directory& dir); + +private: + //Destroys included data + void release(); + +private: + uint32_t id_; + std::wstring name_; + + union includes + { + //Default constructor + includes(); + + //We use pointers, we're doing manual copying here + class resource_data_entry* data_; + class resource_directory* dir_; //We use pointer, because structs include each other + }; + + includes ptr_; + + bool includes_data_, named_; +}; + +//Class representing resource directory +class resource_directory +{ +public: + typedef std::vector<resource_directory_entry> entry_list; + +public: + //Default constructor + resource_directory(); + //Constructor from data + explicit resource_directory(const pe_win::image_resource_directory& dir); + + //Returns characteristics of directory + uint32_t get_characteristics() const; + //Returns date and time stamp of directory + uint32_t get_timestamp() const; + //Returns number of named entries + uint32_t get_number_of_named_entries() const; + //Returns number of ID entries + uint32_t get_number_of_id_entries() const; + //Returns major version of directory + uint16_t get_major_version() const; + //Returns minor version of directory + uint16_t get_minor_version() const; + //Returns resource_directory_entry array + const entry_list& get_entry_list() const; + //Returns resource_directory_entry by ID. If not found - throws an exception + const resource_directory_entry& entry_by_id(uint32_t id) const; + //Returns resource_directory_entry by name. If not found - throws an exception + const resource_directory_entry& entry_by_name(const std::wstring& name) const; + +public: //These functions do not change everything inside image, they are used by PE class + //You can also use them to rebuild resource directory + + //Adds resource_directory_entry + void add_resource_directory_entry(const resource_directory_entry& entry); + //Clears resource_directory_entry array + void clear_resource_directory_entry_list(); + + //Sets characteristics of directory + void set_characteristics(uint32_t characteristics); + //Sets date and time stamp of directory + void set_timestamp(uint32_t timestamp); + //Sets number of named entries + void set_number_of_named_entries(uint32_t number); + //Sets number of ID entries + void set_number_of_id_entries(uint32_t number); + //Sets major version of directory + void set_major_version(uint16_t major_version); + //Sets minor version of directory + void get_minor_version(uint16_t minor_version); + + //Returns resource_directory_entry array + entry_list& get_entry_list(); + +private: + uint32_t characteristics_; + uint32_t timestamp_; + uint16_t major_version_, minor_version_; + uint32_t number_of_named_entries_, number_of_id_entries_; + entry_list entries_; + +public: //Finder helpers + //Finds resource_directory_entry by ID + struct id_entry_finder + { + public: + explicit id_entry_finder(uint32_t id); + bool operator()(const resource_directory_entry& entry) const; + + private: + uint32_t id_; + }; + + //Finds resource_directory_entry by name + struct name_entry_finder + { + public: + explicit name_entry_finder(const std::wstring& name); + bool operator()(const resource_directory_entry& entry) const; + + private: + std::wstring name_; + }; + + //Finds resource_directory_entry by name or ID (universal) + struct entry_finder + { + public: + explicit entry_finder(const std::wstring& name); + explicit entry_finder(uint32_t id); + bool operator()(const resource_directory_entry& entry) const; + + private: + std::wstring name_; + uint32_t id_; + bool named_; + }; +}; + +//Returns resources (root resource_directory) from PE file +const resource_directory get_resources(const pe_base& pe); + +//Resources rebuilder +//resource_directory - root resource directory +//resources_section - section where resource directory will be placed (must be attached to PE image) +//resource_directory is non-constant, because it will be sorted +//offset_from_section_start - offset from resources_section raw data start +//save_to_pe_headers - if true, new resource directory information will be saved to PE image headers +//auto_strip_last_section - if true and resources are placed in the last section, it will be automatically stripped +//number_of_id_entries and number_of_named_entries for resource directories are recalculated and not used +const image_directory rebuild_resources(pe_base& pe, resource_directory& info, section& resources_section, uint32_t offset_from_section_start = 0, bool save_to_pe_header = true, bool auto_strip_last_section = true); +} diff --git a/tools/pe_bliss/pe_rich_data.cpp b/tools/pe_bliss/pe_rich_data.cpp new file mode 100644 index 0000000000..e92f7ddc1b --- /dev/null +++ b/tools/pe_bliss/pe_rich_data.cpp @@ -0,0 +1,152 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include "pe_rich_data.h" + +namespace pe_bliss +{ +//STUB OVERLAY +//Default constructor +rich_data::rich_data() + :number_(0), version_(0), times_(0) +{} + +//Who knows, what these fields mean... +uint32_t rich_data::get_number() const +{ + return number_; +} + +uint32_t rich_data::get_version() const +{ + return version_; +} + +uint32_t rich_data::get_times() const +{ + return times_; +} + +void rich_data::set_number(uint32_t number) +{ + number_ = number; +} + +void rich_data::set_version(uint32_t version) +{ + version_ = version; +} + +void rich_data::set_times(uint32_t times) +{ + times_ = times; +} + +//Returns MSVC rich data +const rich_data_list get_rich_data(const pe_base& pe) +{ + //Returned value + rich_data_list ret; + + const std::string& rich_overlay = pe.get_stub_overlay(); + + //If there's no rich overlay, return empty vector + if(rich_overlay.size() < sizeof(uint32_t)) + return ret; + + //True if rich data was found + bool found = false; + + //Rich overlay ID ("Rich" word) + static const uint32_t rich_overlay_id = 0x68636952; + + //Search for rich data overlay ID + const char* begin = &rich_overlay[0]; + const char* end = begin + rich_overlay.length(); + for(; begin != end; ++begin) + { + if(*reinterpret_cast<const uint32_t*>(begin) == rich_overlay_id) + { + found = true; //We've found it! + break; + } + } + + //If we found it + if(found) + { + //Check remaining length + if(static_cast<size_t>(end - begin) < sizeof(uint32_t)) + return ret; + + //The XOR key is after "Rich" word, we should get it + uint32_t xorkey = *reinterpret_cast<const uint32_t*>(begin + sizeof(uint32_t)); + + //True if rich data was found + found = false; + + //Second search for signature "DanS" + begin = &rich_overlay[0]; + for(; begin != end; ++begin) + { + if((*reinterpret_cast<const uint32_t*>(begin) ^ xorkey) == 0x536e6144) //"DanS" + { + found = true; + break; + } + } + + //If second signature is found + if(found) + { + begin += sizeof(uint32_t) * 3; + //List all rich data structures + while(begin < end) + { + begin += sizeof(uint32_t); + if(begin >= end) + break; + + //Check for rich overlay data end ("Rich" word reached) + if(*reinterpret_cast<const uint32_t*>(begin) == rich_overlay_id) + break; + + //Create rich_data structure + rich_data data; + data.set_number((*reinterpret_cast<const uint32_t*>(begin) ^ xorkey) >> 16); + data.set_version((*reinterpret_cast<const uint32_t*>(begin) ^ xorkey) & 0xFFFF); + + begin += sizeof(uint32_t); + if(begin >= end) + break; + + data.set_times(*reinterpret_cast<const uint32_t*>(begin) ^ xorkey); + + //Save rich data structure + ret.push_back(data); + } + } + } + + //Return rich data structures list + return ret; +} +} diff --git a/tools/pe_bliss/pe_rich_data.h b/tools/pe_bliss/pe_rich_data.h new file mode 100644 index 0000000000..3e01d3c011 --- /dev/null +++ b/tools/pe_bliss/pe_rich_data.h @@ -0,0 +1,58 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <vector> +#include "pe_structures.h" +#include "pe_base.h" + +namespace pe_bliss +{ +//Rich data overlay class of Microsoft Visual Studio +class rich_data +{ +public: + //Default constructor + rich_data(); + +public: //Getters + //Who knows, what these fields mean... + uint32_t get_number() const; + uint32_t get_version() const; + uint32_t get_times() const; + +public: //Setters, used by PE library only + void set_number(uint32_t number); + void set_version(uint32_t version); + void set_times(uint32_t times); + +private: + uint32_t number_; + uint32_t version_; + uint32_t times_; +}; + +//Rich data list typedef +typedef std::vector<rich_data> rich_data_list; + +//Returns a vector with rich data (stub overlay) +const rich_data_list get_rich_data(const pe_base& pe); +} diff --git a/tools/pe_bliss/pe_section.cpp b/tools/pe_bliss/pe_section.cpp new file mode 100644 index 0000000000..72127e22e2 --- /dev/null +++ b/tools/pe_bliss/pe_section.cpp @@ -0,0 +1,303 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <algorithm> +#include <string.h> +#include "utils.h" +#include "pe_section.h" + +namespace pe_bliss +{ +using namespace pe_win; + +//Section structure default constructor +section::section() + :old_size_(static_cast<size_t>(-1)) +{ + memset(&header_, 0, sizeof(image_section_header)); +} + +//Sets the name of section (8 characters maximum) +void section::set_name(const std::string& name) +{ + memset(header_.Name, 0, sizeof(header_.Name)); + memcpy(header_.Name, name.c_str(), std::min<size_t>(name.length(), sizeof(header_.Name))); +} + +//Returns section name +const std::string section::get_name() const +{ + char buf[9] = {0}; + memcpy(buf, header_.Name, 8); + return std::string(buf); +} + +//Set flag (attribute) of section +section& section::set_flag(uint32_t flag, bool setflag) +{ + if(setflag) + header_.Characteristics |= flag; + else + header_.Characteristics &= ~flag; + + return *this; +} + +//Sets "readable" attribute of section +section& section::readable(bool readable) +{ + return set_flag(image_scn_mem_read, readable); +} + +//Sets "writeable" attribute of section +section& section::writeable(bool writeable) +{ + return set_flag(image_scn_mem_write, writeable); +} + +//Sets "executable" attribute of section +section& section::executable(bool executable) +{ + return set_flag(image_scn_mem_execute, executable); +} + +//Sets "shared" attribute of section +section& section::shared(bool shared) +{ + return set_flag(image_scn_mem_shared, shared); +} + +//Sets "discardable" attribute of section +section& section::discardable(bool discardable) +{ + return set_flag(image_scn_mem_discardable, discardable); +} + +//Returns true if section is readable +bool section::readable() const +{ + return (header_.Characteristics & image_scn_mem_read) != 0; +} + +//Returns true if section is writeable +bool section::writeable() const +{ + return (header_.Characteristics & image_scn_mem_write) != 0; +} + +//Returns true if section is executable +bool section::executable() const +{ + return (header_.Characteristics & image_scn_mem_execute) != 0; +} + +bool section::shared() const +{ + return (header_.Characteristics & image_scn_mem_shared) != 0; +} + +bool section::discardable() const +{ + return (header_.Characteristics & image_scn_mem_discardable) != 0; +} + +//Returns true if section has no RAW data +bool section::empty() const +{ + if(old_size_ != static_cast<size_t>(-1)) //If virtual memory is mapped, check raw data length (old_size_) + return old_size_ == 0; + else + return raw_data_.empty(); +} + +//Returns raw section data from file image +std::string& section::get_raw_data() +{ + unmap_virtual(); + return raw_data_; +} + +//Sets raw section data from file image +void section::set_raw_data(const std::string& data) +{ + old_size_ = static_cast<size_t>(-1); + raw_data_ = data; +} + +//Returns raw section data from file image +const std::string& section::get_raw_data() const +{ + unmap_virtual(); + return raw_data_; +} + +//Returns mapped virtual section data +const std::string& section::get_virtual_data(uint32_t section_alignment) const +{ + map_virtual(section_alignment); + return raw_data_; +} + +//Returns mapped virtual section data +std::string& section::get_virtual_data(uint32_t section_alignment) +{ + map_virtual(section_alignment); + return raw_data_; +} + +//Maps virtual section data +void section::map_virtual(uint32_t section_alignment) const +{ + uint32_t aligned_virtual_size = get_aligned_virtual_size(section_alignment); + if(old_size_ == static_cast<size_t>(-1) && aligned_virtual_size && aligned_virtual_size > raw_data_.length()) + { + old_size_ = raw_data_.length(); + raw_data_.resize(aligned_virtual_size, 0); + } +} + +//Unmaps virtual section data +void section::unmap_virtual() const +{ + if(old_size_ != static_cast<size_t>(-1)) + { + raw_data_.resize(old_size_, 0); + old_size_ = static_cast<size_t>(-1); + } +} + +//Returns section virtual size +uint32_t section::get_virtual_size() const +{ + return header_.Misc.VirtualSize; +} + +//Returns section virtual address +uint32_t section::get_virtual_address() const +{ + return header_.VirtualAddress; +} + +//Returns size of section raw data +uint32_t section::get_size_of_raw_data() const +{ + return header_.SizeOfRawData; +} + +//Returns pointer to raw section data in PE file +uint32_t section::get_pointer_to_raw_data() const +{ + return header_.PointerToRawData; +} + +//Returns section characteristics +uint32_t section::get_characteristics() const +{ + return header_.Characteristics; +} + +//Returns raw image section header +const pe_win::image_section_header& section::get_raw_header() const +{ + return header_; +} + +//Returns raw image section header +pe_win::image_section_header& section::get_raw_header() +{ + return header_; +} + +//Calculates aligned virtual section size +uint32_t section::get_aligned_virtual_size(uint32_t section_alignment) const +{ + if(get_size_of_raw_data()) + { + if(!get_virtual_size()) + { + //If section virtual size is zero + //Set aligned virtual size of section as aligned raw size + return pe_utils::align_up(get_size_of_raw_data(), section_alignment); + } + } + + return pe_utils::align_up(get_virtual_size(), section_alignment); +} + +//Calculates aligned raw section size +uint32_t section::get_aligned_raw_size(uint32_t file_alignment) const +{ + if(get_size_of_raw_data()) + return pe_utils::align_up(get_size_of_raw_data(), file_alignment); + else + return 0; +} + +//Sets size of raw section data +void section::set_size_of_raw_data(uint32_t size_of_raw_data) +{ + header_.SizeOfRawData = size_of_raw_data; +} + +//Sets pointer to section raw data +void section::set_pointer_to_raw_data(uint32_t pointer_to_raw_data) +{ + header_.PointerToRawData = pointer_to_raw_data; +} + +//Sets section characteristics +void section::set_characteristics(uint32_t characteristics) +{ + header_.Characteristics = characteristics; +} + +//Sets section virtual size +void section::set_virtual_size(uint32_t virtual_size) +{ + header_.Misc.VirtualSize = virtual_size; +} + +//Sets section virtual address +void section::set_virtual_address(uint32_t virtual_address) +{ + header_.VirtualAddress = virtual_address; +} + +//Section by file offset finder helper (4gb max) +section_by_raw_offset::section_by_raw_offset(uint32_t offset) + :offset_(offset) +{} + +bool section_by_raw_offset::operator()(const section& s) const +{ + return (s.get_pointer_to_raw_data() <= offset_) + && (s.get_pointer_to_raw_data() + s.get_size_of_raw_data() > offset_); +} + +section_ptr_finder::section_ptr_finder(const section& s) + :s_(s) +{} + +bool section_ptr_finder::operator()(const section& s) const +{ + return &s == &s_; +} +} diff --git a/tools/pe_bliss/pe_section.h b/tools/pe_bliss/pe_section.h new file mode 100644 index 0000000000..617ecebe26 --- /dev/null +++ b/tools/pe_bliss/pe_section.h @@ -0,0 +1,158 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <string> +#include <vector> +#include "pe_structures.h" + +namespace pe_bliss +{ +//Enumeration of section data types, used in functions below +enum section_data_type +{ + section_data_raw, + section_data_virtual +}; + +//Class representing image section +class section +{ +public: + //Default constructor + section(); + + //Sets the name of section (stripped to 8 characters) + void set_name(const std::string& name); + + //Returns the name of section + const std::string get_name() const; + + //Changes attributes of section + section& readable(bool readable); + section& writeable(bool writeable); + section& executable(bool executable); + section& shared(bool shared); + section& discardable(bool discardable); + + //Returns attributes of section + bool readable() const; + bool writeable() const; + bool executable() const; + bool shared() const; + bool discardable() const; + + //Returns true if section has no RAW data + bool empty() const; + + //Returns raw section data from file image + std::string& get_raw_data(); + //Returns raw section data from file image + const std::string& get_raw_data() const; + //Returns mapped virtual section data + const std::string& get_virtual_data(uint32_t section_alignment) const; + //Returns mapped virtual section data + std::string& get_virtual_data(uint32_t section_alignment); + +public: //Header getters + //Returns section virtual size + uint32_t get_virtual_size() const; + //Returns section virtual address (RVA) + uint32_t get_virtual_address() const; + //Returns size of section raw data + uint32_t get_size_of_raw_data() const; + //Returns pointer to raw section data in PE file + uint32_t get_pointer_to_raw_data() const; + //Returns section characteristics + uint32_t get_characteristics() const; + + //Returns raw image section header + const pe_win::image_section_header& get_raw_header() const; + +public: //Aligned sizes calculation + //Calculates aligned virtual section size + uint32_t get_aligned_virtual_size(uint32_t section_alignment) const; + //Calculates aligned raw section size + uint32_t get_aligned_raw_size(uint32_t file_alignment) const; + +public: //Setters + //Sets size of raw section data + void set_size_of_raw_data(uint32_t size_of_raw_data); + //Sets pointer to section raw data + void set_pointer_to_raw_data(uint32_t pointer_to_raw_data); + //Sets section characteristics + void set_characteristics(uint32_t characteristics); + //Sets raw section data from file image + void set_raw_data(const std::string& data); + +public: //Setters, be careful + //Sets section virtual size (doesn't set internal aligned virtual size, changes only header value) + //Better use pe_base::set_section_virtual_size + void set_virtual_size(uint32_t virtual_size); + //Sets section virtual address + void set_virtual_address(uint32_t virtual_address); + //Returns raw image section header + pe_win::image_section_header& get_raw_header(); + +private: + //Section header + pe_win::image_section_header header_; + + //Maps virtual section data + void map_virtual(uint32_t section_alignment) const; + + //Unmaps virtual section data + void unmap_virtual() const; + + //Set flag (attribute) of section + section& set_flag(uint32_t flag, bool setflag); + + //Old size of section (stored after mapping of virtual section memory) + mutable std::size_t old_size_; + + //Section raw/virtual data + mutable std::string raw_data_; +}; + +//Section by file offset finder helper (4gb max) +struct section_by_raw_offset +{ +public: + explicit section_by_raw_offset(uint32_t offset); + bool operator()(const section& s) const; + +private: + uint32_t offset_; +}; + +//Helper: finder of section* in sections list +struct section_ptr_finder +{ +public: + explicit section_ptr_finder(const section& s); + bool operator()(const section& s) const; + +private: + const section& s_; +}; + +typedef std::vector<section> section_list; +} diff --git a/tools/pe_bliss/pe_structures.h b/tools/pe_bliss/pe_structures.h new file mode 100644 index 0000000000..efc99103b2 --- /dev/null +++ b/tools/pe_bliss/pe_structures.h @@ -0,0 +1,1028 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <string> +#include <sstream> +#include "stdint_defs.h" +#if defined(_MSC_VER) or defined(__MINGW32__) +#define PE_BLISS_WINDOWS +#endif + +namespace pe_bliss +{ +//Enumeration of PE types +enum pe_type +{ + pe_type_32, + pe_type_64 +}; + +namespace pe_win +{ +const uint32_t image_numberof_directory_entries = 16; +const uint32_t image_nt_optional_hdr32_magic = 0x10b; +const uint32_t image_nt_optional_hdr64_magic = 0x20b; +const uint32_t image_resource_name_is_string = 0x80000000; +const uint32_t image_resource_data_is_directory = 0x80000000; + +const uint32_t image_dllcharacteristics_dynamic_base = 0x0040; // DLL can move. +const uint32_t image_dllcharacteristics_force_integrity = 0x0080; // Code Integrity Image +const uint32_t image_dllcharacteristics_nx_compat = 0x0100; // Image is NX compatible +const uint32_t image_dllcharacteristics_no_isolation = 0x0200; // Image understands isolation and doesn't want it +const uint32_t image_dllcharacteristics_no_seh = 0x0400; // Image does not use SEH. No SE handler may reside in this image +const uint32_t image_dllcharacteristics_no_bind = 0x0800; // Do not bind this image. +const uint32_t image_dllcharacteristics_wdm_driver = 0x2000; // Driver uses WDM model +const uint32_t image_dllcharacteristics_terminal_server_aware = 0x8000; + +const uint32_t image_sizeof_file_header = 20; + +const uint32_t image_file_relocs_stripped = 0x0001; // Relocation info stripped from file. +const uint32_t image_file_executable_image = 0x0002; // File is executable (i.e. no unresolved externel references). +const uint32_t image_file_line_nums_stripped = 0x0004; // Line nunbers stripped from file. +const uint32_t image_file_local_syms_stripped = 0x0008; // Local symbols stripped from file. +const uint32_t image_file_aggresive_ws_trim = 0x0010; // Agressively trim working set +const uint32_t image_file_large_address_aware = 0x0020; // App can handle >2gb addresses +const uint32_t image_file_bytes_reversed_lo = 0x0080; // Bytes of machine word are reversed. +const uint32_t image_file_32bit_machine = 0x0100; // 32 bit word machine. +const uint32_t image_file_debug_stripped = 0x0200; // Debugging info stripped from file in .DBG file +const uint32_t image_file_removable_run_from_swap = 0x0400; // If Image is on removable media, copy and run from the swap file. +const uint32_t image_file_net_run_from_swap = 0x0800; // If Image is on Net, copy and run from the swap file. +const uint32_t image_file_system = 0x1000; // System File. +const uint32_t image_file_dll = 0x2000; // File is a DLL. +const uint32_t image_file_up_system_only = 0x4000; // File should only be run on a UP machine +const uint32_t image_file_bytes_reversed_hi = 0x8000; // Bytes of machine word are reversed. + +const uint32_t image_scn_lnk_nreloc_ovfl = 0x01000000; // Section contains extended relocations. +const uint32_t image_scn_mem_discardable = 0x02000000; // Section can be discarded. +const uint32_t image_scn_mem_not_cached = 0x04000000; // Section is not cachable. +const uint32_t image_scn_mem_not_paged = 0x08000000; // Section is not pageable. +const uint32_t image_scn_mem_shared = 0x10000000; // Section is shareable. +const uint32_t image_scn_mem_execute = 0x20000000; // Section is executable. +const uint32_t image_scn_mem_read = 0x40000000; // Section is readable. +const uint32_t image_scn_mem_write = 0x80000000; // Section is writeable. + +const uint32_t image_scn_cnt_code = 0x00000020; // Section contains code. +const uint32_t image_scn_cnt_initialized_data = 0x00000040; // Section contains initialized data. +const uint32_t image_scn_cnt_uninitialized_data = 0x00000080; // Section contains uninitialized data. + +//Directory Entries +const uint32_t image_directory_entry_export = 0; // Export Directory +const uint32_t image_directory_entry_import = 1; // Import Directory +const uint32_t image_directory_entry_resource = 2; // Resource Directory +const uint32_t image_directory_entry_exception = 3; // Exception Directory +const uint32_t image_directory_entry_security = 4; // Security Directory +const uint32_t image_directory_entry_basereloc = 5; // Base Relocation Table +const uint32_t image_directory_entry_debug = 6; // Debug Directory +const uint32_t image_directory_entry_architecture = 7; // Architecture Specific Data +const uint32_t image_directory_entry_globalptr = 8; // RVA of GP +const uint32_t image_directory_entry_tls = 9; // TLS Directory +const uint32_t image_directory_entry_load_config = 10; // Load Configuration Directory +const uint32_t image_directory_entry_bound_import = 11; // Bound Import Directory in headers +const uint32_t image_directory_entry_iat = 12; // Import Address Table +const uint32_t image_directory_entry_delay_import = 13; // Delay Load Import Descriptors +const uint32_t image_directory_entry_com_descriptor = 14; // COM Runtime descriptor + +//Subsystem Values +const uint32_t image_subsystem_unknown = 0; // Unknown subsystem. +const uint32_t image_subsystem_native = 1; // Image doesn't require a subsystem. +const uint32_t image_subsystem_windows_gui = 2; // Image runs in the Windows GUI subsystem. +const uint32_t image_subsystem_windows_cui = 3; // Image runs in the Windows character subsystem. +const uint32_t image_subsystem_os2_cui = 5; // image runs in the OS/2 character subsystem. +const uint32_t image_subsystem_posix_cui = 7; // image runs in the Posix character subsystem. +const uint32_t image_subsystem_native_windows = 8; // image is a native Win9x driver. +const uint32_t image_subsystem_windows_ce_gui = 9; // Image runs in the Windows CE subsystem. +const uint32_t image_subsystem_efi_application = 10; // +const uint32_t image_subsystem_efi_boot_service_driver = 11; // +const uint32_t image_subsystem_efi_runtime_driver = 12; // +const uint32_t image_subsystem_efi_rom = 13; +const uint32_t image_subsystem_xbox = 14; +const uint32_t image_subsystem_windows_boot_application = 16; + +//Imports +const uint64_t image_ordinal_flag64 = 0x8000000000000000ull; +const uint32_t image_ordinal_flag32 = 0x80000000; + +//Based relocation types +const uint32_t image_rel_based_absolute = 0; +const uint32_t image_rel_based_high = 1; +const uint32_t image_rel_based_low = 2; +const uint32_t image_rel_based_highlow = 3; +const uint32_t image_rel_based_highadj = 4; +const uint32_t image_rel_based_mips_jmpaddr = 5; +const uint32_t image_rel_based_mips_jmpaddr16 = 9; +const uint32_t image_rel_based_ia64_imm64 = 9; +const uint32_t image_rel_based_dir64 = 10; + +//Exception directory +//The function has an exception handler that should be called when looking for functions that need to examine exceptions +const uint32_t unw_flag_ehandler = 0x01; +//The function has a termination handler that should be called when unwinding an exception +const uint32_t unw_flag_uhandler = 0x02; +//This unwind info structure is not the primary one for the procedure. +//Instead, the chained unwind info entry is the contents of a previous RUNTIME_FUNCTION entry. +//If this flag is set, then the UNW_FLAG_EHANDLER and UNW_FLAG_UHANDLER flags must be cleared. +//Also, the frame register and fixed-stack allocation fields must have the same values as in the primary unwind info +const uint32_t unw_flag_chaininfo = 0x04; + +//Debug +const uint32_t image_debug_misc_exename = 1; +const uint32_t image_debug_type_unknown = 0; +const uint32_t image_debug_type_coff = 1; +const uint32_t image_debug_type_codeview = 2; +const uint32_t image_debug_type_fpo = 3; +const uint32_t image_debug_type_misc = 4; +const uint32_t image_debug_type_exception = 5; +const uint32_t image_debug_type_fixup = 6; +const uint32_t image_debug_type_omap_to_src = 7; +const uint32_t image_debug_type_omap_from_src = 8; +const uint32_t image_debug_type_borland = 9; +const uint32_t image_debug_type_reserved10 = 10; +const uint32_t image_debug_type_clsid = 11; + + +//Storage classes +const uint32_t image_sym_class_end_of_function = static_cast<uint8_t>(-1); +const uint32_t image_sym_class_null = 0x0000; +const uint32_t image_sym_class_automatic = 0x0001; +const uint32_t image_sym_class_external = 0x0002; +const uint32_t image_sym_class_static = 0x0003; +const uint32_t image_sym_class_register = 0x0004; +const uint32_t image_sym_class_external_def = 0x0005; +const uint32_t image_sym_class_label = 0x0006; +const uint32_t image_sym_class_undefined_label = 0x0007; +const uint32_t image_sym_class_member_of_struct = 0x0008; +const uint32_t image_sym_class_argument = 0x0009; +const uint32_t image_sym_class_struct_tag = 0x000a; +const uint32_t image_sym_class_member_of_union = 0x000b; +const uint32_t image_sym_class_union_tag = 0x000c; +const uint32_t image_sym_class_type_definition = 0x000d; +const uint32_t image_sym_class_undefined_static = 0x000e; +const uint32_t image_sym_class_enum_tag = 0x000f; +const uint32_t image_sym_class_member_of_enum = 0x0010; +const uint32_t image_sym_class_register_param = 0x0011; +const uint32_t image_sym_class_bit_field = 0x0012; + +const uint32_t image_sym_class_far_external = 0x0044; + +const uint32_t image_sym_class_block = 0x0064; +const uint32_t image_sym_class_function = 0x0065; +const uint32_t image_sym_class_end_of_struct = 0x0066; +const uint32_t image_sym_class_file = 0x0067; + +const uint32_t image_sym_class_section = 0x0068; +const uint32_t image_sym_class_weak_external = 0x0069; + +const uint32_t image_sym_class_clr_token = 0x006b; + +//type packing constants +const uint32_t n_btmask = 0x000f; +const uint32_t n_tmask = 0x0030; +const uint32_t n_tmask1 = 0x00c0; +const uint32_t n_tmask2 = 0x00f0; +const uint32_t n_btshft = 4; +const uint32_t n_tshift = 2; + +//Type (derived) values. +const uint32_t image_sym_dtype_null = 0; // no derived type. +const uint32_t image_sym_dtype_pointer = 1; // pointer. +const uint32_t image_sym_dtype_function = 2; // function. +const uint32_t image_sym_dtype_array = 3; // array. + +// Is x a function? +//TODO +#ifndef ISFCN +#define ISFCN(x) (((x) & n_tmask) == (image_sym_dtype_function << n_btshft)) +#endif + +//Version info +const uint32_t vs_ffi_fileflagsmask = 0x0000003FL; + +const uint32_t vs_ffi_signature = 0xFEEF04BDL; +const uint32_t vs_ffi_strucversion = 0x00010000L; + +/* ----- VS_VERSION.dwFileFlags ----- */ +const uint32_t vs_ff_debug = 0x00000001L; +const uint32_t vs_ff_prerelease = 0x00000002L; +const uint32_t vs_ff_patched = 0x00000004L; +const uint32_t vs_ff_privatebuild = 0x00000008L; +const uint32_t vs_ff_infoinferred = 0x00000010L; +const uint32_t vs_ff_specialbuild = 0x00000020L; + +/* ----- VS_VERSION.dwFileOS ----- */ +const uint32_t vos_unknown = 0x00000000L; +const uint32_t vos_dos = 0x00010000L; +const uint32_t vos_os216 = 0x00020000L; +const uint32_t vos_os232 = 0x00030000L; +const uint32_t vos_nt = 0x00040000L; +const uint32_t vos_wince = 0x00050000L; + +const uint32_t vos__base = 0x00000000L; +const uint32_t vos__windows16 = 0x00000001L; +const uint32_t vos__pm16 = 0x00000002L; +const uint32_t vos__pm32 = 0x00000003L; +const uint32_t vos__windows32 = 0x00000004L; + +const uint32_t vos_dos_windows16 = 0x00010001L; +const uint32_t vos_dos_windows32 = 0x00010004L; +const uint32_t vos_os216_pm16 = 0x00020002L; +const uint32_t vos_os232_pm32 = 0x00030003L; +const uint32_t vos_nt_windows32 = 0x00040004L; + +/* ----- VS_VERSION.dwFileType ----- */ +const uint32_t vft_unknown = 0x00000000L; +const uint32_t vft_app = 0x00000001L; +const uint32_t vft_dll = 0x00000002L; +const uint32_t vft_drv = 0x00000003L; +const uint32_t vft_font = 0x00000004L; +const uint32_t vft_vxd = 0x00000005L; +const uint32_t vft_static_lib = 0x00000007L; + +const uint32_t message_resource_unicode = 0x0001; + +#pragma pack(push, 1) + +//Windows GUID structure +struct guid +{ + uint32_t Data1; + uint16_t Data2; + uint16_t Data3; + uint8_t Data4[8]; +}; + +//DOS .EXE header +struct image_dos_header +{ + uint16_t e_magic; // Magic number + uint16_t e_cblp; // Bytes on last page of file + uint16_t e_cp; // Pages in file + uint16_t e_crlc; // Relocations + uint16_t e_cparhdr; // Size of header in paragraphs + uint16_t e_minalloc; // Minimum extra paragraphs needed + uint16_t e_maxalloc; // Maximum extra paragraphs needed + uint16_t e_ss; // Initial (relative) SS value + uint16_t e_sp; // Initial SP value + uint16_t e_csum; // Checksum + uint16_t e_ip; // Initial IP value + uint16_t e_cs; // Initial (relative) CS value + uint16_t e_lfarlc; // File address of relocation table + uint16_t e_ovno; // Overlay number + uint16_t e_res[4]; // Reserved words + uint16_t e_oemid; // OEM identifier (for e_oeminfo) + uint16_t e_oeminfo; // OEM information; e_oemid specific + uint16_t e_res2[10]; // Reserved words + int32_t e_lfanew; // File address of new exe header +}; + +//Directory format +struct image_data_directory +{ + uint32_t VirtualAddress; + uint32_t Size; +}; + +//Optional header format +struct image_optional_header32 +{ + //Standard fields + uint16_t Magic; + uint8_t MajorLinkerVersion; + uint8_t MinorLinkerVersion; + uint32_t SizeOfCode; + uint32_t SizeOfInitializedData; + uint32_t SizeOfUninitializedData; + uint32_t AddressOfEntryPoint; + uint32_t BaseOfCode; + uint32_t BaseOfData; + + //NT additional fields + uint32_t ImageBase; + uint32_t SectionAlignment; + uint32_t FileAlignment; + uint16_t MajorOperatingSystemVersion; + uint16_t MinorOperatingSystemVersion; + uint16_t MajorImageVersion; + uint16_t MinorImageVersion; + uint16_t MajorSubsystemVersion; + uint16_t MinorSubsystemVersion; + uint32_t Win32VersionValue; + uint32_t SizeOfImage; + uint32_t SizeOfHeaders; + uint32_t CheckSum; + uint16_t Subsystem; + uint16_t DllCharacteristics; + uint32_t SizeOfStackReserve; + uint32_t SizeOfStackCommit; + uint32_t SizeOfHeapReserve; + uint32_t SizeOfHeapCommit; + uint32_t LoaderFlags; + uint32_t NumberOfRvaAndSizes; + image_data_directory DataDirectory[image_numberof_directory_entries]; +}; + +struct image_optional_header64 +{ + uint16_t Magic; + uint8_t MajorLinkerVersion; + uint8_t MinorLinkerVersion; + uint32_t SizeOfCode; + uint32_t SizeOfInitializedData; + uint32_t SizeOfUninitializedData; + uint32_t AddressOfEntryPoint; + uint32_t BaseOfCode; + uint64_t ImageBase; + uint32_t SectionAlignment; + uint32_t FileAlignment; + uint16_t MajorOperatingSystemVersion; + uint16_t MinorOperatingSystemVersion; + uint16_t MajorImageVersion; + uint16_t MinorImageVersion; + uint16_t MajorSubsystemVersion; + uint16_t MinorSubsystemVersion; + uint32_t Win32VersionValue; + uint32_t SizeOfImage; + uint32_t SizeOfHeaders; + uint32_t CheckSum; + uint16_t Subsystem; + uint16_t DllCharacteristics; + uint64_t SizeOfStackReserve; + uint64_t SizeOfStackCommit; + uint64_t SizeOfHeapReserve; + uint64_t SizeOfHeapCommit; + uint32_t LoaderFlags; + uint32_t NumberOfRvaAndSizes; + image_data_directory DataDirectory[image_numberof_directory_entries]; +}; + +struct image_file_header +{ + uint16_t Machine; + uint16_t NumberOfSections; + uint32_t TimeDateStamp; + uint32_t PointerToSymbolTable; + uint32_t NumberOfSymbols; + uint16_t SizeOfOptionalHeader; + uint16_t Characteristics; +}; + +struct image_nt_headers64 +{ + uint32_t Signature; + image_file_header FileHeader; + image_optional_header64 OptionalHeader; +}; + +struct image_nt_headers32 +{ + uint32_t Signature; + image_file_header FileHeader; + image_optional_header32 OptionalHeader; +}; + +//Section header format +struct image_section_header +{ + uint8_t Name[8]; + union + { + uint32_t PhysicalAddress; + uint32_t VirtualSize; + } Misc; + + uint32_t VirtualAddress; + uint32_t SizeOfRawData; + uint32_t PointerToRawData; + uint32_t PointerToRelocations; + uint32_t PointerToLinenumbers; + uint16_t NumberOfRelocations; + uint16_t NumberOfLinenumbers; + uint32_t Characteristics; +}; + + +/// RESOURCES /// +struct image_resource_directory +{ + uint32_t Characteristics; + uint32_t TimeDateStamp; + uint16_t MajorVersion; + uint16_t MinorVersion; + uint16_t NumberOfNamedEntries; + uint16_t NumberOfIdEntries; + // IMAGE_RESOURCE_DIRECTORY_ENTRY DirectoryEntries[]; +}; + +struct vs_fixedfileinfo +{ + uint32_t dwSignature; /* e.g. 0xfeef04bd */ + uint32_t dwStrucVersion; /* e.g. 0x00000042 = "0.42" */ + uint32_t dwFileVersionMS; /* e.g. 0x00030075 = "3.75" */ + uint32_t dwFileVersionLS; /* e.g. 0x00000031 = "0.31" */ + uint32_t dwProductVersionMS; /* e.g. 0x00030010 = "3.10" */ + uint32_t dwProductVersionLS; /* e.g. 0x00000031 = "0.31" */ + uint32_t dwFileFlagsMask; /* = 0x3F for version "0.42" */ + uint32_t dwFileFlags; /* e.g. VFF_DEBUG | VFF_PRERELEASE */ + uint32_t dwFileOS; /* e.g. VOS_DOS_WINDOWS16 */ + uint32_t dwFileType; /* e.g. VFT_DRIVER */ + uint32_t dwFileSubtype; /* e.g. VFT2_DRV_KEYBOARD */ + uint32_t dwFileDateMS; /* e.g. 0 */ + uint32_t dwFileDateLS; /* e.g. 0 */ +}; + +struct bitmapinfoheader +{ + uint32_t biSize; + int32_t biWidth; + int32_t biHeight; + uint16_t biPlanes; + uint16_t biBitCount; + uint32_t biCompression; + uint32_t biSizeImage; + int32_t biXPelsPerMeter; + int32_t biYPelsPerMeter; + uint32_t biClrUsed; + uint32_t biClrImportant; +}; + +struct message_resource_entry +{ + uint16_t Length; + uint16_t Flags; + uint8_t Text[1]; +}; + +struct message_resource_block +{ + uint32_t LowId; + uint32_t HighId; + uint32_t OffsetToEntries; +}; + +struct message_resource_data +{ + uint32_t NumberOfBlocks; + message_resource_block Blocks[1]; +}; + +struct image_resource_directory_entry +{ + union + { + struct + { + uint32_t NameOffset:31; + uint32_t NameIsString:1; + }; + uint32_t Name; + uint16_t Id; + }; + + union + { + uint32_t OffsetToData; + struct + { + uint32_t OffsetToDirectory:31; + uint32_t DataIsDirectory:1; + }; + }; +}; + +struct image_resource_data_entry +{ + uint32_t OffsetToData; + uint32_t Size; + uint32_t CodePage; + uint32_t Reserved; +}; + +#pragma pack(push, 2) +struct bitmapfileheader +{ + uint16_t bfType; + uint32_t bfSize; + uint16_t bfReserved1; + uint16_t bfReserved2; + uint32_t bfOffBits; +}; +#pragma pack(pop) + + + +//Structure representing ICON file header +struct ico_header +{ + uint16_t Reserved; + uint16_t Type; //1 + uint16_t Count; //Count of icons included in icon group +}; + +//Structure that is stored in icon group directory in PE resources +struct icon_group +{ + uint8_t Width; + uint8_t Height; + uint8_t ColorCount; + uint8_t Reserved; + uint16_t Planes; + uint16_t BitCount; + uint32_t SizeInBytes; + uint16_t Number; //Represents resource ID in PE icon list +}; + +//Structure representing ICON directory entry inside ICON file +struct icondirentry +{ + uint8_t Width; + uint8_t Height; + uint8_t ColorCount; + uint8_t Reserved; + uint16_t Planes; + uint16_t BitCount; + uint32_t SizeInBytes; + uint32_t ImageOffset; //Offset from start of header to the image +}; + +//Structure representing CURSOR file header +struct cursor_header +{ + uint16_t Reserved; + uint16_t Type; //2 + uint16_t Count; //Count of cursors included in cursor group +}; + +struct cursor_group +{ + uint16_t Width; + uint16_t Height; //Divide by 2 to get the actual height. + uint16_t Planes; + uint16_t BitCount; + uint32_t SizeInBytes; + uint16_t Number; //Represents resource ID in PE icon list +}; + +//Structure representing CURSOR directory entry inside CURSOR file +struct cursordirentry +{ + uint8_t Width; //Set to CURSOR_GROUP::Height/2. + uint8_t Height; + uint8_t ColorCount; + uint8_t Reserved; + uint16_t HotspotX; + uint16_t HotspotY; + uint32_t SizeInBytes; + uint32_t ImageOffset; //Offset from start of header to the image +}; + +//Structure representing BLOCK in version info resource +struct version_info_block //(always aligned on 32-bit (DWORD) boundary) +{ + uint16_t Length; //Length of this block (doesn't include padding) + uint16_t ValueLength; //Value length (if any) + uint16_t Type; //Value type (0 = binary, 1 = text) + uint16_t Key[1]; //Value name (block key) (always NULL terminated) + + ////////// + //WORD padding1[]; //Padding, if any (ALIGNMENT) + //xxxxx Value[]; //Value data, if any (*ALIGNED*) + //WORD padding2[]; //Padding, if any (ALIGNMENT) + //xxxxx Child[]; //Child block(s), if any (*ALIGNED*) + ////////// +}; + + +/// IMPORTS /// +#pragma pack(push, 8) +struct image_thunk_data64 +{ + union + { + uint64_t ForwarderString; // PBYTE + uint64_t Function; // PDWORD + uint64_t Ordinal; + uint64_t AddressOfData; // PIMAGE_IMPORT_BY_NAME + } u1; +}; +#pragma pack(pop) + +struct image_thunk_data32 +{ + union + { + uint32_t ForwarderString; // PBYTE + uint32_t Function; // PDWORD + uint32_t Ordinal; + uint32_t AddressOfData; // PIMAGE_IMPORT_BY_NAME + } u1; +}; + +struct image_import_descriptor +{ + union + { + uint32_t Characteristics; // 0 for terminating null import descriptor + uint32_t OriginalFirstThunk; // RVA to original unbound IAT (PIMAGE_THUNK_DATA) + }; + + uint32_t TimeDateStamp; // 0 if not bound, + // -1 if bound, and real date\time stamp + // in IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT (new BIND) + // O.W. date/time stamp of DLL bound to (Old BIND) + + uint32_t ForwarderChain; // -1 if no forwarders + uint32_t Name; + uint32_t FirstThunk; // RVA to IAT (if bound this IAT has actual addresses) +}; + + +/// TLS /// +struct image_tls_directory64 +{ + uint64_t StartAddressOfRawData; + uint64_t EndAddressOfRawData; + uint64_t AddressOfIndex; // PDWORD + uint64_t AddressOfCallBacks; // PIMAGE_TLS_CALLBACK *; + uint32_t SizeOfZeroFill; + uint32_t Characteristics; +}; + +struct image_tls_directory32 +{ + uint32_t StartAddressOfRawData; + uint32_t EndAddressOfRawData; + uint32_t AddressOfIndex; // PDWORD + uint32_t AddressOfCallBacks; // PIMAGE_TLS_CALLBACK * + uint32_t SizeOfZeroFill; + uint32_t Characteristics; +}; + + +/// Export Format /// +struct image_export_directory +{ + uint32_t Characteristics; + uint32_t TimeDateStamp; + uint16_t MajorVersion; + uint16_t MinorVersion; + uint32_t Name; + uint32_t Base; + uint32_t NumberOfFunctions; + uint32_t NumberOfNames; + uint32_t AddressOfFunctions; // RVA from base of image + uint32_t AddressOfNames; // RVA from base of image + uint32_t AddressOfNameOrdinals; // RVA from base of image +}; + + +/// Based relocation format /// +struct image_base_relocation +{ + uint32_t VirtualAddress; + uint32_t SizeOfBlock; + // uint16_t TypeOffset[1]; +}; + + +/// New format import descriptors pointed to by DataDirectory[ IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT ] /// +struct image_bound_import_descriptor +{ + uint32_t TimeDateStamp; + uint16_t OffsetModuleName; + uint16_t NumberOfModuleForwarderRefs; + // Array of zero or more IMAGE_BOUND_FORWARDER_REF follows +}; + +struct image_bound_forwarder_ref +{ + uint32_t TimeDateStamp; + uint16_t OffsetModuleName; + uint16_t Reserved; +}; + + +/// Exception directory /// +struct image_runtime_function_entry +{ + uint32_t BeginAddress; + uint32_t EndAddress; + uint32_t UnwindInfoAddress; +}; + +enum unwind_op_codes +{ + uwop_push_nonvol = 0, /* info == register number */ + uwop_alloc_large, /* no info, alloc size in next 2 slots */ + uwop_alloc_small, /* info == size of allocation / 8 - 1 */ + uwop_set_fpreg, /* no info, FP = RSP + UNWIND_INFO.FPRegOffset*16 */ + uwop_save_nonvol, /* info == register number, offset in next slot */ + uwop_save_nonvol_far, /* info == register number, offset in next 2 slots */ + uwop_save_xmm128, /* info == XMM reg number, offset in next slot */ + uwop_save_xmm128_far, /* info == XMM reg number, offset in next 2 slots */ + uwop_push_machframe /* info == 0: no error-code, 1: error-code */ +}; + +union unwind_code +{ + struct s + { + uint8_t CodeOffset; + uint8_t UnwindOp : 4; + uint8_t OpInfo : 4; + }; + + uint16_t FrameOffset; +}; + +struct unwind_info +{ + uint8_t Version : 3; + uint8_t Flags : 5; + uint8_t SizeOfProlog; + uint8_t CountOfCodes; + uint8_t FrameRegister : 4; + uint8_t FrameOffset : 4; + unwind_code UnwindCode[1]; + /* unwind_code MoreUnwindCode[((CountOfCodes + 1) & ~1) - 1]; + * union { + * OPTIONAL ULONG ExceptionHandler; + * OPTIONAL ULONG FunctionEntry; + * }; + * OPTIONAL ULONG ExceptionData[]; */ +}; + + + +/// Debug /// +struct image_debug_misc +{ + uint32_t DataType; // type of misc data, see defines + uint32_t Length; // total length of record, rounded to four + // byte multiple. + uint8_t Unicode; // TRUE if data is unicode string + uint8_t Reserved[3]; + uint8_t Data[1]; // Actual data +}; + +struct image_coff_symbols_header +{ + uint32_t NumberOfSymbols; + uint32_t LvaToFirstSymbol; + uint32_t NumberOfLinenumbers; + uint32_t LvaToFirstLinenumber; + uint32_t RvaToFirstByteOfCode; + uint32_t RvaToLastByteOfCode; + uint32_t RvaToFirstByteOfData; + uint32_t RvaToLastByteOfData; +}; + +struct image_debug_directory +{ + uint32_t Characteristics; + uint32_t TimeDateStamp; + uint16_t MajorVersion; + uint16_t MinorVersion; + uint32_t Type; + uint32_t SizeOfData; + uint32_t AddressOfRawData; + uint32_t PointerToRawData; +}; + + +#pragma pack(push, 2) +struct image_symbol +{ + union + { + uint8_t ShortName[8]; + struct + { + uint32_t Short; // if 0, use LongName + uint32_t Long; // offset into string table + } Name; + uint32_t LongName[2]; // PBYTE [2] + } N; + uint32_t Value; + int16_t SectionNumber; + uint16_t Type; + uint8_t StorageClass; + uint8_t NumberOfAuxSymbols; +}; +#pragma pack(pop) + +//CodeView Debug OMF signature. The signature at the end of the file is +//a negative offset from the end of the file to another signature. At +//the negative offset (base address) is another signature whose filepos +//field points to the first OMFDirHeader in a chain of directories. +//The NB05 signature is used by the link utility to indicated a completely +//unpacked file. The NB06 signature is used by ilink to indicate that the +//executable has had CodeView information from an incremental link appended +//to the executable. The NB08 signature is used by cvpack to indicate that +//the CodeView Debug OMF has been packed. CodeView will only process +//executables with the NB08 signature. +struct OMFSignature +{ + char Signature[4]; // "NBxx" + uint32_t filepos; // offset in file +}; + +struct CV_INFO_PDB20 +{ + OMFSignature CvHeader; + uint32_t Signature; + uint32_t Age; + uint8_t PdbFileName[1]; +}; + +struct CV_INFO_PDB70 +{ + uint32_t CvSignature; + guid Signature; + uint32_t Age; + uint8_t PdbFileName[1]; +}; + +// directory information structure +// This structure contains the information describing the directory. +// It is pointed to by the signature at the base address or the directory +// link field of a preceeding directory. The directory entries immediately +// follow this structure. +struct OMFDirHeader +{ + uint16_t cbDirHeader; // length of this structure + uint16_t cbDirEntry; // number of bytes in each directory entry + uint32_t cDir; // number of directorie entries + int32_t lfoNextDir; // offset from base of next directory + uint32_t flags; // status flags +}; + +// directory structure +// The data in this structure is used to reference the data for each +// subsection of the CodeView Debug OMF information. Tables that are +// not associated with a specific module will have a module index of +// oxffff. These tables are the global types table, the global symbol +// table, the global public table and the library table. +struct OMFDirEntry +{ + uint16_t SubSection; // subsection type (sst...) + uint16_t iMod; // module index + int32_t lfo; // large file offset of subsection + uint32_t cb; // number of bytes in subsection +}; + + +/// CLR 2.0 header structure /// +struct image_cor20_header +{ + //Header versioning + uint32_t cb; + uint16_t MajorRuntimeVersion; + uint16_t MinorRuntimeVersion; + + // Symbol table and startup information + image_data_directory MetaData; + uint32_t Flags; + + // If COMIMAGE_FLAGS_NATIVE_ENTRYPOINT is not set, EntryPointToken represents a managed entrypoint. + // If COMIMAGE_FLAGS_NATIVE_ENTRYPOINT is set, EntryPointRVA represents an RVA to a native entrypoint. + union + { + uint32_t EntryPointToken; + uint32_t EntryPointRVA; + }; + + // Binding information + image_data_directory Resources; + image_data_directory StrongNameSignature; + + // Regular fixup and binding information + image_data_directory CodeManagerTable; + image_data_directory VTableFixups; + image_data_directory ExportAddressTableJumps; + + // Precompiled image info (internal use only - set to zero) + image_data_directory ManagedNativeHeader; +}; + +enum replaces_cor_hdr_numeric_defines +{ + // COM+ Header entry point flags. + comimage_flags_ilonly =0x00000001, + comimage_flags_32bitrequired =0x00000002, + comimage_flags_il_library =0x00000004, + comimage_flags_strongnamesigned =0x00000008, + comimage_flags_native_entrypoint =0x00000010, + comimage_flags_trackdebugdata =0x00010000, + + // Version flags for image. + cor_version_major_v2 =2, + cor_version_major =cor_version_major_v2, + cor_version_minor =0, + cor_deleted_name_length =8, + cor_vtablegap_name_length =8, + + // Maximum size of a NativeType descriptor. + native_type_max_cb =1, + cor_ilmethod_sect_small_max_datasize=0xff, + + // #defines for the MIH FLAGS + image_cor_mih_methodrva =0x01, + image_cor_mih_ehrva =0x02, + image_cor_mih_basicblock =0x08, + + // V-table constants + cor_vtable_32bit =0x01, // V-table slots are 32-bits in size. + cor_vtable_64bit =0x02, // V-table slots are 64-bits in size. + cor_vtable_from_unmanaged =0x04, // If set, transition from unmanaged. + cor_vtable_from_unmanaged_retain_appdomain =0x08, // If set, transition from unmanaged with keeping the current appdomain. + cor_vtable_call_most_derived =0x10, // Call most derived method described by + + // EATJ constants + image_cor_eatj_thunk_size =32, // Size of a jump thunk reserved range. + + // Max name lengths + //@todo: Change to unlimited name lengths. + max_class_name =1024, + max_package_name =1024 +}; + +/// Load Configuration Directory Entry /// +struct image_load_config_directory32 +{ + uint32_t Size; + uint32_t TimeDateStamp; + uint16_t MajorVersion; + uint16_t MinorVersion; + uint32_t GlobalFlagsClear; + uint32_t GlobalFlagsSet; + uint32_t CriticalSectionDefaultTimeout; + uint32_t DeCommitFreeBlockThreshold; + uint32_t DeCommitTotalFreeThreshold; + uint32_t LockPrefixTable; // VA + uint32_t MaximumAllocationSize; + uint32_t VirtualMemoryThreshold; + uint32_t ProcessHeapFlags; + uint32_t ProcessAffinityMask; + uint16_t CSDVersion; + uint16_t Reserved1; + uint32_t EditList; // VA + uint32_t SecurityCookie; // VA + uint32_t SEHandlerTable; // VA + uint32_t SEHandlerCount; +}; + +struct image_load_config_directory64 +{ + uint32_t Size; + uint32_t TimeDateStamp; + uint16_t MajorVersion; + uint16_t MinorVersion; + uint32_t GlobalFlagsClear; + uint32_t GlobalFlagsSet; + uint32_t CriticalSectionDefaultTimeout; + uint64_t DeCommitFreeBlockThreshold; + uint64_t DeCommitTotalFreeThreshold; + uint64_t LockPrefixTable; // VA + uint64_t MaximumAllocationSize; + uint64_t VirtualMemoryThreshold; + uint64_t ProcessAffinityMask; + uint32_t ProcessHeapFlags; + uint16_t CSDVersion; + uint16_t Reserved1; + uint64_t EditList; // VA + uint64_t SecurityCookie; // VA + uint64_t SEHandlerTable; // VA + uint64_t SEHandlerCount; +}; + +#pragma pack(pop) +} //namespace pe_win + +#ifdef PE_BLISS_WINDOWS +typedef wchar_t unicode16_t; +typedef std::basic_string<unicode16_t> u16string; +#else +//Instead of wchar_t for windows +typedef unsigned short unicode16_t; +typedef std::basic_string<unicode16_t> u16string; +#endif + +} //namespace pe_bliss diff --git a/tools/pe_bliss/pe_tls.cpp b/tools/pe_bliss/pe_tls.cpp new file mode 100644 index 0000000000..5ec68e3f10 --- /dev/null +++ b/tools/pe_bliss/pe_tls.cpp @@ -0,0 +1,396 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <string.h> +#include "pe_tls.h" +#include "pe_properties_generic.h" + +namespace pe_bliss +{ +using namespace pe_win; + +//TLS +//Default constructor +tls_info::tls_info() + :start_rva_(0), end_rva_(0), index_rva_(0), callbacks_rva_(0), + size_of_zero_fill_(0), characteristics_(0) +{} + +//Returns start RVA of TLS raw data +uint32_t tls_info::get_raw_data_start_rva() const +{ + return start_rva_; +} + +//Returns end RVA of TLS raw data +uint32_t tls_info::get_raw_data_end_rva() const +{ + return end_rva_; +} + +//Returns TLS index RVA +uint32_t tls_info::get_index_rva() const +{ + return index_rva_; +} + +//Returns TLS callbacks RVA +uint32_t tls_info::get_callbacks_rva() const +{ + return callbacks_rva_; +} + +//Returns size of zero fill +uint32_t tls_info::get_size_of_zero_fill() const +{ + return size_of_zero_fill_; +} + +//Returns characteristics +uint32_t tls_info::get_characteristics() const +{ + return characteristics_; +} + +//Returns raw TLS data +const std::string& tls_info::get_raw_data() const +{ + return raw_data_; +} + +//Returns TLS callbacks addresses +const tls_info::tls_callback_list& tls_info::get_tls_callbacks() const +{ + return callbacks_; +} + +//Returns TLS callbacks addresses +tls_info::tls_callback_list& tls_info::get_tls_callbacks() +{ + return callbacks_; +} + +//Adds TLS callback +void tls_info::add_tls_callback(uint32_t rva) +{ + callbacks_.push_back(rva); +} + +//Clears TLS callbacks list +void tls_info::clear_tls_callbacks() +{ + callbacks_.clear(); +} + +//Recalculates end address of raw TLS data +void tls_info::recalc_raw_data_end_rva() +{ + end_rva_ = static_cast<uint32_t>(start_rva_ + raw_data_.length()); +} + +//Sets start RVA of TLS raw data +void tls_info::set_raw_data_start_rva(uint32_t rva) +{ + start_rva_ = rva; +} + +//Sets end RVA of TLS raw data +void tls_info::set_raw_data_end_rva(uint32_t rva) +{ + end_rva_ = rva; +} + +//Sets TLS index RVA +void tls_info::set_index_rva(uint32_t rva) +{ + index_rva_ = rva; +} + +//Sets TLS callbacks RVA +void tls_info::set_callbacks_rva(uint32_t rva) +{ + callbacks_rva_ = rva; +} + +//Sets size of zero fill +void tls_info::set_size_of_zero_fill(uint32_t size) +{ + size_of_zero_fill_ = size; +} + +//Sets characteristics +void tls_info::set_characteristics(uint32_t characteristics) +{ + characteristics_ = characteristics; +} + +//Sets raw TLS data +void tls_info::set_raw_data(const std::string& data) +{ + raw_data_ = data; +} + +//If image does not have TLS, throws an exception +const tls_info get_tls_info(const pe_base& pe) +{ + return pe.get_pe_type() == pe_type_32 + ? get_tls_info_base<pe_types_class_32>(pe) + : get_tls_info_base<pe_types_class_64>(pe); +} + +//TLS Rebuilder +const image_directory rebuild_tls(pe_base& pe, const tls_info& info, section& tls_section, uint32_t offset_from_section_start, bool write_tls_callbacks, bool write_tls_data, tls_data_expand_type expand, bool save_to_pe_header, bool auto_strip_last_section) +{ + return pe.get_pe_type() == pe_type_32 + ? rebuild_tls_base<pe_types_class_32>(pe, info, tls_section, offset_from_section_start, write_tls_callbacks, write_tls_data, expand, save_to_pe_header, auto_strip_last_section) + : rebuild_tls_base<pe_types_class_64>(pe, info, tls_section, offset_from_section_start, write_tls_callbacks, write_tls_data, expand, save_to_pe_header, auto_strip_last_section); +} + +//Get TLS info +//If image does not have TLS, throws an exception +template<typename PEClassType> +const tls_info get_tls_info_base(const pe_base& pe) +{ + tls_info ret; + + //If there's no TLS directory, throw an exception + if(!pe.has_tls()) + throw pe_exception("Image does not have TLS directory", pe_exception::directory_does_not_exist); + + //Get TLS directory data + typename PEClassType::TLSStruct tls_directory_data = pe.section_data_from_rva<typename PEClassType::TLSStruct>(pe.get_directory_rva(image_directory_entry_tls), section_data_virtual, true); + + //Check data addresses + if(tls_directory_data.EndAddressOfRawData == tls_directory_data.StartAddressOfRawData) + { + try + { + pe.va_to_rva(static_cast<typename PEClassType::BaseSize>(tls_directory_data.EndAddressOfRawData)); + } + catch(const pe_exception&) + { + //Fix addressess on incorrect conversion + tls_directory_data.EndAddressOfRawData = tls_directory_data.StartAddressOfRawData = 0; + } + } + + if(tls_directory_data.StartAddressOfRawData && + pe.section_data_length_from_va(static_cast<typename PEClassType::BaseSize>(tls_directory_data.StartAddressOfRawData), + static_cast<typename PEClassType::BaseSize>(tls_directory_data.StartAddressOfRawData), section_data_virtual, true) + < (tls_directory_data.EndAddressOfRawData - tls_directory_data.StartAddressOfRawData)) + throw pe_exception("Incorrect TLS directory", pe_exception::incorrect_tls_directory); + + //Fill TLS info + //VAs are not checked + ret.set_raw_data_start_rva(tls_directory_data.StartAddressOfRawData ? pe.va_to_rva(static_cast<typename PEClassType::BaseSize>(tls_directory_data.StartAddressOfRawData)) : 0); + ret.set_raw_data_end_rva(tls_directory_data.EndAddressOfRawData ? pe.va_to_rva(static_cast<typename PEClassType::BaseSize>(tls_directory_data.EndAddressOfRawData)) : 0); + ret.set_index_rva(tls_directory_data.AddressOfIndex ? pe.va_to_rva(static_cast<typename PEClassType::BaseSize>(tls_directory_data.AddressOfIndex)) : 0); + ret.set_callbacks_rva(tls_directory_data.AddressOfCallBacks ? pe.va_to_rva(static_cast<typename PEClassType::BaseSize>(tls_directory_data.AddressOfCallBacks)) : 0); + ret.set_size_of_zero_fill(tls_directory_data.SizeOfZeroFill); + ret.set_characteristics(tls_directory_data.Characteristics); + + if(tls_directory_data.StartAddressOfRawData && tls_directory_data.StartAddressOfRawData != tls_directory_data.EndAddressOfRawData) + { + //Read and save TLS RAW data + ret.set_raw_data(std::string( + pe.section_data_from_va(static_cast<typename PEClassType::BaseSize>(tls_directory_data.StartAddressOfRawData), section_data_virtual, true), + static_cast<uint32_t>(tls_directory_data.EndAddressOfRawData - tls_directory_data.StartAddressOfRawData))); + } + + //If file has TLS callbacks + if(ret.get_callbacks_rva()) + { + //Read callbacks VAs + uint32_t current_tls_callback = 0; + + while(true) + { + //Read TLS callback VA + typename PEClassType::BaseSize va = pe.section_data_from_va<typename PEClassType::BaseSize>(static_cast<typename PEClassType::BaseSize>(tls_directory_data.AddressOfCallBacks + current_tls_callback), section_data_virtual, true); + if(va == 0) + break; + + //Save it + ret.add_tls_callback(pe.va_to_rva(va, false)); + + //Move to next callback VA + current_tls_callback += sizeof(va); + } + } + + return ret; +} + +//Rebuilder of TLS structures +//If write_tls_callbacks = true, TLS callbacks VAs will be written to their place +//If write_tls_data = true, TLS data will be written to its place +//If you have chosen to rewrite raw data, only (EndAddressOfRawData - StartAddressOfRawData) bytes will be written, not the full length of string +//representing raw data content +//auto_strip_last_section - if true and TLS are placed in the last section, it will be automatically stripped +//Note/TODO: TLS Callbacks array is not DWORD-aligned (seems to work on WinXP - Win7) +template<typename PEClassType> +const image_directory rebuild_tls_base(pe_base& pe, const tls_info& info, section& tls_section, uint32_t offset_from_section_start, bool write_tls_callbacks, bool write_tls_data, tls_data_expand_type expand, bool save_to_pe_header, bool auto_strip_last_section) +{ + //Check that tls_section is attached to this PE image + if(!pe.section_attached(tls_section)) + throw pe_exception("TLS section must be attached to PE file", pe_exception::section_is_not_attached); + + uint32_t tls_data_pos = pe_utils::align_up(offset_from_section_start, sizeof(typename PEClassType::BaseSize)); + uint32_t needed_size = sizeof(typename PEClassType::TLSStruct); //Calculate needed size for TLS table + + //Check if tls_section is last one. If it's not, check if there's enough place for TLS data + if(&tls_section != &*(pe.get_image_sections().end() - 1) && + (tls_section.empty() || pe_utils::align_up(tls_section.get_size_of_raw_data(), pe.get_file_alignment()) < needed_size + tls_data_pos)) + throw pe_exception("Insufficient space for TLS directory", pe_exception::insufficient_space); + + //Check raw data positions + if(info.get_raw_data_end_rva() < info.get_raw_data_start_rva() || info.get_index_rva() == 0) + throw pe_exception("Incorrect TLS directory", pe_exception::incorrect_tls_directory); + + std::string& raw_data = tls_section.get_raw_data(); + + //This will be done only if tls_section is the last section of image or for section with unaligned raw length of data + if(raw_data.length() < needed_size + tls_data_pos) + raw_data.resize(needed_size + tls_data_pos); //Expand section raw data + + //Create and fill TLS structure + typename PEClassType::TLSStruct tls_struct = {0}; + + typename PEClassType::BaseSize va; + if(info.get_raw_data_start_rva()) + { + pe.rva_to_va(info.get_raw_data_start_rva(), va); + tls_struct.StartAddressOfRawData = va; + tls_struct.SizeOfZeroFill = info.get_size_of_zero_fill(); + } + + if(info.get_raw_data_end_rva()) + { + pe.rva_to_va(info.get_raw_data_end_rva(), va); + tls_struct.EndAddressOfRawData = va; + } + + pe.rva_to_va(info.get_index_rva(), va); + tls_struct.AddressOfIndex = va; + + if(info.get_callbacks_rva()) + { + pe.rva_to_va(info.get_callbacks_rva(), va); + tls_struct.AddressOfCallBacks = va; + } + + tls_struct.Characteristics = info.get_characteristics(); + + //Save TLS structure + memcpy(&raw_data[tls_data_pos], &tls_struct, sizeof(tls_struct)); + + //If we are asked to rewrite TLS raw data + if(write_tls_data && info.get_raw_data_start_rva() && info.get_raw_data_start_rva() != info.get_raw_data_end_rva()) + { + try + { + //Check if we're going to write TLS raw data to an existing section (not to PE headers) + section& raw_data_section = pe.section_from_rva(info.get_raw_data_start_rva()); + pe.expand_section(raw_data_section, info.get_raw_data_start_rva(), info.get_raw_data_end_rva() - info.get_raw_data_start_rva(), expand == tls_data_expand_raw ? pe_base::expand_section_raw : pe_base::expand_section_virtual); + } + catch(const pe_exception&) + { + //If no section is presented by StartAddressOfRawData, just go to next step + } + + unsigned long write_raw_data_size = info.get_raw_data_end_rva() - info.get_raw_data_start_rva(); + unsigned long available_raw_length = 0; + + //Check if there's enough RAW space to write raw TLS data... + if((available_raw_length = pe.section_data_length_from_rva(info.get_raw_data_start_rva(), info.get_raw_data_start_rva(), section_data_raw, true)) + < info.get_raw_data_end_rva() - info.get_raw_data_start_rva()) + { + //Check if there's enough virtual space for it... + if(pe.section_data_length_from_rva(info.get_raw_data_start_rva(), info.get_raw_data_start_rva(), section_data_virtual, true) + < info.get_raw_data_end_rva() - info.get_raw_data_start_rva()) + throw pe_exception("Insufficient space for TLS raw data", pe_exception::insufficient_space); + else + write_raw_data_size = available_raw_length; //We'll write just a part of full raw data + } + + //Write raw TLS data, if any + if(write_raw_data_size != 0) + memcpy(pe.section_data_from_rva(info.get_raw_data_start_rva(), true), info.get_raw_data().data(), write_raw_data_size); + } + + //If we are asked to rewrite TLS callbacks addresses + if(write_tls_callbacks && info.get_callbacks_rva()) + { + unsigned long needed_callback_size = static_cast<unsigned long>((info.get_tls_callbacks().size() + 1 /* last null element */) * sizeof(typename PEClassType::BaseSize)); + + try + { + //Check if we're going to write TLS callbacks VAs to an existing section (not to PE headers) + section& raw_data_section = pe.section_from_rva(info.get_callbacks_rva()); + pe.expand_section(raw_data_section, info.get_callbacks_rva(), needed_callback_size, pe_base::expand_section_raw); + } + catch(const pe_exception&) + { + //If no section is presented by RVA of callbacks, just go to next step + } + + //Check if there's enough space to write callbacks TLS data... + if(pe.section_data_length_from_rva(info.get_callbacks_rva(), info.get_callbacks_rva(), section_data_raw, true) + < needed_callback_size - sizeof(typename PEClassType::BaseSize) /* last zero element can be virtual only */) + throw pe_exception("Insufficient space for TLS callbacks data", pe_exception::insufficient_space); + + if(pe.section_data_length_from_rva(info.get_callbacks_rva(), info.get_callbacks_rva(), section_data_virtual, true) + < needed_callback_size /* check here full virtual data length available */) + throw pe_exception("Insufficient space for TLS callbacks data", pe_exception::insufficient_space); + + std::vector<typename PEClassType::BaseSize> callbacks_virtual_addresses; + callbacks_virtual_addresses.reserve(info.get_tls_callbacks().size() + 1 /* last null element */); + + //Convert TLS RVAs to VAs + for(tls_info::tls_callback_list::const_iterator it = info.get_tls_callbacks().begin(); it != info.get_tls_callbacks().end(); ++it) + { + typename PEClassType::BaseSize cb_va = 0; + pe.rva_to_va(*it, cb_va); + callbacks_virtual_addresses.push_back(cb_va); + } + + //Ending null element + callbacks_virtual_addresses.push_back(0); + + //Write callbacks TLS data + memcpy(pe.section_data_from_rva(info.get_callbacks_rva(), true), &callbacks_virtual_addresses[0], needed_callback_size); + } + + //Adjust section raw and virtual sizes + pe.recalculate_section_sizes(tls_section, auto_strip_last_section); + + image_directory ret(pe.rva_from_section_offset(tls_section, tls_data_pos), needed_size); + + //If auto-rewrite of PE headers is required + if(save_to_pe_header) + { + pe.set_directory_rva(image_directory_entry_tls, ret.get_rva()); + pe.set_directory_size(image_directory_entry_tls, ret.get_size()); + } + + return ret; +} +} diff --git a/tools/pe_bliss/pe_tls.h b/tools/pe_bliss/pe_tls.h new file mode 100644 index 0000000000..316e208147 --- /dev/null +++ b/tools/pe_bliss/pe_tls.h @@ -0,0 +1,122 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <memory> +#include <istream> +#include "pe_base.h" +#include "pe_directory.h" + +namespace pe_bliss +{ +//Class representing TLS info +//We use "DWORD" type to represent RVAs, because RVA is +//always 32bit even in PE+ +class tls_info +{ +public: + typedef std::vector<uint32_t> tls_callback_list; + +public: + //Default constructor + tls_info(); + + //Returns start RVA of TLS raw data + uint32_t get_raw_data_start_rva() const; + //Returns end RVA of TLS raw data + uint32_t get_raw_data_end_rva() const; + //Returns TLS index RVA + uint32_t get_index_rva() const; + //Returns TLS callbacks RVA + uint32_t get_callbacks_rva() const; + //Returns size of zero fill + uint32_t get_size_of_zero_fill() const; + //Returns characteristics + uint32_t get_characteristics() const; + //Returns raw TLS data + const std::string& get_raw_data() const; + //Returns TLS callbacks addresses + const tls_callback_list& get_tls_callbacks() const; + +public: //These functions do not change everything inside image, they are used by PE class + //You can also use them to rebuild TLS directory + + //Sets start RVA of TLS raw data + void set_raw_data_start_rva(uint32_t rva); + //Sets end RVA of TLS raw data + void set_raw_data_end_rva(uint32_t rva); + //Sets TLS index RVA + void set_index_rva(uint32_t rva); + //Sets TLS callbacks RVA + void set_callbacks_rva(uint32_t rva); + //Sets size of zero fill + void set_size_of_zero_fill(uint32_t size); + //Sets characteristics + void set_characteristics(uint32_t characteristics); + //Sets raw TLS data + void set_raw_data(const std::string& data); + //Returns TLS callbacks addresses + tls_callback_list& get_tls_callbacks(); + //Adds TLS callback + void add_tls_callback(uint32_t rva); + //Clears TLS callbacks list + void clear_tls_callbacks(); + //Recalculates end address of raw TLS data + void recalc_raw_data_end_rva(); + +private: + uint32_t start_rva_, end_rva_, index_rva_, callbacks_rva_; + uint32_t size_of_zero_fill_, characteristics_; + + //Raw TLS data + std::string raw_data_; + + //TLS callback RVAs + tls_callback_list callbacks_; +}; + +//Represents type of expanding of TLS section containing raw data +//(Works only if you are writing TLS raw data to tls_section and it is the last one in the PE image on the moment of TLS rebuild) +enum tls_data_expand_type +{ + tls_data_expand_raw, //If there is not enough raw space for raw TLS data, it can be expanded + tls_data_expand_virtual //If there is not enough virtual place for raw TLS data, it can be expanded +}; + + +//Get TLS info +//If image does not have TLS, throws an exception +const tls_info get_tls_info(const pe_base& pe); + +template<typename PEClassType> +const tls_info get_tls_info_base(const pe_base& pe); + +//Rebuilder of TLS structures +//If write_tls_callbacks = true, TLS callbacks VAs will be written to their place +//If write_tls_data = true, TLS data will be written to its place +//If you have chosen to rewrite raw data, only (EndAddressOfRawData - StartAddressOfRawData) bytes will be written, not the full length of string +//representing raw data content +//auto_strip_last_section - if true and TLS are placed in the last section, it will be automatically stripped +const image_directory rebuild_tls(pe_base& pe, const tls_info& info, section& tls_section, uint32_t offset_from_section_start = 0, bool write_tls_callbacks = true, bool write_tls_data = true, tls_data_expand_type expand = tls_data_expand_raw, bool save_to_pe_header = true, bool auto_strip_last_section = true); + +template<typename PEClassType> +const image_directory rebuild_tls_base(pe_base& pe, const tls_info& info, section& tls_section, uint32_t offset_from_section_start = 0, bool write_tls_callbacks = true, bool write_tls_data = true, tls_data_expand_type expand = tls_data_expand_raw, bool save_to_pe_header = true, bool auto_strip_last_section = true); +} diff --git a/tools/pe_bliss/resource_bitmap_reader.cpp b/tools/pe_bliss/resource_bitmap_reader.cpp new file mode 100644 index 0000000000..3546461f53 --- /dev/null +++ b/tools/pe_bliss/resource_bitmap_reader.cpp @@ -0,0 +1,86 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <cmath> +#include "resource_bitmap_reader.h" +#include "pe_resource_viewer.h" +#include "pe_structures.h" + +namespace pe_bliss +{ +using namespace pe_win; + +resource_bitmap_reader::resource_bitmap_reader(const pe_resource_viewer& res) + :res_(res) +{} + +//Returns bitmap data by name and index in language directory (instead of language) (minimum checks of format correctness) +const std::string resource_bitmap_reader::get_bitmap_by_name(const std::wstring& name, uint32_t index) const +{ + return create_bitmap(res_.get_resource_data_by_name(pe_resource_viewer::resource_bitmap, name, index).get_data()); +} + +//Returns bitmap data by name and language (minimum checks of format correctness) +const std::string resource_bitmap_reader::get_bitmap_by_name(uint32_t language, const std::wstring& name) const +{ + return create_bitmap(res_.get_resource_data_by_name(language, pe_resource_viewer::resource_bitmap, name).get_data()); +} + +//Returns bitmap data by ID and language (minimum checks of format correctness) +const std::string resource_bitmap_reader::get_bitmap_by_id_lang(uint32_t language, uint32_t id) const +{ + return create_bitmap(res_.get_resource_data_by_id(language, pe_resource_viewer::resource_bitmap, id).get_data()); +} + +//Returns bitmap data by ID and index in language directory (instead of language) (minimum checks of format correctness) +const std::string resource_bitmap_reader::get_bitmap_by_id(uint32_t id, uint32_t index) const +{ + return create_bitmap(res_.get_resource_data_by_id(pe_resource_viewer::resource_bitmap, id, index).get_data()); +} + +//Helper function of creating bitmap header +const std::string resource_bitmap_reader::create_bitmap(const std::string& resource_data) +{ + //Create bitmap file header + bitmapfileheader header = {0}; + header.bfType = 0x4d42; //Signature "BM" + header.bfOffBits = sizeof(bitmapfileheader) + sizeof(bitmapinfoheader); //Offset to bitmap bits + header.bfSize = static_cast<uint32_t>(sizeof(bitmapfileheader) + resource_data.length()); //Size of bitmap + + //Check size of resource data + if(resource_data.length() < sizeof(bitmapinfoheader)) + throw pe_exception("Incorrect resource bitmap", pe_exception::resource_incorrect_bitmap); + + { + //Get bitmap info header + const bitmapinfoheader* info = reinterpret_cast<const bitmapinfoheader*>(resource_data.data()); + + //If color table is present, skip it + if(info->biClrUsed != 0) + header.bfOffBits += 4 * info->biClrUsed; //Add this size to offset to bitmap bits + else if(info->biBitCount <= 8) + header.bfOffBits += 4 * static_cast<uint32_t>(std::pow(2.f, info->biBitCount)); //Add this size to offset to bitmap bits + } + + //Return final bitmap data + return std::string(reinterpret_cast<const char*>(&header), sizeof(bitmapfileheader)) + resource_data; +} +} diff --git a/tools/pe_bliss/resource_bitmap_reader.h b/tools/pe_bliss/resource_bitmap_reader.h new file mode 100644 index 0000000000..f2b92bbde7 --- /dev/null +++ b/tools/pe_bliss/resource_bitmap_reader.h @@ -0,0 +1,50 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <string> +#include "stdint_defs.h" + +namespace pe_bliss +{ +class pe_resource_viewer; + +class resource_bitmap_reader +{ +public: + resource_bitmap_reader(const pe_resource_viewer& res); + + //Returns bitmap data by name and language (minimum checks of format correctness) + const std::string get_bitmap_by_name(uint32_t language, const std::wstring& name) const; + //Returns bitmap data by name and index in language directory (instead of language) (minimum checks of format correctness) + const std::string get_bitmap_by_name(const std::wstring& name, uint32_t index = 0) const; + //Returns bitmap data by ID and language (minimum checks of format correctness) + const std::string get_bitmap_by_id_lang(uint32_t language, uint32_t id) const; + //Returns bitmap data by ID and index in language directory (instead of language) (minimum checks of format correctness) + const std::string get_bitmap_by_id(uint32_t id, uint32_t index = 0) const; + +private: + //Helper function of creating bitmap header + static const std::string create_bitmap(const std::string& resource_data); + + const pe_resource_viewer& res_; +}; +} diff --git a/tools/pe_bliss/resource_bitmap_writer.cpp b/tools/pe_bliss/resource_bitmap_writer.cpp new file mode 100644 index 0000000000..3445a08445 --- /dev/null +++ b/tools/pe_bliss/resource_bitmap_writer.cpp @@ -0,0 +1,75 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include "resource_bitmap_writer.h" +#include "pe_resource_manager.h" +#include "pe_structures.h" + +namespace pe_bliss +{ +using namespace pe_win; + +resource_bitmap_writer::resource_bitmap_writer(pe_resource_manager& res) + :res_(res) +{} + +//Adds bitmap from bitmap file data. If bitmap already exists, replaces it +//timestamp will be used for directories that will be added +void resource_bitmap_writer::add_bitmap(const std::string& bitmap_file, uint32_t id, uint32_t language, uint32_t codepage, uint32_t timestamp) +{ + //Check bitmap data a little + if(bitmap_file.length() < sizeof(bitmapfileheader)) + throw pe_exception("Incorrect resource bitmap", pe_exception::resource_incorrect_bitmap); + + resource_directory_entry new_entry; + new_entry.set_id(id); + + //Add bitmap + res_.add_resource(bitmap_file.substr(sizeof(bitmapfileheader)), pe_resource_viewer::resource_bitmap, new_entry, resource_directory::entry_finder(id), language, codepage, timestamp); +} + +//Adds bitmap from bitmap file data. If bitmap already exists, replaces it +//timestamp will be used for directories that will be added +void resource_bitmap_writer::add_bitmap(const std::string& bitmap_file, const std::wstring& name, uint32_t language, uint32_t codepage, uint32_t timestamp) +{ + //Check bitmap data a little + if(bitmap_file.length() < sizeof(bitmapfileheader)) + throw pe_exception("Incorrect resource bitmap", pe_exception::resource_incorrect_bitmap); + + resource_directory_entry new_entry; + new_entry.set_name(name); + + //Add bitmap + res_.add_resource(bitmap_file.substr(sizeof(bitmapfileheader)), pe_resource_viewer::resource_bitmap, new_entry, resource_directory::entry_finder(name), language, codepage, timestamp); +} + +//Removes bitmap by name/ID and language +bool resource_bitmap_writer::remove_bitmap(const std::wstring& name, uint32_t language) +{ + return res_.remove_resource(pe_resource_viewer::resource_bitmap, name, language); +} + +//Removes bitmap by name/ID and language +bool resource_bitmap_writer::remove_bitmap(uint32_t id, uint32_t language) +{ + return res_.remove_resource(pe_resource_viewer::resource_bitmap, id, language); +} +} diff --git a/tools/pe_bliss/resource_bitmap_writer.h b/tools/pe_bliss/resource_bitmap_writer.h new file mode 100644 index 0000000000..4b8ea72705 --- /dev/null +++ b/tools/pe_bliss/resource_bitmap_writer.h @@ -0,0 +1,47 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <string> +#include "stdint_defs.h" + +namespace pe_bliss +{ +class pe_resource_manager; + +class resource_bitmap_writer +{ +public: + resource_bitmap_writer(pe_resource_manager& res); + + //Adds bitmap from bitmap file data. If bitmap already exists, replaces it + //timestamp will be used for directories that will be added + void add_bitmap(const std::string& bitmap_file, uint32_t id, uint32_t language, uint32_t codepage = 0, uint32_t timestamp = 0); + void add_bitmap(const std::string& bitmap_file, const std::wstring& name, uint32_t language, uint32_t codepage = 0, uint32_t timestamp = 0); + + //Removes bitmap by name/ID and language + bool remove_bitmap(const std::wstring& name, uint32_t language); + bool remove_bitmap(uint32_t id, uint32_t language); + +private: + pe_resource_manager& res_; +}; +} diff --git a/tools/pe_bliss/resource_cursor_icon_reader.cpp b/tools/pe_bliss/resource_cursor_icon_reader.cpp new file mode 100644 index 0000000000..28a259163e --- /dev/null +++ b/tools/pe_bliss/resource_cursor_icon_reader.cpp @@ -0,0 +1,521 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <algorithm> +#include "resource_cursor_icon_reader.h" +#include "pe_structures.h" +#include "pe_resource_viewer.h" + +namespace pe_bliss +{ +using namespace pe_win; + +resource_cursor_icon_reader::resource_cursor_icon_reader(const pe_resource_viewer& res) + :res_(res) +{} + +//Helper function of creating icon headers from ICON_GROUP resource data +//Returns icon count +uint16_t resource_cursor_icon_reader::format_icon_headers(std::string& ico_data, const std::string& resource_data) +{ + //Check resource data size + if(resource_data.length() < sizeof(ico_header)) + throw pe_exception("Incorrect resource icon", pe_exception::resource_incorrect_icon); + + //Get icon header + const ico_header* info = reinterpret_cast<const ico_header*>(resource_data.data()); + + //Check resource data size + if(resource_data.length() < sizeof(ico_header) + info->Count * sizeof(icon_group)) + throw pe_exception("Incorrect resource icon", pe_exception::resource_incorrect_icon); + + //Reserve memory to speed up a little + ico_data.reserve(sizeof(ico_header) + info->Count * sizeof(icondirentry)); + ico_data.append(reinterpret_cast<const char*>(info), sizeof(ico_header)); + + //Iterate over all listed icons + uint32_t offset = sizeof(ico_header) + sizeof(icondirentry) * info->Count; + for(uint16_t i = 0; i != info->Count; ++i) + { + const icon_group* group = reinterpret_cast<const icon_group*>(resource_data.data() + sizeof(ico_header) + i * sizeof(icon_group)); + + //Fill icon data + icondirentry direntry; + direntry.BitCount = group->BitCount; + direntry.ColorCount = group->ColorCount; + direntry.Height = group->Height; + direntry.Planes = group->Planes; + direntry.Reserved = group->Reserved; + direntry.SizeInBytes = group->SizeInBytes; + direntry.Width = group->Width; + direntry.ImageOffset = offset; + + //Add icon header to returned value + ico_data.append(reinterpret_cast<const char*>(&direntry), sizeof(icondirentry)); + + offset += group->SizeInBytes; + } + + //Return icon count + return info->Count; +} + +//Returns single icon data by ID and language (minimum checks of format correctness) +const std::string resource_cursor_icon_reader::get_single_icon_by_id_lang(uint32_t language, uint32_t id) const +{ + //Get icon headers + std::string icon_data(lookup_icon_group_data_by_icon(id, language)); + //Append icon data + icon_data.append(res_.get_resource_data_by_id(language, pe_resource_viewer::resource_icon, id).get_data()); + return icon_data; +} + +//Returns single icon data by ID and index in language directory (instead of language) (minimum checks of format correctness) +const std::string resource_cursor_icon_reader::get_single_icon_by_id(uint32_t id, uint32_t index) const +{ + pe_resource_viewer::resource_language_list languages(res_.list_resource_languages(pe_resource_viewer::resource_icon, id)); + if(languages.size() <= index) + throw pe_exception("Resource data entry not found", pe_exception::resource_data_entry_not_found); + + //Get icon headers + std::string icon_data(lookup_icon_group_data_by_icon(id, languages.at(index))); + //Append icon data + icon_data.append(res_.get_resource_data_by_id(pe_resource_viewer::resource_icon, id, index).get_data()); + return icon_data; +} + +//Returns icon data by name and index in language directory (instead of language) (minimum checks of format correctness) +const std::string resource_cursor_icon_reader::get_icon_by_name(const std::wstring& name, uint32_t index) const +{ + std::string ret; + + //Get resource by name and index + const std::string data = res_.get_resource_data_by_name(pe_resource_viewer::resource_icon_group, name, index).get_data(); + + //Create icon headers + uint16_t icon_count = format_icon_headers(ret, data); + + //Append icon data + for(uint16_t i = 0; i != icon_count; ++i) + { + const icon_group* group = reinterpret_cast<const icon_group*>(data.data() + sizeof(ico_header) + i * sizeof(icon_group)); + ret += res_.get_resource_data_by_id(pe_resource_viewer::resource_icon, group->Number, index).get_data(); + } + + return ret; +} + +//Returns icon data by name and language (minimum checks of format correctness) +const std::string resource_cursor_icon_reader::get_icon_by_name(uint32_t language, const std::wstring& name) const +{ + std::string ret; + + //Get resource by name and language + const std::string data = res_.get_resource_data_by_name(language, pe_resource_viewer::resource_icon_group, name).get_data(); + + //Create icon headers + uint16_t icon_count = format_icon_headers(ret, data); + + //Append icon data + for(uint16_t i = 0; i != icon_count; ++i) + { + const icon_group* group = reinterpret_cast<const icon_group*>(data.data() + sizeof(ico_header) + i * sizeof(icon_group)); + ret += res_.get_resource_data_by_id(language, pe_resource_viewer::resource_icon, group->Number).get_data(); + } + + return ret; +} + +//Returns icon data by ID and language (minimum checks of format correctness) +const std::string resource_cursor_icon_reader::get_icon_by_id_lang(uint32_t language, uint32_t id) const +{ + std::string ret; + + //Get resource by language and id + const std::string data = res_.get_resource_data_by_id(language, pe_resource_viewer::resource_icon_group, id).get_data(); + + //Create icon headers + uint16_t icon_count = format_icon_headers(ret, data); + + //Append icon data + for(uint16_t i = 0; i != icon_count; ++i) + { + const icon_group* group = reinterpret_cast<const icon_group*>(data.data() + sizeof(ico_header) + i * sizeof(icon_group)); + ret += res_.get_resource_data_by_id(language, pe_resource_viewer::resource_icon, group->Number).get_data(); + } + + return ret; +} + +//Returns icon data by ID and index in language directory (instead of language) (minimum checks of format correctness) +const std::string resource_cursor_icon_reader::get_icon_by_id(uint32_t id, uint32_t index) const +{ + std::string ret; + + //Get resource by id and index + const std::string data = res_.get_resource_data_by_id(pe_resource_viewer::resource_icon_group, id, index).get_data(); + + //Create icon headers + uint16_t icon_count = format_icon_headers(ret, data); + + //Append icon data + for(uint16_t i = 0; i != icon_count; ++i) + { + const icon_group* group = reinterpret_cast<const icon_group*>(data.data() + sizeof(ico_header) + i * sizeof(icon_group)); + ret += res_.get_resource_data_by_id(pe_resource_viewer::resource_icon, group->Number, index).get_data(); + } + + return ret; +} + +//Checks for icon presence inside icon group, fills icon headers if found +bool resource_cursor_icon_reader::check_icon_presence(const std::string& icon_group_resource_data, uint32_t icon_id, std::string& ico_data) +{ + //Check resource data size + if(icon_group_resource_data.length() < sizeof(ico_header)) + throw pe_exception("Incorrect resource icon", pe_exception::resource_incorrect_icon); + + //Get icon header + const ico_header* info = reinterpret_cast<const ico_header*>(icon_group_resource_data.data()); + + //Check resource data size + if(icon_group_resource_data.length() < sizeof(ico_header) + info->Count * sizeof(icon_group)) + throw pe_exception("Incorrect resource icon", pe_exception::resource_incorrect_icon); + + for(uint16_t i = 0; i != info->Count; ++i) + { + const icon_group* group = reinterpret_cast<const icon_group*>(icon_group_resource_data.data() + sizeof(ico_header) + i * sizeof(icon_group)); + if(group->Number == icon_id) + { + //Reserve memory to speed up a little + ico_data.reserve(sizeof(ico_header) + sizeof(icondirentry)); + //Write single-icon icon header + ico_header new_header = *info; + new_header.Count = 1; + ico_data.append(reinterpret_cast<const char*>(&new_header), sizeof(ico_header)); + + //Fill icon data + icondirentry direntry; + direntry.BitCount = group->BitCount; + direntry.ColorCount = group->ColorCount; + direntry.Height = group->Height; + direntry.Planes = group->Planes; + direntry.Reserved = group->Reserved; + direntry.SizeInBytes = group->SizeInBytes; + direntry.Width = group->Width; + direntry.ImageOffset = sizeof(ico_header) + sizeof(icondirentry); + ico_data.append(reinterpret_cast<const char*>(&direntry), sizeof(direntry)); + + return true; + } + } + + return false; +} + +//Looks up icon group by icon id and returns full icon headers if found +const std::string resource_cursor_icon_reader::lookup_icon_group_data_by_icon(uint32_t icon_id, uint32_t language) const +{ + std::string icon_header_data; + + { + //List all ID-resources + pe_resource_viewer::resource_id_list ids(res_.list_resource_ids(pe_resource_viewer::resource_icon_group)); + + for(pe_resource_viewer::resource_id_list::const_iterator it = ids.begin(); it != ids.end(); ++it) + { + pe_resource_viewer::resource_language_list group_languages(res_.list_resource_languages(pe_resource_viewer::resource_icon_group, *it)); + if(std::find(group_languages.begin(), group_languages.end(), language) != group_languages.end() + && check_icon_presence(res_.get_resource_data_by_id(language, pe_resource_viewer::resource_icon_group, *it).get_data(), icon_id, icon_header_data)) + return icon_header_data; + } + } + + { + //List all named resources + pe_resource_viewer::resource_name_list names(res_.list_resource_names(pe_resource_viewer::resource_icon_group)); + for(pe_resource_viewer::resource_name_list::const_iterator it = names.begin(); it != names.end(); ++it) + { + pe_resource_viewer::resource_language_list group_languages(res_.list_resource_languages(pe_resource_viewer::resource_icon_group, *it)); + if(std::find(group_languages.begin(), group_languages.end(), language) != group_languages.end() + && check_icon_presence(res_.get_resource_data_by_name(language, pe_resource_viewer::resource_icon_group, *it).get_data(), icon_id, icon_header_data)) + return icon_header_data; + } + } + + throw pe_exception("No icon group find for requested icon", pe_exception::no_icon_group_found); +} + +//Returns single cursor data by ID and language (minimum checks of format correctness) +const std::string resource_cursor_icon_reader::get_single_cursor_by_id_lang(uint32_t language, uint32_t id) const +{ + std::string raw_cursor_data(res_.get_resource_data_by_id(language, pe_resource_viewer::resource_cursor, id).get_data()); + //Get cursor headers + std::string cursor_data(lookup_cursor_group_data_by_cursor(id, language, raw_cursor_data)); + //Append cursor data + cursor_data.append(raw_cursor_data.substr(sizeof(uint16_t) * 2 /* hotspot position */)); + return cursor_data; +} + +//Returns single cursor data by ID and index in language directory (instead of language) (minimum checks of format correctness) +const std::string resource_cursor_icon_reader::get_single_cursor_by_id(uint32_t id, uint32_t index) const +{ + pe_resource_viewer::resource_language_list languages(res_.list_resource_languages(pe_resource_viewer::resource_cursor, id)); + if(languages.size() <= index) + throw pe_exception("Resource data entry not found", pe_exception::resource_data_entry_not_found); + + std::string raw_cursor_data(res_.get_resource_data_by_id(pe_resource_viewer::resource_cursor, id, index).get_data()); + //Get cursor headers + std::string cursor_data(lookup_cursor_group_data_by_cursor(id, languages.at(index), raw_cursor_data)); + //Append cursor data + cursor_data.append(raw_cursor_data.substr(sizeof(uint16_t) * 2 /* hotspot position */)); + return cursor_data; +} + +//Helper function of creating cursor headers +//Returns cursor count +uint16_t resource_cursor_icon_reader::format_cursor_headers(std::string& cur_data, const std::string& resource_data, uint32_t language, uint32_t index) const +{ + //Check resource data length + if(resource_data.length() < sizeof(cursor_header)) + throw pe_exception("Incorrect resource cursor", pe_exception::resource_incorrect_cursor); + + const cursor_header* info = reinterpret_cast<const cursor_header*>(resource_data.data()); + + //Check resource data length + if(resource_data.length() < sizeof(cursor_header) + sizeof(cursor_group) * info->Count) + throw pe_exception("Incorrect resource cursor", pe_exception::resource_incorrect_cursor); + + //Reserve needed space to speed up a little + cur_data.reserve(sizeof(cursor_header) + info->Count * sizeof(cursordirentry)); + //Add cursor header + cur_data.append(reinterpret_cast<const char*>(info), sizeof(cursor_header)); + + //Iterate over all cursors listed in cursor group + uint32_t offset = sizeof(cursor_header) + sizeof(cursordirentry) * info->Count; + for(uint16_t i = 0; i != info->Count; ++i) + { + const cursor_group* group = reinterpret_cast<const cursor_group*>(resource_data.data() + sizeof(cursor_header) + i * sizeof(cursor_group)); + + //Fill cursor info + cursordirentry direntry; + direntry.ColorCount = 0; //OK + direntry.Width = static_cast<uint8_t>(group->Width); + direntry.Height = static_cast<uint8_t>(group->Height) / 2; + direntry.Reserved = 0; + + //Now read hotspot data from cursor data directory + const std::string cursor = index == 0xFFFFFFFF + ? res_.get_resource_data_by_id(language, pe_resource_viewer::resource_cursor, group->Number).get_data() + : res_.get_resource_data_by_id(pe_resource_viewer::resource_cursor, group->Number, index).get_data(); + if(cursor.length() < 2 * sizeof(uint16_t)) + throw pe_exception("Incorrect resource cursor", pe_exception::resource_incorrect_cursor); + + //Here it is - two words in the very beginning of cursor data + direntry.HotspotX = *reinterpret_cast<const uint16_t*>(cursor.data()); + direntry.HotspotY = *reinterpret_cast<const uint16_t*>(cursor.data() + sizeof(uint16_t)); + + //Fill the rest data + direntry.SizeInBytes = group->SizeInBytes - 2 * sizeof(uint16_t); + direntry.ImageOffset = offset; + + //Add cursor header + cur_data.append(reinterpret_cast<const char*>(&direntry), sizeof(cursordirentry)); + + offset += direntry.SizeInBytes; + } + + //Return cursor count + return info->Count; +} + +//Returns cursor data by name and language (minimum checks of format correctness) +const std::string resource_cursor_icon_reader::get_cursor_by_name(uint32_t language, const std::wstring& name) const +{ + std::string ret; + + //Get resource by name and language + const std::string resource_data = res_.get_resource_data_by_name(language, pe_resource_viewer::resource_cursor_group, name).get_data(); + + //Create cursor headers + uint16_t cursor_count = format_cursor_headers(ret, resource_data, language); + + //Add cursor data + for(uint16_t i = 0; i != cursor_count; ++i) + { + const cursor_group* group = reinterpret_cast<const cursor_group*>(resource_data.data() + sizeof(cursor_header) + i * sizeof(cursor_group)); + ret += res_.get_resource_data_by_id(language, pe_resource_viewer::resource_cursor, group->Number).get_data().substr(2 * sizeof(uint16_t)); + } + + return ret; +} + +//Returns cursor data by name and index in language directory (instead of language) (minimum checks of format correctness) +const std::string resource_cursor_icon_reader::get_cursor_by_name(const std::wstring& name, uint32_t index) const +{ + std::string ret; + + //Get resource by name and index + const std::string resource_data = res_.get_resource_data_by_name(pe_resource_viewer::resource_cursor_group, name, index).get_data(); + + //Create cursor headers + uint16_t cursor_count = format_cursor_headers(ret, resource_data, 0, index); + + //Add cursor data + for(uint16_t i = 0; i != cursor_count; ++i) + { + const cursor_group* group = reinterpret_cast<const cursor_group*>(resource_data.data() + sizeof(cursor_header) + i * sizeof(cursor_group)); + ret += res_.get_resource_data_by_id(pe_resource_viewer::resource_cursor, group->Number, index).get_data().substr(2 * sizeof(uint16_t)); + } + + return ret; +} + +//Returns cursor data by ID and language (minimum checks of format correctness) +const std::string resource_cursor_icon_reader::get_cursor_by_id_lang(uint32_t language, uint32_t id) const +{ + std::string ret; + + //Get resource by ID and language + const std::string resource_data = res_.get_resource_data_by_id(language, pe_resource_viewer::resource_cursor_group, id).get_data(); + + //Create cursor headers + uint16_t cursor_count = format_cursor_headers(ret, resource_data, language); + + //Add cursor data + for(uint16_t i = 0; i != cursor_count; ++i) + { + const cursor_group* group = reinterpret_cast<const cursor_group*>(resource_data.data() + sizeof(cursor_header) + i * sizeof(cursor_group)); + ret += res_.get_resource_data_by_id(language, pe_resource_viewer::resource_cursor, group->Number).get_data().substr(2 * sizeof(uint16_t)); + } + + return ret; +} + +//Returns cursor data by ID and index in language directory (instead of language) (minimum checks of format correctness) +const std::string resource_cursor_icon_reader::get_cursor_by_id(uint32_t id, uint32_t index) const +{ + std::string ret; + + //Get resource by ID and index + const std::string resource_data = res_.get_resource_data_by_id(pe_resource_viewer::resource_cursor_group, id, index).get_data(); + + //Create cursor headers + uint16_t cursor_count = format_cursor_headers(ret, resource_data, 0, index); + + //Add cursor data + for(uint16_t i = 0; i != cursor_count; ++i) + { + const cursor_group* group = reinterpret_cast<const cursor_group*>(resource_data.data() + sizeof(cursor_header) + i * sizeof(cursor_group)); + ret += res_.get_resource_data_by_id(pe_resource_viewer::resource_cursor, group->Number, index).get_data().substr(2 * sizeof(uint16_t)); + } + + return ret; +} + +//Checks for cursor presence inside cursor group, fills cursor headers if found +bool resource_cursor_icon_reader::check_cursor_presence(const std::string& cursor_group_resource_data, uint32_t cursor_id, std::string& cur_header_data, const std::string& raw_cursor_data) +{ + //Check resource data length + if(cursor_group_resource_data.length() < sizeof(cursor_header)) + throw pe_exception("Incorrect resource cursor", pe_exception::resource_incorrect_cursor); + + const cursor_header* info = reinterpret_cast<const cursor_header*>(cursor_group_resource_data.data()); + + //Check resource data length + if(cursor_group_resource_data.length() < sizeof(cursor_header) + sizeof(cursor_group)) + throw pe_exception("Incorrect resource cursor", pe_exception::resource_incorrect_cursor); + + //Iterate over all cursors listed in cursor group + for(uint16_t i = 0; i != info->Count; ++i) + { + const cursor_group* group = reinterpret_cast<const cursor_group*>(cursor_group_resource_data.data() + sizeof(cursor_header) + i * sizeof(cursor_group)); + + if(group->Number == cursor_id) + { + //Reserve needed space to speed up a little + cur_header_data.reserve(sizeof(cursor_header) + sizeof(cursordirentry)); + //Write single-cursor cursor header + cursor_header new_header = *info; + new_header.Count = 1; + cur_header_data.append(reinterpret_cast<const char*>(&new_header), sizeof(cursor_header)); + + //Fill cursor info + cursordirentry direntry; + direntry.ColorCount = 0; //OK + direntry.Width = static_cast<uint8_t>(group->Width); + direntry.Height = static_cast<uint8_t>(group->Height) / 2; + direntry.Reserved = 0; + + if(raw_cursor_data.length() < 2 * sizeof(uint16_t)) + throw pe_exception("Incorrect resource cursor", pe_exception::resource_incorrect_cursor); + + //Here it is - two words in the very beginning of cursor data + direntry.HotspotX = *reinterpret_cast<const uint16_t*>(raw_cursor_data.data()); + direntry.HotspotY = *reinterpret_cast<const uint16_t*>(raw_cursor_data.data() + sizeof(uint16_t)); + + //Fill the rest data + direntry.SizeInBytes = group->SizeInBytes - 2 * sizeof(uint16_t); + direntry.ImageOffset = sizeof(cursor_header) + sizeof(cursordirentry); + + //Add cursor header + cur_header_data.append(reinterpret_cast<const char*>(&direntry), sizeof(cursordirentry)); + + return true; + } + } + + return false; +} + +//Looks up cursor group by cursor id and returns full cursor headers if found +const std::string resource_cursor_icon_reader::lookup_cursor_group_data_by_cursor(uint32_t cursor_id, uint32_t language, const std::string& raw_cursor_data) const +{ + std::string cursor_header_data; + + { + //List all ID-resources + pe_resource_viewer::resource_id_list ids(res_.list_resource_ids(pe_resource_viewer::resource_cursor_group)); + + for(pe_resource_viewer::resource_id_list::const_iterator it = ids.begin(); it != ids.end(); ++it) + { + pe_resource_viewer::resource_language_list group_languages(res_.list_resource_languages(pe_resource_viewer::resource_cursor_group, *it)); + if(std::find(group_languages.begin(), group_languages.end(), language) != group_languages.end() + && check_cursor_presence(res_.get_resource_data_by_id(language, pe_resource_viewer::resource_cursor_group, *it).get_data(), cursor_id, cursor_header_data, raw_cursor_data)) + return cursor_header_data; + } + } + + { + //List all named resources + pe_resource_viewer::resource_name_list names(res_.list_resource_names(pe_resource_viewer::resource_cursor_group)); + for(pe_resource_viewer::resource_name_list::const_iterator it = names.begin(); it != names.end(); ++it) + { + pe_resource_viewer::resource_language_list group_languages(res_.list_resource_languages(pe_resource_viewer::resource_cursor_group, *it)); + if(std::find(group_languages.begin(), group_languages.end(), language) != group_languages.end() + && check_cursor_presence(res_.get_resource_data_by_name(language, pe_resource_viewer::resource_cursor_group, *it).get_data(), cursor_id, cursor_header_data, raw_cursor_data)) + return cursor_header_data; + } + } + + throw pe_exception("No cursor group find for requested icon", pe_exception::no_cursor_group_found); +} +} diff --git a/tools/pe_bliss/resource_cursor_icon_reader.h b/tools/pe_bliss/resource_cursor_icon_reader.h new file mode 100644 index 0000000000..e34fff419b --- /dev/null +++ b/tools/pe_bliss/resource_cursor_icon_reader.h @@ -0,0 +1,84 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <string> +#include "stdint_defs.h" + +namespace pe_bliss +{ +class pe_resource_viewer; + +class resource_cursor_icon_reader +{ +public: + resource_cursor_icon_reader(const pe_resource_viewer& res); + + //Returns single icon data by ID and language (minimum checks of format correctness) + const std::string get_single_icon_by_id_lang(uint32_t language, uint32_t id) const; + //Returns single icon data by ID and index in language directory (instead of language) (minimum checks of format correctness) + const std::string get_single_icon_by_id(uint32_t id, uint32_t index = 0) const; + + //Returns icon data of group of icons by name and language (minimum checks of format correctness) + const std::string get_icon_by_name(uint32_t language, const std::wstring& icon_group_name) const; + //Returns icon data of group of icons by name and index in language directory (instead of language) (minimum checks of format correctness) + const std::string get_icon_by_name(const std::wstring& icon_group_name, uint32_t index = 0) const; + //Returns icon data of group of icons by ID and language (minimum checks of format correctness) + const std::string get_icon_by_id_lang(uint32_t language, uint32_t icon_group_id) const; + //Returns icon data of group of icons by ID and index in language directory (instead of language) (minimum checks of format correctness) + const std::string get_icon_by_id(uint32_t icon_group_id, uint32_t index = 0) const; + + //Returns single cursor data by ID and language (minimum checks of format correctness) + const std::string get_single_cursor_by_id_lang(uint32_t language, uint32_t id) const; + //Returns single cursor data by ID and index in language directory (instead of language) (minimum checks of format correctness) + const std::string get_single_cursor_by_id(uint32_t id, uint32_t index = 0) const; + + //Returns cursor data by name and language (minimum checks of format correctness) + const std::string get_cursor_by_name(uint32_t language, const std::wstring& cursor_group_name) const; + //Returns cursor data by name and index in language directory (instead of language) (minimum checks of format correctness) + const std::string get_cursor_by_name(const std::wstring& cursor_group_name, uint32_t index = 0) const; + //Returns cursor data by ID and language (minimum checks of format correctness) + const std::string get_cursor_by_id_lang(uint32_t language, uint32_t cursor_group_id) const; + //Returns cursor data by ID and index in language directory (instead of language) (minimum checks of format correctness) + const std::string get_cursor_by_id(uint32_t cursor_group_id, uint32_t index = 0) const; + +private: + const pe_resource_viewer& res_; + + //Helper function of creating icon headers from ICON_GROUP resource data + //Returns icon count + static uint16_t format_icon_headers(std::string& ico_data, const std::string& resource_data); + + //Helper function of creating cursor headers from CURSOR_GROUP resource data + //Returns cursor count + uint16_t format_cursor_headers(std::string& cur_data, const std::string& resource_data, uint32_t language, uint32_t index = 0xFFFFFFFF) const; + + //Looks up icon group by icon id and returns full icon headers if found + const std::string lookup_icon_group_data_by_icon(uint32_t icon_id, uint32_t language) const; + //Checks for icon presence inside icon group, fills icon headers if found + static bool check_icon_presence(const std::string& icon_group_resource_data, uint32_t icon_id, std::string& ico_data); + + //Looks up cursor group by cursor id and returns full cursor headers if found + const std::string lookup_cursor_group_data_by_cursor(uint32_t cursor_id, uint32_t language, const std::string& raw_cursor_data) const; + //Checks for cursor presence inside cursor group, fills cursor headers if found + static bool check_cursor_presence(const std::string& icon_group_resource_data, uint32_t cursor_id, std::string& cur_header_data, const std::string& raw_cursor_data); +}; +} diff --git a/tools/pe_bliss/resource_cursor_icon_writer.cpp b/tools/pe_bliss/resource_cursor_icon_writer.cpp new file mode 100644 index 0000000000..2f1c4363c4 --- /dev/null +++ b/tools/pe_bliss/resource_cursor_icon_writer.cpp @@ -0,0 +1,447 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <algorithm> +#include <string.h> +#include "resource_cursor_icon_writer.h" + +namespace pe_bliss +{ +using namespace pe_win; + +resource_cursor_icon_writer::resource_cursor_icon_writer(pe_resource_manager& res) + :res_(res) +{} + +//Add icon helper +void resource_cursor_icon_writer::add_icon(const std::string& icon_file, const resource_data_info* group_icon_info /* or zero */, resource_directory_entry& new_icon_group_entry, const resource_directory::entry_finder& finder, uint32_t language, icon_place_mode mode, uint32_t codepage, uint32_t timestamp) +{ + //Check icon for correctness + if(icon_file.length() < sizeof(ico_header)) + throw pe_exception("Incorrect resource icon", pe_exception::resource_incorrect_icon); + + const ico_header* icon_header = reinterpret_cast<const ico_header*>(&icon_file[0]); + + unsigned long size_of_headers = sizeof(ico_header) + icon_header->Count * sizeof(icondirentry); + if(icon_file.length() < size_of_headers || icon_header->Count == 0) + throw pe_exception("Incorrect resource icon", pe_exception::resource_incorrect_icon); + + //Enumerate all icons in file + for(uint16_t i = 0; i != icon_header->Count; ++i) + { + //Check icon entries + const icondirentry* icon_entry = reinterpret_cast<const icondirentry*>(&icon_file[sizeof(ico_header) + i * sizeof(icondirentry)]); + if(icon_entry->SizeInBytes == 0 + || icon_entry->ImageOffset < size_of_headers + || !pe_utils::is_sum_safe(icon_entry->ImageOffset, icon_entry->SizeInBytes) + || icon_entry->ImageOffset + icon_entry->SizeInBytes > icon_file.length()) + throw pe_exception("Incorrect resource icon", pe_exception::resource_incorrect_icon); + } + + std::string icon_group_data; + ico_header* info = 0; + + if(group_icon_info) + { + //If icon group already exists + { + icon_group_data = group_icon_info->get_data(); + codepage = group_icon_info->get_codepage(); //Don't change codepage of icon group entry + } + + //Check resource data size + if(icon_group_data.length() < sizeof(ico_header)) + throw pe_exception("Incorrect resource icon", pe_exception::resource_incorrect_icon); + + //Get icon header + info = reinterpret_cast<ico_header*>(&icon_group_data[0]); + + //Check resource data size + if(icon_group_data.length() < sizeof(ico_header) + info->Count * sizeof(icon_group)) + throw pe_exception("Incorrect resource icon", pe_exception::resource_incorrect_icon); + + icon_group_data.resize(sizeof(ico_header) + (info->Count + icon_header->Count) * sizeof(icon_group)); + info = reinterpret_cast<ico_header*>(&icon_group_data[0]); //In case if memory was reallocated + } + else //Entry not found - icon group doesn't exist + { + icon_group_data.resize(sizeof(ico_header) + icon_header->Count * sizeof(icon_group)); + memcpy(&icon_group_data[0], icon_header, sizeof(ico_header)); + } + + //Search for available icon IDs + std::vector<uint16_t> icon_id_list(get_icon_or_cursor_free_id_list(pe_resource_viewer::resource_icon, mode, icon_header->Count)); + + //Enumerate all icons in file + for(uint16_t i = 0; i != icon_header->Count; ++i) + { + const icondirentry* icon_entry = reinterpret_cast<const icondirentry*>(&icon_file[sizeof(ico_header) + i * sizeof(icondirentry)]); + icon_group group = {0}; + + //Fill icon resource header + group.BitCount = icon_entry->BitCount; + group.ColorCount = icon_entry->ColorCount; + group.Height = icon_entry->Height; + group.Planes = icon_entry->Planes; + group.Reserved = icon_entry->Reserved; + group.SizeInBytes = icon_entry->SizeInBytes; + group.Width = icon_entry->Width; + group.Number = icon_id_list.at(i); + + memcpy(&icon_group_data[sizeof(ico_header) + ((info ? info->Count : 0) + i) * sizeof(icon_group)], &group, sizeof(group)); + + //Add icon to resources + resource_directory_entry new_entry; + new_entry.set_id(group.Number); + res_.add_resource(icon_file.substr(icon_entry->ImageOffset, icon_entry->SizeInBytes), pe_resource_viewer::resource_icon, new_entry, resource_directory::entry_finder(group.Number), language, codepage, timestamp); + } + + if(info) + info->Count += icon_header->Count; //Increase icon count, if we're adding icon to existing group + + { + //Add or replace icon group data entry + res_.add_resource(icon_group_data, pe_resource_viewer::resource_icon_group, new_icon_group_entry, finder, language, codepage, timestamp); + } +} + +//Returns free icon or cursor ID list depending on icon_place_mode +const std::vector<uint16_t> resource_cursor_icon_writer::get_icon_or_cursor_free_id_list(pe_resource_viewer::resource_type type, icon_place_mode mode, uint32_t count) +{ + //Search for available icon/cursor IDs + std::vector<uint16_t> icon_cursor_id_list; + + try + { + //If any icon exists + //List icon IDs + std::vector<uint32_t> id_list(res_.list_resource_ids(type)); + std::sort(id_list.begin(), id_list.end()); + + //If we are placing icon on free spaces + //I.e., icon IDs 1, 3, 4, 7, 8 already exist + //We'll place five icons on IDs 2, 5, 6, 9, 10 + if(mode != icon_place_after_max_icon_id) + { + if(!id_list.empty()) + { + //Determine and list free icon IDs + for(std::vector<uint32_t>::const_iterator it = id_list.begin(); it != id_list.end(); ++it) + { + if(it == id_list.begin()) + { + if(*it > 1) + { + for(uint16_t i = 1; i != *it; ++i) + { + icon_cursor_id_list.push_back(i); + if(icon_cursor_id_list.size() == count) + break; + } + } + } + else if(*(it - 1) - *it > 1) + { + for(uint16_t i = static_cast<uint16_t>(*(it - 1) + 1); i != static_cast<uint16_t>(*it); ++i) + { + icon_cursor_id_list.push_back(i); + if(icon_cursor_id_list.size() == count) + break; + } + } + + if(icon_cursor_id_list.size() == count) + break; + } + } + } + + uint32_t max_id = id_list.empty() ? 0 : *std::max_element(id_list.begin(), id_list.end()); + for(uint32_t i = static_cast<uint32_t>(icon_cursor_id_list.size()); i != count; ++i) + icon_cursor_id_list.push_back(static_cast<uint16_t>(++max_id)); + } + catch(const pe_exception&) //Entry not found + { + for(uint16_t i = 1; i != count + 1; ++i) + icon_cursor_id_list.push_back(i); + } + + return icon_cursor_id_list; +} + +//Add cursor helper +void resource_cursor_icon_writer::add_cursor(const std::string& cursor_file, const resource_data_info* group_cursor_info /* or zero */, resource_directory_entry& new_cursor_group_entry, const resource_directory::entry_finder& finder, uint32_t language, icon_place_mode mode, uint32_t codepage, uint32_t timestamp) +{ + //Check cursor for correctness + if(cursor_file.length() < sizeof(cursor_header)) + throw pe_exception("Incorrect resource cursor", pe_exception::resource_incorrect_cursor); + + const cursor_header* cur_header = reinterpret_cast<const cursor_header*>(&cursor_file[0]); + + unsigned long size_of_headers = sizeof(cursor_header) + cur_header->Count * sizeof(cursordirentry); + if(cursor_file.length() < size_of_headers || cur_header->Count == 0) + throw pe_exception("Incorrect resource cursor", pe_exception::resource_incorrect_cursor); + + //Enumerate all cursors in file + for(uint16_t i = 0; i != cur_header->Count; ++i) + { + //Check cursor entries + const cursordirentry* cursor_entry = reinterpret_cast<const cursordirentry*>(&cursor_file[sizeof(cursor_header) + i * sizeof(cursordirentry)]); + if(cursor_entry->SizeInBytes == 0 + || cursor_entry->ImageOffset < size_of_headers + || !pe_utils::is_sum_safe(cursor_entry->ImageOffset, cursor_entry->SizeInBytes) + || cursor_entry->ImageOffset + cursor_entry->SizeInBytes > cursor_file.length()) + throw pe_exception("Incorrect resource cursor", pe_exception::resource_incorrect_cursor); + } + + std::string cursor_group_data; + cursor_header* info = 0; + + if(group_cursor_info) + { + //If cursor group already exists + { + cursor_group_data = group_cursor_info->get_data(); + codepage = group_cursor_info->get_codepage(); //Don't change codepage of cursor group entry + } + + //Check resource data size + if(cursor_group_data.length() < sizeof(cursor_header)) + throw pe_exception("Incorrect resource cursor", pe_exception::resource_incorrect_cursor); + + //Get cursor header + info = reinterpret_cast<cursor_header*>(&cursor_group_data[0]); + + //Check resource data size + if(cursor_group_data.length() < sizeof(cursor_header) + info->Count * sizeof(cursor_group)) + throw pe_exception("Incorrect resource cursor", pe_exception::resource_incorrect_cursor); + + cursor_group_data.resize(sizeof(cursor_header) + (info->Count + cur_header->Count) * sizeof(cursor_group)); + info = reinterpret_cast<cursor_header*>(&cursor_group_data[0]); //In case if memory was reallocated + } + else //Entry not found - cursor group doesn't exist + { + cursor_group_data.resize(sizeof(cursor_header) + cur_header->Count * sizeof(cursor_group)); + memcpy(&cursor_group_data[0], cur_header, sizeof(cursor_header)); + } + + //Search for available cursor IDs + std::vector<uint16_t> cursor_id_list(get_icon_or_cursor_free_id_list(pe_resource_viewer::resource_cursor, mode, cur_header->Count)); + + //Enumerate all cursors in file + for(uint16_t i = 0; i != cur_header->Count; ++i) + { + const cursordirentry* cursor_entry = reinterpret_cast<const cursordirentry*>(&cursor_file[sizeof(cursor_header) + i * sizeof(cursordirentry)]); + cursor_group group = {0}; + + //Fill cursor resource header + group.Height = cursor_entry->Height * 2; + group.SizeInBytes = cursor_entry->SizeInBytes + 2 * sizeof(uint16_t) /* hotspot coordinates */; + group.Width = cursor_entry->Width; + group.Number = cursor_id_list.at(i); + + memcpy(&cursor_group_data[sizeof(cursor_header) + ((info ? info->Count : 0) + i) * sizeof(cursor_group)], &group, sizeof(group)); + + //Add cursor to resources + resource_directory_entry new_entry; + new_entry.set_id(group.Number); + + //Fill resource data (two WORDs for hotspot of cursor, and cursor bitmap data) + std::string cur_data; + cur_data.resize(sizeof(uint16_t) * 2); + memcpy(&cur_data[0], &cursor_entry->HotspotX, sizeof(uint16_t)); + memcpy(&cur_data[sizeof(uint16_t)], &cursor_entry->HotspotY, sizeof(uint16_t)); + cur_data.append(cursor_file.substr(cursor_entry->ImageOffset, cursor_entry->SizeInBytes)); + + res_.add_resource(cur_data, pe_resource_viewer::resource_cursor, new_entry, resource_directory::entry_finder(group.Number), language, codepage, timestamp); + } + + if(info) + info->Count += cur_header->Count; //Increase cursor count, if we're adding cursor to existing group + + { + //Add or replace cursor group data entry + res_.add_resource(cursor_group_data, pe_resource_viewer::resource_cursor_group, new_cursor_group_entry, finder, language, codepage, timestamp); + } +} + +//Adds icon(s) from icon file data +//timestamp will be used for directories that will be added +//If icon group with name "icon_group_name" or ID "icon_group_id" already exists, it will be appended with new icon(s) +//(Codepage of icon group and icons will not be changed in this case) +//icon_place_mode determines, how new icon(s) will be placed +void resource_cursor_icon_writer::add_icon(const std::string& icon_file, const std::wstring& icon_group_name, uint32_t language, icon_place_mode mode, uint32_t codepage, uint32_t timestamp) +{ + resource_directory_entry new_icon_group_entry; + new_icon_group_entry.set_name(icon_group_name); + std::auto_ptr<resource_data_info> data_info; + + try + { + data_info.reset(new resource_data_info(res_.get_resource_data_by_name(language, pe_resource_viewer::resource_icon_group, icon_group_name))); + } + catch(const pe_exception&) //Entry not found + { + } + + add_icon(icon_file, data_info.get(), new_icon_group_entry, resource_directory::entry_finder(icon_group_name), language, mode, codepage, timestamp); +} + +void resource_cursor_icon_writer::add_icon(const std::string& icon_file, uint32_t icon_group_id, uint32_t language, icon_place_mode mode, uint32_t codepage, uint32_t timestamp) +{ + resource_directory_entry new_icon_group_entry; + new_icon_group_entry.set_id(icon_group_id); + std::auto_ptr<resource_data_info> data_info; + + try + { + data_info.reset(new resource_data_info(res_.get_resource_data_by_id(language, pe_resource_viewer::resource_icon_group, icon_group_id))); + } + catch(const pe_exception&) //Entry not found + { + } + + add_icon(icon_file, data_info.get(), new_icon_group_entry, resource_directory::entry_finder(icon_group_id), language, mode, codepage, timestamp); +} + +//Adds cursor(s) from cursor file data +//timestamp will be used for directories that will be added +//If cursor group with name "cursor_group_name" or ID "cursor_group_id" already exists, it will be appended with new cursor(s) +//(Codepage of cursor group and cursors will not be changed in this case) +//icon_place_mode determines, how new cursor(s) will be placed +void resource_cursor_icon_writer::add_cursor(const std::string& cursor_file, const std::wstring& cursor_group_name, uint32_t language, icon_place_mode mode, uint32_t codepage, uint32_t timestamp) +{ + resource_directory_entry new_cursor_group_entry; + new_cursor_group_entry.set_name(cursor_group_name); + std::auto_ptr<resource_data_info> data_info; + + try + { + data_info.reset(new resource_data_info(res_.get_resource_data_by_name(language, pe_resource_viewer::resource_cursor_group, cursor_group_name))); + } + catch(const pe_exception&) //Entry not found + { + } + + add_cursor(cursor_file, data_info.get(), new_cursor_group_entry, resource_directory::entry_finder(cursor_group_name), language, mode, codepage, timestamp); +} + +void resource_cursor_icon_writer::add_cursor(const std::string& cursor_file, uint32_t cursor_group_id, uint32_t language, icon_place_mode mode, uint32_t codepage, uint32_t timestamp) +{ + resource_directory_entry new_cursor_group_entry; + new_cursor_group_entry.set_id(cursor_group_id); + std::auto_ptr<resource_data_info> data_info; + + try + { + data_info.reset(new resource_data_info(res_.get_resource_data_by_id(language, pe_resource_viewer::resource_cursor_group, cursor_group_id))); + } + catch(const pe_exception&) //Entry not found + { + } + + add_cursor(cursor_file, data_info.get(), new_cursor_group_entry, resource_directory::entry_finder(cursor_group_id), language, mode, codepage, timestamp); +} + +//Remove icon group helper +void resource_cursor_icon_writer::remove_icons_from_icon_group(const std::string& icon_group_data, uint32_t language) +{ + //Check resource data size + if(icon_group_data.length() < sizeof(ico_header)) + throw pe_exception("Incorrect resource icon", pe_exception::resource_incorrect_icon); + + //Get icon header + const ico_header* info = reinterpret_cast<const ico_header*>(icon_group_data.data()); + + uint16_t icon_count = info->Count; + + //Check resource data size + if(icon_group_data.length() < sizeof(ico_header) + icon_count * sizeof(icon_group)) + throw pe_exception("Incorrect resource icon", pe_exception::resource_incorrect_icon); + + //Remove icon data + for(uint16_t i = 0; i != icon_count; ++i) + { + const icon_group* group = reinterpret_cast<const icon_group*>(icon_group_data.data() + sizeof(ico_header) + i * sizeof(icon_group)); + res_.remove_resource(pe_resource_viewer::resource_icon, group->Number, language); + } +} + +//Remove cursor group helper +void resource_cursor_icon_writer::remove_cursors_from_cursor_group(const std::string& cursor_group_data, uint32_t language) +{ + //Check resource data size + if(cursor_group_data.length() < sizeof(cursor_header)) + throw pe_exception("Incorrect resource cursor", pe_exception::resource_incorrect_cursor); + + //Get icon header + const cursor_header* info = reinterpret_cast<const cursor_header*>(cursor_group_data.data()); + + uint16_t cursor_count = info->Count; + + //Check resource data size + if(cursor_group_data.length() < sizeof(cursor_header) + cursor_count * sizeof(cursor_group)) + throw pe_exception("Incorrect resource cursor", pe_exception::resource_incorrect_cursor); + + //Remove icon data + for(uint16_t i = 0; i != cursor_count; ++i) + { + const icon_group* group = reinterpret_cast<const icon_group*>(cursor_group_data.data() + sizeof(cursor_header) + i * sizeof(cursor_group)); + res_.remove_resource(pe_resource_viewer::resource_cursor, group->Number, language); + } +} + +//Removes cursor group and all its cursors by name/ID and language +bool resource_cursor_icon_writer::remove_cursor_group(const std::wstring& cursor_group_name, uint32_t language) +{ + //Get resource by name and language + const std::string data = res_.get_resource_data_by_name(language, pe_resource_viewer::resource_cursor_group, cursor_group_name).get_data(); + remove_cursors_from_cursor_group(data, language); + return res_.remove_resource(pe_resource_viewer::resource_cursor_group, cursor_group_name, language); +} + +//Removes cursor group and all its cursors by name/ID and language +bool resource_cursor_icon_writer::remove_cursor_group(uint32_t cursor_group_id, uint32_t language) +{ + //Get resource by name and language + const std::string data = res_.get_resource_data_by_id(language, pe_resource_viewer::resource_cursor_group, cursor_group_id).get_data(); + remove_cursors_from_cursor_group(data, language); + return res_.remove_resource(pe_resource_viewer::resource_cursor_group, cursor_group_id, language); +} + +//Removes icon group and all its icons by name/ID and language +bool resource_cursor_icon_writer::remove_icon_group(const std::wstring& icon_group_name, uint32_t language) +{ + //Get resource by name and language + const std::string data = res_.get_resource_data_by_name(language, pe_resource_viewer::resource_icon_group, icon_group_name).get_data(); + remove_icons_from_icon_group(data, language); + return res_.remove_resource(pe_resource_viewer::resource_icon_group, icon_group_name, language); +} + +//Removes icon group and all its icons by name/ID and language +bool resource_cursor_icon_writer::remove_icon_group(uint32_t icon_group_id, uint32_t language) +{ + //Get resource by name and language + const std::string data = res_.get_resource_data_by_id(language, pe_resource_viewer::resource_icon_group, icon_group_id).get_data(); + remove_icons_from_icon_group(data, language); + return res_.remove_resource(pe_resource_viewer::resource_icon_group, icon_group_id, language); +} +} diff --git a/tools/pe_bliss/resource_cursor_icon_writer.h b/tools/pe_bliss/resource_cursor_icon_writer.h new file mode 100644 index 0000000000..e73ac6a093 --- /dev/null +++ b/tools/pe_bliss/resource_cursor_icon_writer.h @@ -0,0 +1,94 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <string> +#include <vector> +#include "stdint_defs.h" +#include "pe_resource_manager.h" + +namespace pe_bliss +{ +class pe_resource_manager; + +class resource_cursor_icon_writer +{ +public: + //Determines, how new icon(s) or cursor(s) will be placed + enum icon_place_mode + { + icon_place_after_max_icon_id, //Icon(s) will be placed after all existing + icon_place_free_ids //New icon(s) will take all free IDs between existing icons + }; + +public: + resource_cursor_icon_writer(pe_resource_manager& res); + + //Removes icon group and all its icons by name/ID and language + bool remove_icon_group(const std::wstring& icon_group_name, uint32_t language); + bool remove_icon_group(uint32_t icon_group_id, uint32_t language); + + //Adds icon(s) from icon file data + //timestamp will be used for directories that will be added + //If icon group with name "icon_group_name" or ID "icon_group_id" already exists, it will be appended with new icon(s) + //(Codepage of icon group and icons will not be changed in this case) + //icon_place_mode determines, how new icon(s) will be placed + void add_icon(const std::string& icon_file, + const std::wstring& icon_group_name, + uint32_t language, icon_place_mode mode = icon_place_after_max_icon_id, + uint32_t codepage = 0, uint32_t timestamp = 0); + + void add_icon(const std::string& icon_file, + uint32_t icon_group_id, + uint32_t language, icon_place_mode mode = icon_place_after_max_icon_id, + uint32_t codepage = 0, uint32_t timestamp = 0); + + //Removes cursor group and all its cursors by name/ID and language + bool remove_cursor_group(const std::wstring& cursor_group_name, uint32_t language); + bool remove_cursor_group(uint32_t cursor_group_id, uint32_t language); + + //Adds cursor(s) from cursor file data + //timestamp will be used for directories that will be added + //If cursor group with name "cursor_group_name" or ID "cursor_group_id" already exists, it will be appended with new cursor(s) + //(Codepage of cursor group and cursors will not be changed in this case) + //icon_place_mode determines, how new cursor(s) will be placed + void add_cursor(const std::string& cursor_file, const std::wstring& cursor_group_name, uint32_t language, icon_place_mode mode = icon_place_after_max_icon_id, uint32_t codepage = 0, uint32_t timestamp = 0); + void add_cursor(const std::string& cursor_file, uint32_t cursor_group_id, uint32_t language, icon_place_mode mode = icon_place_after_max_icon_id, uint32_t codepage = 0, uint32_t timestamp = 0); + +private: + pe_resource_manager& res_; + + //Add icon helper + void add_icon(const std::string& icon_file, const resource_data_info* group_icon_info /* or zero */, resource_directory_entry& new_icon_group_entry, const resource_directory::entry_finder& finder, uint32_t language, icon_place_mode mode, uint32_t codepage, uint32_t timestamp); + + //Remove icon group helper + void remove_icons_from_icon_group(const std::string& icon_group_data, uint32_t language); + + //Add cursor helper + void add_cursor(const std::string& cursor_file, const resource_data_info* group_cursor_info /* or zero */, resource_directory_entry& new_cursor_group_entry, const resource_directory::entry_finder& finder, uint32_t language, icon_place_mode mode, uint32_t codepage, uint32_t timestamp); + + //Remove cursor group helper + void remove_cursors_from_cursor_group(const std::string& cursor_group_data, uint32_t language); + + //Returns free icon or cursor ID list depending on icon_place_mode + const std::vector<uint16_t> get_icon_or_cursor_free_id_list(pe_resource_manager::resource_type type, icon_place_mode mode, uint32_t count); +}; +} diff --git a/tools/pe_bliss/resource_data_info.cpp b/tools/pe_bliss/resource_data_info.cpp new file mode 100644 index 0000000000..75bb060eae --- /dev/null +++ b/tools/pe_bliss/resource_data_info.cpp @@ -0,0 +1,48 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include "resource_data_info.h" +#include "pe_resource_viewer.h" + +namespace pe_bliss +{ +//Default constructor +resource_data_info::resource_data_info(const std::string& data, uint32_t codepage) + :data_(data), codepage_(codepage) +{} + +//Constructor from data +resource_data_info::resource_data_info(const resource_data_entry& data) + :data_(data.get_data()), codepage_(data.get_codepage()) +{} + +//Returns resource data +const std::string& resource_data_info::get_data() const +{ + return data_; +} + +//Returns resource codepage +uint32_t resource_data_info::get_codepage() const +{ + return codepage_; +} +} diff --git a/tools/pe_bliss/resource_data_info.h b/tools/pe_bliss/resource_data_info.h new file mode 100644 index 0000000000..e2275ebbf5 --- /dev/null +++ b/tools/pe_bliss/resource_data_info.h @@ -0,0 +1,48 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <string> +#include "stdint_defs.h" + +namespace pe_bliss +{ +class resource_data_entry; + +//Class representing resource data +class resource_data_info +{ +public: + //Constructor from data + resource_data_info(const std::string& data, uint32_t codepage); + //Constructor from data + explicit resource_data_info(const resource_data_entry& data); + + //Returns resource data + const std::string& get_data() const; + //Returns resource codepage + uint32_t get_codepage() const; + +private: + std::string data_; + uint32_t codepage_; +}; +} diff --git a/tools/pe_bliss/resource_internal.h b/tools/pe_bliss/resource_internal.h new file mode 100644 index 0000000000..64a5bf3903 --- /dev/null +++ b/tools/pe_bliss/resource_internal.h @@ -0,0 +1,34 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once + +#define U16TEXT(t) reinterpret_cast<const unicode16_t*>( t ) + +#define StringFileInfo U16TEXT("S\0t\0r\0i\0n\0g\0F\0i\0l\0e\0I\0n\0f\0o\0\0") +#define SizeofStringFileInfo sizeof("S\0t\0r\0i\0n\0g\0F\0i\0l\0e\0I\0n\0f\0o\0\0") +#define VarFileInfo U16TEXT("V\0a\0r\0F\0i\0l\0e\0I\0n\0f\0o\0\0") +#define Translation U16TEXT("T\0r\0a\0n\0s\0l\0a\0t\0i\0o\0n\0\0") + +#define VarFileInfoAligned U16TEXT("V\0a\0r\0F\0i\0l\0e\0I\0n\0f\0o\0\0\0\0") +#define TranslationAligned U16TEXT("T\0r\0a\0n\0s\0l\0a\0t\0i\0o\0n\0\0\0\0") +#define SizeofVarFileInfoAligned sizeof("V\0a\0r\0F\0i\0l\0e\0I\0n\0f\0o\0\0\0\0") +#define SizeofTranslationAligned sizeof("T\0r\0a\0n\0s\0l\0a\0t\0i\0o\0n\0\0\0\0") diff --git a/tools/pe_bliss/resource_message_list_reader.cpp b/tools/pe_bliss/resource_message_list_reader.cpp new file mode 100644 index 0000000000..f2ea142bee --- /dev/null +++ b/tools/pe_bliss/resource_message_list_reader.cpp @@ -0,0 +1,131 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include "resource_message_list_reader.h" +#include "pe_resource_viewer.h" + +namespace pe_bliss +{ +using namespace pe_win; + +resource_message_list_reader::resource_message_list_reader(const pe_resource_viewer& res) + :res_(res) +{} + +//Helper function of parsing message list table +const resource_message_list resource_message_list_reader::parse_message_list(const std::string& resource_data) +{ + resource_message_list ret; + + //Check resource data length + if(resource_data.length() < sizeof(message_resource_data)) + throw pe_exception("Incorrect resource message table", pe_exception::resource_incorrect_message_table); + + const message_resource_data* message_data = reinterpret_cast<const message_resource_data*>(resource_data.data()); + + //Check resource data length more carefully and some possible overflows + if(message_data->NumberOfBlocks >= pe_utils::max_dword / sizeof(message_resource_block) + || !pe_utils::is_sum_safe(message_data->NumberOfBlocks * sizeof(message_resource_block), sizeof(message_resource_data)) + || resource_data.length() < message_data->NumberOfBlocks * sizeof(message_resource_block) + sizeof(message_resource_data)) + throw pe_exception("Incorrect resource message table", pe_exception::resource_incorrect_message_table); + + //Iterate over all message resource blocks + for(unsigned long i = 0; i != message_data->NumberOfBlocks; ++i) + { + //Get block + const message_resource_block* block = + reinterpret_cast<const message_resource_block*>(resource_data.data() + sizeof(message_resource_data) - sizeof(message_resource_block) + sizeof(message_resource_block) * i); + + //Check resource data length and IDs + if(resource_data.length() < block->OffsetToEntries || block->LowId > block->HighId) + throw pe_exception("Incorrect resource message table", pe_exception::resource_incorrect_message_table); + + unsigned long current_pos = 0; + static const unsigned long size_of_entry_headers = 4; + //List all message resource entries in block + for(uint32_t curr_id = block->LowId; curr_id <= block->HighId; curr_id++) + { + //Check resource data length and some possible overflows + if(!pe_utils::is_sum_safe(block->OffsetToEntries, current_pos) + || !pe_utils::is_sum_safe(block->OffsetToEntries + current_pos, size_of_entry_headers) + || resource_data.length() < block->OffsetToEntries + current_pos + size_of_entry_headers) + throw pe_exception("Incorrect resource message table", pe_exception::resource_incorrect_message_table); + + //Get entry + const message_resource_entry* entry = reinterpret_cast<const message_resource_entry*>(resource_data.data() + block->OffsetToEntries + current_pos); + + //Check resource data length and entry length and some possible overflows + if(entry->Length < size_of_entry_headers + || !pe_utils::is_sum_safe(block->OffsetToEntries + current_pos, entry->Length) + || resource_data.length() < block->OffsetToEntries + current_pos + entry->Length + || entry->Length < size_of_entry_headers) + throw pe_exception("Incorrect resource message table", pe_exception::resource_incorrect_message_table); + + if(entry->Flags & message_resource_unicode) + { + //If string is UNICODE + //Check its length + if(entry->Length % 2) + throw pe_exception("Incorrect resource message table", pe_exception::resource_incorrect_message_table); + + //Add ID and string to message table +#ifdef PE_BLISS_WINDOWS + ret.insert(std::make_pair(curr_id, message_table_item( + std::wstring(reinterpret_cast<const wchar_t*>(resource_data.data() + block->OffsetToEntries + current_pos + size_of_entry_headers), + (entry->Length - size_of_entry_headers) / 2) + ))); +#else + ret.insert(std::make_pair(curr_id, message_table_item( + pe_utils::from_ucs2(u16string(reinterpret_cast<const unicode16_t*>(resource_data.data() + block->OffsetToEntries + current_pos + size_of_entry_headers), + (entry->Length - size_of_entry_headers) / 2)) + ))); +#endif + } + else + { + //If string is ANSI + //Add ID and string to message table + ret.insert(std::make_pair(curr_id, message_table_item( + std::string(resource_data.data() + block->OffsetToEntries + current_pos + size_of_entry_headers, + entry->Length - size_of_entry_headers) + ))); + } + + //Go to next entry + current_pos += entry->Length; + } + } + + return ret; +} + +//Returns message table data by ID and index in language directory (instead of language) +const resource_message_list resource_message_list_reader::get_message_table_by_id(uint32_t id, uint32_t index) const +{ + return parse_message_list(res_.get_resource_data_by_id(pe_resource_viewer::resource_message_table, id, index).get_data()); +} + +//Returns message table data by ID and language +const resource_message_list resource_message_list_reader::get_message_table_by_id_lang(uint32_t language, uint32_t id) const +{ + return parse_message_list(res_.get_resource_data_by_id(language, pe_resource_viewer::resource_message_table, id).get_data()); +} +} diff --git a/tools/pe_bliss/resource_message_list_reader.h b/tools/pe_bliss/resource_message_list_reader.h new file mode 100644 index 0000000000..a0ac96eb8c --- /dev/null +++ b/tools/pe_bliss/resource_message_list_reader.h @@ -0,0 +1,49 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include "message_table.h" + +namespace pe_bliss +{ +class pe_resource_viewer; + +//ID; message_table_item +typedef std::map<uint32_t, message_table_item> resource_message_list; + +class resource_message_list_reader +{ +public: + resource_message_list_reader(const pe_resource_viewer& res); + + //Returns message table data by ID and language + const resource_message_list get_message_table_by_id_lang(uint32_t language, uint32_t id) const; + //Returns message table data by ID and index in language directory (instead of language) + const resource_message_list get_message_table_by_id(uint32_t id, uint32_t index = 0) const; + + //Helper function of parsing message list table + //resource_data - raw message table resource data + static const resource_message_list parse_message_list(const std::string& resource_data); + +private: + const pe_resource_viewer& res_; +}; +} diff --git a/tools/pe_bliss/resource_string_table_reader.cpp b/tools/pe_bliss/resource_string_table_reader.cpp new file mode 100644 index 0000000000..8a51720e6a --- /dev/null +++ b/tools/pe_bliss/resource_string_table_reader.cpp @@ -0,0 +1,109 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include "resource_string_table_reader.h" +#include "pe_resource_viewer.h" + +namespace pe_bliss +{ +resource_string_table_reader::resource_string_table_reader(const pe_resource_viewer& res) + :res_(res) +{} + +//Returns string table data by ID and index in language directory (instead of language) +const resource_string_list resource_string_table_reader::get_string_table_by_id(uint32_t id, uint32_t index) const +{ + return parse_string_list(id, res_.get_resource_data_by_id(pe_resource_viewer::resource_string, id, index).get_data()); +} + +//Returns string table data by ID and language +const resource_string_list resource_string_table_reader::get_string_table_by_id_lang(uint32_t language, uint32_t id) const +{ + return parse_string_list(id, res_.get_resource_data_by_id(language, pe_resource_viewer::resource_string, id).get_data()); +} + +//Helper function of parsing string list table +const resource_string_list resource_string_table_reader::parse_string_list(uint32_t id, const std::string& resource_data) +{ + resource_string_list ret; + + //16 is maximum count of strings in a string table + static const unsigned long max_string_list_entries = 16; + unsigned long passed_bytes = 0; + for(unsigned long i = 0; i != max_string_list_entries; ++i) + { + //Check resource data length + if(resource_data.length() < sizeof(uint16_t) + passed_bytes) + throw pe_exception("Incorrect resource string table", pe_exception::resource_incorrect_string_table); + + //Get string length - the first WORD + uint16_t string_length = *reinterpret_cast<const uint16_t*>(resource_data.data() + passed_bytes); + passed_bytes += sizeof(uint16_t); //WORD containing string length + + //Check resource data length again + if(resource_data.length() < string_length + passed_bytes) + throw pe_exception("Incorrect resource string table", pe_exception::resource_incorrect_string_table); + + if(string_length) + { + //Create and save string (UNICODE) +#ifdef PE_BLISS_WINDOWS + ret.insert( + std::make_pair(static_cast<uint16_t>(((id - 1) << 4) + i), //ID of string is calculated such way + std::wstring(reinterpret_cast<const wchar_t*>(resource_data.data() + passed_bytes), string_length))); +#else + ret.insert( + std::make_pair(static_cast<uint16_t>(((id - 1) << 4) + i), //ID of string is calculated such way + pe_utils::from_ucs2(u16string(reinterpret_cast<const unicode16_t*>(resource_data.data() + passed_bytes), string_length)))); +#endif + } + + //Go to next string + passed_bytes += string_length * 2; + } + + return ret; +} + +//Returns string from string table by ID and language +const std::wstring resource_string_table_reader::get_string_by_id_lang(uint32_t language, uint16_t id) const +{ + //List strings by string table id and language + const resource_string_list strings(get_string_table_by_id_lang(language, (id >> 4) + 1)); + resource_string_list::const_iterator it = strings.find(id); //Find string by id + if(it == strings.end()) + throw pe_exception("Resource string not found", pe_exception::resource_string_not_found); + + return (*it).second; +} + +//Returns string from string table by ID and index in language directory (instead of language) +const std::wstring resource_string_table_reader::get_string_by_id(uint16_t id, uint32_t index) const +{ + //List strings by string table id and index + const resource_string_list strings(get_string_table_by_id((id >> 4) + 1, index)); + resource_string_list::const_iterator it = strings.find(id); //Find string by id + if(it == strings.end()) + throw pe_exception("Resource string not found", pe_exception::resource_string_not_found); + + return (*it).second; +} +} diff --git a/tools/pe_bliss/resource_string_table_reader.h b/tools/pe_bliss/resource_string_table_reader.h new file mode 100644 index 0000000000..e3ded1da85 --- /dev/null +++ b/tools/pe_bliss/resource_string_table_reader.h @@ -0,0 +1,57 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <string> +#include <map> +#include "stdint_defs.h" + +namespace pe_bliss +{ +class pe_resource_viewer; + +//ID; string +typedef std::map<uint16_t, std::wstring> resource_string_list; + +class resource_string_table_reader +{ +public: + resource_string_table_reader(const pe_resource_viewer& res); + +public: + //Returns string table data by ID and language + const resource_string_list get_string_table_by_id_lang(uint32_t language, uint32_t id) const; + //Returns string table data by ID and index in language directory (instead of language) + const resource_string_list get_string_table_by_id(uint32_t id, uint32_t index = 0) const; + //Returns string from string table by ID and language + const std::wstring get_string_by_id_lang(uint32_t language, uint16_t id) const; + //Returns string from string table by ID and index in language directory (instead of language) + const std::wstring get_string_by_id(uint16_t id, uint32_t index = 0) const; + +private: + const pe_resource_viewer& res_; + + //Helper function of parsing string list table + //Id of resource is needed to calculate string IDs correctly + //resource_data is raw string table resource data + static const resource_string_list parse_string_list(uint32_t id, const std::string& resource_data); +}; +} diff --git a/tools/pe_bliss/resource_version_info_reader.cpp b/tools/pe_bliss/resource_version_info_reader.cpp new file mode 100644 index 0000000000..8ad44c6856 --- /dev/null +++ b/tools/pe_bliss/resource_version_info_reader.cpp @@ -0,0 +1,311 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include "resource_version_info_reader.h" +#include "utils.h" +#include "pe_exception.h" +#include "resource_internal.h" +#include "pe_resource_viewer.h" + +namespace pe_bliss +{ +using namespace pe_win; + +//Root version info block key value +const u16string resource_version_info_reader::version_info_key(U16TEXT("V\0S\0_\0V\0E\0R\0S\0I\0O\0N\0_\0I\0N\0F\0O\0\0")); + +resource_version_info_reader::resource_version_info_reader(const pe_resource_viewer& res) + :res_(res) +{} + +//Returns aligned version block value position +uint32_t resource_version_info_reader::get_version_block_value_pos(uint32_t base_pos, const unicode16_t* key) +{ + uint32_t string_length = static_cast<uint32_t>(u16string(key).length()); + uint32_t ret = pe_utils::align_up(static_cast<uint32_t>(sizeof(uint16_t) * 3 /* headers before Key data */ + + base_pos + + (string_length + 1 /* nullbyte */) * 2), + sizeof(uint32_t)); + + //Check possible overflows + if(ret < base_pos || ret < sizeof(uint16_t) * 3 || ret < (string_length + 1) * 2) + throw_incorrect_version_info(); + + return ret; +} + +//Returns aligned version block first child position +uint32_t resource_version_info_reader::get_version_block_first_child_pos(uint32_t base_pos, uint32_t value_length, const unicode16_t* key) +{ + uint32_t string_length = static_cast<uint32_t>(u16string(key).length()); + uint32_t ret = pe_utils::align_up(static_cast<uint32_t>(sizeof(uint16_t) * 3 /* headers before Key data */ + + base_pos + + (string_length + 1 /* nullbyte */) * 2), + sizeof(uint32_t)) + + pe_utils::align_up(value_length, sizeof(uint32_t)); + + //Check possible overflows + if(ret < base_pos || ret < value_length || ret < sizeof(uint16_t) * 3 || ret < (string_length + 1) * 2) + throw_incorrect_version_info(); + + return ret; +} + +//Throws an exception (id = resource_incorrect_version_info) +void resource_version_info_reader::throw_incorrect_version_info() +{ + throw pe_exception("Incorrect resource version info", pe_exception::resource_incorrect_version_info); +} + +//Returns full version information: +//file_version_info: versions and file info +//lang_string_values_map: map of version info strings with encodings +//translation_values_map: map of translations +const file_version_info resource_version_info_reader::get_version_info(lang_string_values_map& string_values, translation_values_map& translations, const std::string& resource_data) const +{ + //Fixed file version info + file_version_info ret; + + //Check resource data length + if(resource_data.length() < sizeof(version_info_block)) + throw_incorrect_version_info(); + + //Root version info block + const version_info_block* root_block = reinterpret_cast<const version_info_block*>(resource_data.data()); + + //Check root block key for null-termination and its name + if(!pe_utils::is_null_terminated(root_block->Key, resource_data.length() - sizeof(uint16_t) * 3 /* headers before Key data */) + || version_info_key != reinterpret_cast<const unicode16_t*>(root_block->Key)) + throw_incorrect_version_info(); + + //If file has fixed version info + if(root_block->ValueLength) + { + //Get root block value position + uint32_t value_pos = get_version_block_value_pos(0, reinterpret_cast<const unicode16_t*>(root_block->Key)); + //Check value length + if(resource_data.length() < value_pos + sizeof(vs_fixedfileinfo)) + throw_incorrect_version_info(); + + //Get VS_FIXEDFILEINFO structure pointer + const vs_fixedfileinfo* file_info = reinterpret_cast<const vs_fixedfileinfo*>(resource_data.data() + value_pos); + //Check its signature and some other fields + if(file_info->dwSignature != vs_ffi_signature || file_info->dwStrucVersion != vs_ffi_strucversion) //Don't check if file_info->dwFileFlagsMask == VS_FFI_FILEFLAGSMASK + throw_incorrect_version_info(); + + //Save fixed version info + ret = file_version_info(*file_info); + } + + //Iterate over child elements of VS_VERSIONINFO (StringFileInfo or VarFileInfo) + for(uint32_t child_pos = get_version_block_first_child_pos(0, root_block->ValueLength, reinterpret_cast<const unicode16_t*>(root_block->Key)); + child_pos < root_block->Length;) + { + //Check block position + if(!pe_utils::is_sum_safe(child_pos, sizeof(version_info_block)) + || resource_data.length() < child_pos + sizeof(version_info_block)) + throw_incorrect_version_info(); + + //Get VERSION_INFO_BLOCK structure pointer + const version_info_block* block = reinterpret_cast<const version_info_block*>(resource_data.data() + child_pos); + + //Check its length + if(block->Length == 0) + throw_incorrect_version_info(); + + //Check block key for null-termination + if(!pe_utils::is_null_terminated(block->Key, resource_data.length() - child_pos - sizeof(uint16_t) * 3 /* headers before Key data */)) + throw_incorrect_version_info(); + + u16string info_type(reinterpret_cast<const unicode16_t*>(block->Key)); + //If we encountered StringFileInfo... + if(info_type == StringFileInfo) + { + //Enumerate all string tables + for(uint32_t string_table_pos = get_version_block_first_child_pos(child_pos, block->ValueLength, reinterpret_cast<const unicode16_t*>(block->Key)); + string_table_pos - child_pos < block->Length;) + { + //Check string table block position + if(resource_data.length() < string_table_pos + sizeof(version_info_block)) + throw_incorrect_version_info(); + + //Get VERSION_INFO_BLOCK structure pointer for string table + const version_info_block* string_table = reinterpret_cast<const version_info_block*>(resource_data.data() + string_table_pos); + + //Check its length + if(string_table->Length == 0) + throw_incorrect_version_info(); + + //Check string table key for null-termination + if(!pe_utils::is_null_terminated(string_table->Key, resource_data.length() - string_table_pos - sizeof(uint16_t) * 3 /* headers before Key data */)) + throw_incorrect_version_info(); + + string_values_map new_values; + + //Enumerate all strings in the string table + for(uint32_t string_pos = get_version_block_first_child_pos(string_table_pos, string_table->ValueLength, reinterpret_cast<const unicode16_t*>(string_table->Key)); + string_pos - string_table_pos < string_table->Length;) + { + //Check string block position + if(resource_data.length() < string_pos + sizeof(version_info_block)) + throw_incorrect_version_info(); + + //Get VERSION_INFO_BLOCK structure pointer for string block + const version_info_block* string_block = reinterpret_cast<const version_info_block*>(resource_data.data() + string_pos); + + //Check its length + if(string_block->Length == 0) + throw_incorrect_version_info(); + + //Check string block key for null-termination + if(!pe_utils::is_null_terminated(string_block->Key, resource_data.length() - string_pos - sizeof(uint16_t) * 3 /* headers before Key data */)) + throw_incorrect_version_info(); + + u16string data; + //If string block has value + if(string_block->ValueLength != 0) + { + //Get value position + uint32_t value_pos = get_version_block_value_pos(string_pos, reinterpret_cast<const unicode16_t*>(string_block->Key)); + //Check it + if(resource_data.length() < value_pos + string_block->ValueLength) + throw pe_exception("Incorrect resource version info", pe_exception::resource_incorrect_version_info); + + //Get UNICODE string value + data = u16string(reinterpret_cast<const unicode16_t*>(resource_data.data() + value_pos), string_block->ValueLength); + pe_utils::strip_nullbytes(data); + } + + //Save name-value pair +#ifdef PE_BLISS_WINDOWS + new_values.insert(std::make_pair(reinterpret_cast<const unicode16_t*>(string_block->Key), data)); +#else + new_values.insert(std::make_pair(pe_utils::from_ucs2(reinterpret_cast<const unicode16_t*>(string_block->Key)), + pe_utils::from_ucs2(data))); +#endif + + //Navigate to next string block + string_pos += pe_utils::align_up(string_block->Length, sizeof(uint32_t)); + } + +#ifdef PE_BLISS_WINDOWS + string_values.insert(std::make_pair(reinterpret_cast<const unicode16_t*>(string_table->Key), new_values)); +#else + string_values.insert(std::make_pair(pe_utils::from_ucs2(reinterpret_cast<const unicode16_t*>(string_table->Key)), new_values)); +#endif + + //Navigate to next string table block + string_table_pos += pe_utils::align_up(string_table->Length, sizeof(uint32_t)); + } + } + else if(info_type == VarFileInfo) //If we encountered VarFileInfo + { + for(uint32_t var_table_pos = get_version_block_first_child_pos(child_pos, block->ValueLength, reinterpret_cast<const unicode16_t*>(block->Key)); + var_table_pos - child_pos < block->Length;) + { + //Check var block position + if(resource_data.length() < var_table_pos + sizeof(version_info_block)) + throw_incorrect_version_info(); + + //Get VERSION_INFO_BLOCK structure pointer for var block + const version_info_block* var_table = reinterpret_cast<const version_info_block*>(resource_data.data() + var_table_pos); + + //Check its length + if(var_table->Length == 0) + throw_incorrect_version_info(); + + //Check its key for null-termination + if(!pe_utils::is_null_terminated(var_table->Key, resource_data.length() - var_table_pos - sizeof(uint16_t) * 3 /* headers before Key data */)) + throw_incorrect_version_info(); + + //If block is "Translation" (actually, there's no other types possible in VarFileInfo) and it has value + if(u16string(reinterpret_cast<const unicode16_t*>(var_table->Key)) == Translation && var_table->ValueLength) + { + //Get its value position + uint32_t value_pos = get_version_block_value_pos(var_table_pos, reinterpret_cast<const unicode16_t*>(var_table->Key)); + //Cherck value length + if(resource_data.length() < value_pos + var_table->ValueLength) + throw_incorrect_version_info(); + + //Get list of translations: pairs of LANGUAGE_ID - CODEPAGE_ID + for(unsigned long i = 0; i < var_table->ValueLength; i += sizeof(uint16_t) * 2) + { + //Pair of WORDs + uint16_t lang_id = *reinterpret_cast<const uint16_t*>(resource_data.data() + value_pos + i); + uint16_t codepage_id = *reinterpret_cast<const uint16_t*>(resource_data.data() + value_pos + sizeof(uint16_t) + i); + //Save translation + translations.insert(std::make_pair(lang_id, codepage_id)); + } + } + + //Navigate to next var block + var_table_pos += pe_utils::align_up(var_table->Length, sizeof(uint32_t)); + } + } + else + { + throw_incorrect_version_info(); + } + + //Navigate to next element in root block + child_pos += pe_utils::align_up(block->Length, sizeof(uint32_t)); + } + + return ret; +} + +//Returns full version information: +//file_version info: versions and file info +//lang_string_values_map: map of version info strings with encodings +//translation_values_map: map of translations +const file_version_info resource_version_info_reader::get_version_info_by_lang(lang_string_values_map& string_values, translation_values_map& translations, uint32_t language) const +{ + const std::string& resource_data = res_.get_root_directory() //Type directory + .entry_by_id(pe_resource_viewer::resource_version) + .get_resource_directory() //Name/ID directory + .entry_by_id(1) + .get_resource_directory() //Language directory + .entry_by_id(language) + .get_data_entry() //Data directory + .get_data(); + + return get_version_info(string_values, translations, resource_data); +} + +//Returns full version information: +//file_version_info: versions and file info +//lang_string_values_map: map of version info strings with encodings +//translation_values_map: map of translations +const file_version_info resource_version_info_reader::get_version_info(lang_string_values_map& string_values, translation_values_map& translations, uint32_t index) const +{ + const resource_directory::entry_list& entries = res_.get_root_directory() //Type directory + .entry_by_id(pe_resource_viewer::resource_version) + .get_resource_directory() //Name/ID directory + .entry_by_id(1) + .get_resource_directory() //Language directory + .get_entry_list(); + + if(entries.size() <= index) + throw pe_exception("Resource data entry not found", pe_exception::resource_data_entry_not_found); + + return get_version_info(string_values, translations, entries.at(index).get_data_entry().get_data()); //Data directory +} +} diff --git a/tools/pe_bliss/resource_version_info_reader.h b/tools/pe_bliss/resource_version_info_reader.h new file mode 100644 index 0000000000..c1dfbffdc2 --- /dev/null +++ b/tools/pe_bliss/resource_version_info_reader.h @@ -0,0 +1,67 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <map> +#include "file_version_info.h" +#include "pe_structures.h" +#include "version_info_types.h" + +namespace pe_bliss +{ +class pe_resource_viewer; + +class resource_version_info_reader +{ +public: //VERSION INFO + resource_version_info_reader(const pe_resource_viewer& res); + + //Returns full version information: + //file_version_info: versions and file info + //lang_lang_string_values_map: map of version info strings with encodings with encodings + //translation_values_map: map of translations + const file_version_info get_version_info(lang_string_values_map& string_values, translation_values_map& translations, uint32_t index = 0) const; + const file_version_info get_version_info_by_lang(lang_string_values_map& string_values, translation_values_map& translations, uint32_t language) const; + +public: + //L"VS_VERSION_INFO" key of root version info block + static const u16string version_info_key; + +private: + const pe_resource_viewer& res_; + + //VERSION INFO helpers + //Returns aligned version block value position + static uint32_t get_version_block_value_pos(uint32_t base_pos, const unicode16_t* key); + + //Returns aligned version block first child position + static uint32_t get_version_block_first_child_pos(uint32_t base_pos, uint32_t value_length, const unicode16_t* key); + + //Returns full version information: + //file_version_info: versions and file info + //lang_string_values_map: map of version info strings with encodings + //translation_values_map: map of translations + const file_version_info get_version_info(lang_string_values_map& string_values, translation_values_map& translations, const std::string& resource_data) const; + + //Throws an exception (id = resource_incorrect_version_info) + static void throw_incorrect_version_info(); +}; +} diff --git a/tools/pe_bliss/resource_version_info_writer.cpp b/tools/pe_bliss/resource_version_info_writer.cpp new file mode 100644 index 0000000000..ed95a0f7ea --- /dev/null +++ b/tools/pe_bliss/resource_version_info_writer.cpp @@ -0,0 +1,283 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <string.h> +#include "resource_version_info_writer.h" +#include "pe_structures.h" +#include "resource_internal.h" +#include "utils.h" +#include "pe_resource_manager.h" +#include "resource_version_info_reader.h" + +namespace pe_bliss +{ +using namespace pe_win; + +resource_version_info_writer::resource_version_info_writer(pe_resource_manager& res) + :res_(res) +{} + +//Sets/replaces full version information: +//file_version_info: versions and file info +//lang_string_values_map: map of version info strings with encodings +//translation_values_map: map of translations +void resource_version_info_writer::set_version_info(const file_version_info& file_info, + const lang_string_values_map& string_values, + const translation_values_map& translations, + uint32_t language, + uint32_t codepage, + uint32_t timestamp) +{ + std::string version_data; + + //Calculate total size of version resource data + uint32_t total_version_info_length = + static_cast<uint32_t>(sizeof(version_info_block) - sizeof(uint16_t) + sizeof(uint16_t) /* pading */ + + (resource_version_info_reader::version_info_key.length() + 1) * 2 + + sizeof(vs_fixedfileinfo)); + + //If we have any strings values + if(!string_values.empty()) + { + total_version_info_length += sizeof(version_info_block) - sizeof(uint16_t); //StringFileInfo block + total_version_info_length += SizeofStringFileInfo; //Name of block (key) + + //Add required size for version strings + for(lang_string_values_map::const_iterator table_it = string_values.begin(); table_it != string_values.end(); ++table_it) + { + total_version_info_length += pe_utils::align_up(static_cast<uint32_t>(sizeof(uint16_t) * 3 + ((*table_it).first.length() + 1) * 2), sizeof(uint32_t)); //Name of child block and block size (key of string table block) + + const string_values_map& values = (*table_it).second; + for(string_values_map::const_iterator it = values.begin(); it != values.end(); ++it) + { + total_version_info_length += pe_utils::align_up(static_cast<uint32_t>(sizeof(uint16_t) * 3 + ((*it).first.length() + 1) * 2), sizeof(uint32_t)); + total_version_info_length += pe_utils::align_up(static_cast<uint32_t>(((*it).second.length() + 1) * 2), sizeof(uint32_t)); + } + } + } + + //If we have translations + if(!translations.empty()) + { + total_version_info_length += (sizeof(version_info_block) - sizeof(uint16_t)) * 2; //VarFileInfo and Translation blocks + total_version_info_length += SizeofVarFileInfoAligned; //DWORD-aligned VarFileInfo block name + total_version_info_length += SizeofTranslationAligned; //DWORD-aligned Translation block name + total_version_info_length += static_cast<uint32_t>(translations.size() * sizeof(uint16_t) * 2); + } + + //Resize version data buffer + version_data.resize(total_version_info_length); + + //Create root version block + version_info_block root_block = {0}; + root_block.ValueLength = sizeof(vs_fixedfileinfo); + root_block.Length = static_cast<uint16_t>(total_version_info_length); + + //Fill fixed file info + vs_fixedfileinfo fixed_info = {0}; + fixed_info.dwFileDateLS = file_info.get_file_date_ls(); + fixed_info.dwFileDateMS = file_info.get_file_date_ms(); + fixed_info.dwFileFlags = file_info.get_file_flags(); + fixed_info.dwFileFlagsMask = vs_ffi_fileflagsmask; + fixed_info.dwFileOS = file_info.get_file_os_raw(); + fixed_info.dwFileSubtype = file_info.get_file_subtype(); + fixed_info.dwFileType = file_info.get_file_type_raw(); + fixed_info.dwFileVersionLS = file_info.get_file_version_ls(); + fixed_info.dwFileVersionMS = file_info.get_file_version_ms(); + fixed_info.dwSignature = vs_ffi_signature; + fixed_info.dwStrucVersion = vs_ffi_strucversion; + fixed_info.dwProductVersionLS = file_info.get_product_version_ls(); + fixed_info.dwProductVersionMS = file_info.get_product_version_ms(); + + //Write root block and fixed file info to buffer + uint32_t data_ptr = 0; + memcpy(&version_data[data_ptr], &root_block, sizeof(version_info_block) - sizeof(uint16_t)); + data_ptr += sizeof(version_info_block) - sizeof(uint16_t); + memcpy(&version_data[data_ptr], resource_version_info_reader::version_info_key.c_str(), (resource_version_info_reader::version_info_key.length() + 1) * sizeof(uint16_t)); + data_ptr += static_cast<uint32_t>((resource_version_info_reader::version_info_key.length() + 1) * sizeof(uint16_t)); + memset(&version_data[data_ptr], 0, sizeof(uint16_t)); + data_ptr += sizeof(uint16_t); + memcpy(&version_data[data_ptr], &fixed_info, sizeof(fixed_info)); + data_ptr += sizeof(fixed_info); + + //Write string values, if any + if(!string_values.empty()) + { + //Create string file info root block + version_info_block string_file_info_block = {0}; + string_file_info_block.Type = 1; //Block type is string + memcpy(&version_data[data_ptr], &string_file_info_block, sizeof(version_info_block) - sizeof(uint16_t)); + //We will calculate its length later + version_info_block* string_file_info_block_ptr = reinterpret_cast<version_info_block*>(&version_data[data_ptr]); + data_ptr += sizeof(version_info_block) - sizeof(uint16_t); + + uint32_t old_ptr1 = data_ptr; //Used to calculate string file info block length later + memcpy(&version_data[data_ptr], StringFileInfo, SizeofStringFileInfo); //Write block name + data_ptr += SizeofStringFileInfo; + + //Create string table root block (child of string file info) + version_info_block string_table_block = {0}; + string_table_block.Type = 1; //Block type is string + + for(lang_string_values_map::const_iterator table_it = string_values.begin(); table_it != string_values.end(); ++table_it) + { + const string_values_map& values = (*table_it).second; + + memcpy(&version_data[data_ptr], &string_table_block, sizeof(version_info_block) - sizeof(uint16_t)); + //We will calculate its length later + version_info_block* string_table_block_ptr = reinterpret_cast<version_info_block*>(&version_data[data_ptr]); + data_ptr += sizeof(version_info_block) - sizeof(uint16_t); + + uint32_t old_ptr2 = data_ptr; //Used to calculate string table block length later + uint32_t lang_key_length = static_cast<uint32_t>(((*table_it).first.length() + 1) * sizeof(uint16_t)); + +#ifdef PE_BLISS_WINDOWS + memcpy(&version_data[data_ptr], (*table_it).first.c_str(), lang_key_length); //Write block key +#else + { + u16string str(pe_utils::to_ucs2((*table_it).first)); + memcpy(&version_data[data_ptr], str.c_str(), lang_key_length); //Write block key + } +#endif + + data_ptr += lang_key_length; + //Align key if necessary + if((sizeof(uint16_t) * 3 + lang_key_length) % sizeof(uint32_t)) + { + memset(&version_data[data_ptr], 0, sizeof(uint16_t)); + data_ptr += sizeof(uint16_t); + } + + //Create string block (child of string table block) + version_info_block string_block = {0}; + string_block.Type = 1; //Block type is string + for(string_values_map::const_iterator it = values.begin(); it != values.end(); ++it) + { + //Calculate value length and key length of string block + string_block.ValueLength = static_cast<uint16_t>((*it).second.length() + 1); + uint32_t key_length = static_cast<uint32_t>(((*it).first.length() + 1) * sizeof(uint16_t)); + //Calculate length of block + string_block.Length = static_cast<uint16_t>(pe_utils::align_up(sizeof(uint16_t) * 3 + key_length, sizeof(uint32_t)) + string_block.ValueLength * sizeof(uint16_t)); + + //Write string block + memcpy(&version_data[data_ptr], &string_block, sizeof(version_info_block) - sizeof(uint16_t)); + data_ptr += sizeof(version_info_block) - sizeof(uint16_t); + +#ifdef PE_BLISS_WINDOWS + memcpy(&version_data[data_ptr], (*it).first.c_str(), key_length); //Write block key +#else + { + u16string str(pe_utils::to_ucs2((*it).first)); + memcpy(&version_data[data_ptr], str.c_str(), key_length); //Write block key + } +#endif + + data_ptr += key_length; + //Align key if necessary + if((sizeof(uint16_t) * 3 + key_length) % sizeof(uint32_t)) + { + memset(&version_data[data_ptr], 0, sizeof(uint16_t)); + data_ptr += sizeof(uint16_t); + } + + //Write block data (value) +#ifdef PE_BLISS_WINDOWS + memcpy(&version_data[data_ptr], (*it).second.c_str(), string_block.ValueLength * sizeof(uint16_t)); +#else + { + u16string str(pe_utils::to_ucs2((*it).second)); + memcpy(&version_data[data_ptr], str.c_str(), string_block.ValueLength * sizeof(uint16_t)); + } +#endif + + data_ptr += string_block.ValueLength * 2; + //Align data if necessary + if((string_block.ValueLength * 2) % sizeof(uint32_t)) + { + memset(&version_data[data_ptr], 0, sizeof(uint16_t)); + data_ptr += sizeof(uint16_t); + } + } + + //Calculate string table and string file info blocks lengths + string_table_block_ptr->Length = static_cast<uint16_t>(data_ptr - old_ptr2 + sizeof(uint16_t) * 3); + } + + string_file_info_block_ptr->Length = static_cast<uint16_t>(data_ptr - old_ptr1 + sizeof(uint16_t) * 3); + } + + //If we have transactions + if(!translations.empty()) + { + //Create root var file info block + version_info_block var_file_info_block = {0}; + var_file_info_block.Type = 1; //Type of block is string + //Write block header + memcpy(&version_data[data_ptr], &var_file_info_block, sizeof(version_info_block) - sizeof(uint16_t)); + //We will calculate its length later + version_info_block* var_file_info_block_ptr = reinterpret_cast<version_info_block*>(&version_data[data_ptr]); + data_ptr += sizeof(version_info_block) - sizeof(uint16_t); + + uint32_t old_ptr1 = data_ptr; //Used to calculate var file info block length later + memcpy(&version_data[data_ptr], VarFileInfoAligned, SizeofVarFileInfoAligned); //Write block key (aligned) + data_ptr += SizeofVarFileInfoAligned; + + //Create root translation block (child of var file info block) + version_info_block translation_block = {0}; + //Write block header + memcpy(&version_data[data_ptr], &translation_block, sizeof(version_info_block) - sizeof(uint16_t)); + //We will calculate its length later + version_info_block* translation_block_ptr = reinterpret_cast<version_info_block*>(&version_data[data_ptr]); + data_ptr += sizeof(version_info_block) - sizeof(uint16_t); + + uint32_t old_ptr2 = data_ptr; //Used to calculate var file info block length later + memcpy(&version_data[data_ptr], TranslationAligned, SizeofTranslationAligned); //Write block key (aligned) + data_ptr += SizeofTranslationAligned; + + //Calculate translation block value length + translation_block_ptr->ValueLength = static_cast<uint16_t>(sizeof(uint16_t) * 2 * translations.size()); + + //Write translation values to block + for(translation_values_map::const_iterator it = translations.begin(); it != translations.end(); ++it) + { + uint16_t lang_id = (*it).first; //Language ID + uint16_t codepage_id = (*it).second; //Codepage ID + memcpy(&version_data[data_ptr], &lang_id, sizeof(lang_id)); + data_ptr += sizeof(lang_id); + memcpy(&version_data[data_ptr], &codepage_id, sizeof(codepage_id)); + data_ptr += sizeof(codepage_id); + } + + //Calculate Translation and VarFileInfo blocks lengths + translation_block_ptr->Length = static_cast<uint16_t>(data_ptr - old_ptr2 + sizeof(uint16_t) * 3); + var_file_info_block_ptr->Length = static_cast<uint16_t>(data_ptr - old_ptr1 + sizeof(uint16_t) * 3); + } + + //Add/replace version info resource + res_.add_resource(version_data, pe_resource_viewer::resource_version, 1, language, codepage, timestamp); +} + +//Removes version info by language (ID = 1) +bool resource_version_info_writer::remove_version_info(uint32_t language) +{ + return res_.remove_resource(pe_resource_viewer::resource_version, 1, language); +} +} diff --git a/tools/pe_bliss/resource_version_info_writer.h b/tools/pe_bliss/resource_version_info_writer.h new file mode 100644 index 0000000000..da279ddedb --- /dev/null +++ b/tools/pe_bliss/resource_version_info_writer.h @@ -0,0 +1,52 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include "version_info_types.h" +#include "file_version_info.h" + +namespace pe_bliss +{ +class pe_resource_manager; + +class resource_version_info_writer +{ +public: + resource_version_info_writer(pe_resource_manager& res); + + //Sets/replaces full version information: + //file_version_info: versions and file info + //lang_string_values_map: map of version info strings with encodings + //translation_values_map: map of translations + void set_version_info(const file_version_info& file_info, + const lang_string_values_map& string_values, + const translation_values_map& translations, + uint32_t language, + uint32_t codepage = 0, + uint32_t timestamp = 0); + + //Removes version info by language (ID = 1) + bool remove_version_info(uint32_t language); + +private: + pe_resource_manager& res_; +}; +} diff --git a/tools/pe_bliss/stdint_defs.h b/tools/pe_bliss/stdint_defs.h new file mode 100644 index 0000000000..bbc003690a --- /dev/null +++ b/tools/pe_bliss/stdint_defs.h @@ -0,0 +1,45 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#ifdef _MSC_VER +#if _MSC_VER < 1600 +namespace pe_bliss +{ + //stdint.h definitions for MSVC 2008 and earlier, as + //it doesn't have them + typedef signed char int8_t; + typedef short int16_t; + typedef int int32_t; + + typedef unsigned char uint8_t; + typedef unsigned short uint16_t; + typedef unsigned int uint32_t; + + typedef long long int64_t; + typedef unsigned long long uint64_t; +} +#else +#include <stdint.h> +#endif +#else +#include <stdint.h> +#endif diff --git a/tools/pe_bliss/utils.cpp b/tools/pe_bliss/utils.cpp new file mode 100644 index 0000000000..e6a75d5497 --- /dev/null +++ b/tools/pe_bliss/utils.cpp @@ -0,0 +1,85 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <string.h> +#include "utils.h" +#include "pe_exception.h" + + +namespace pe_bliss +{ +const double pe_utils::log_2 = 1.44269504088896340736; //instead of using M_LOG2E + +//Returns stream size +std::streamoff pe_utils::get_file_size(std::istream& file) +{ + //Get old istream offset + std::streamoff old_offset = file.tellg(); + file.seekg(0, std::ios::end); + std::streamoff filesize = file.tellg(); + //Set old istream offset + file.seekg(old_offset); + return filesize; +} + +#ifndef PE_BLISS_WINDOWS +const u16string pe_utils::to_ucs2(const std::wstring& str) +{ + u16string ret; + if(str.empty()) + return ret; + + int len = str.length(); + + ret.resize(len); + + for(int i=0;i<len;i++) { + ret[i]=str[i]&0xFFFF; + } + + return ret; +} + +const std::wstring pe_utils::from_ucs2(const u16string& str) +{ + std::wstring ret; + if(str.empty()) + return ret; + + int len = str.length(); + ret.resize(str.length()); + + for(int i=0;i<len;i++) { + ret[i]=str[i]; + } + + return ret; +} +#endif + +bool operator==(const pe_win::guid& guid1, const pe_win::guid& guid2) +{ + return guid1.Data1 == guid2.Data1 + && guid1.Data2 == guid2.Data2 + && guid1.Data3 == guid2.Data3 + && !memcmp(guid1.Data4, guid2.Data4, sizeof(guid1.Data4)); +} +} diff --git a/tools/pe_bliss/utils.h b/tools/pe_bliss/utils.h new file mode 100644 index 0000000000..29125f8dc1 --- /dev/null +++ b/tools/pe_bliss/utils.h @@ -0,0 +1,105 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <istream> +#include <string> +#include "stdint_defs.h" +#include "pe_structures.h" + +namespace pe_bliss +{ +class pe_utils +{ +public: + //Returns true if string "data" with maximum length "raw_length" is null-terminated + template<typename T> + static bool is_null_terminated(const T* data, size_t raw_length) + { + raw_length /= sizeof(T); + for(size_t l = 0; l < raw_length; l++) + { + if(data[l] == static_cast<T>(L'\0')) + return true; + } + + return false; + } + + //Helper template function to strip nullbytes in the end of string + template<typename T> + static void strip_nullbytes(std::basic_string<T>& str) + { + while(!*(str.end() - 1) && !str.empty()) + str.erase(str.length() - 1); + } + + //Helper function to determine if number is power of 2 + template<typename T> + static inline bool is_power_of_2(T x) + { + return !(x & (x - 1)); + } + + //Helper function to align number down + template<typename T> + static inline T align_down(T x, uint32_t align) + { + return x & ~(static_cast<T>(align) - 1); + } + + //Helper function to align number up + template<typename T> + static inline T align_up(T x, uint32_t align) + { + return (x & static_cast<T>(align - 1)) ? align_down(x, align) + static_cast<T>(align) : x; + } + + //Returns true if sum of two unsigned integers is safe (no overflow occurs) + static inline bool is_sum_safe(uint32_t a, uint32_t b) + { + return a <= static_cast<uint32_t>(-1) - b; + } + + //Two gigabytes value in bytes + static const uint32_t two_gb = 0x80000000; + static const uint32_t max_dword = 0xFFFFFFFF; + static const uint32_t max_word = 0x0000FFFF; + static const double log_2; //instead of using M_LOG2E + + //Returns stream size + static std::streamoff get_file_size(std::istream& file); + +#ifndef PE_BLISS_WINDOWS +public: + static const u16string to_ucs2(const std::wstring& str); + static const std::wstring from_ucs2(const u16string& str); +#endif + +private: + pe_utils(); + pe_utils(pe_utils&); + pe_utils& operator=(const pe_utils&); +}; + +//Windows GUID comparison +bool operator==(const pe_win::guid& guid1, const pe_win::guid& guid2); +} diff --git a/tools/pe_bliss/version_info_editor.cpp b/tools/pe_bliss/version_info_editor.cpp new file mode 100644 index 0000000000..199eebfd54 --- /dev/null +++ b/tools/pe_bliss/version_info_editor.cpp @@ -0,0 +1,184 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <sstream> +#include <iomanip> +#include "version_info_types.h" +#include "version_info_editor.h" +#include "version_info_viewer.h" + +namespace pe_bliss +{ +//Default constructor +//strings - version info strings with charsets +//translations - version info translations map +version_info_editor::version_info_editor(lang_string_values_map& strings, translation_values_map& translations) + :version_info_viewer(strings, translations), + strings_edit_(strings), + translations_edit_(translations) +{} + +//Below functions have parameter translation +//If it's empty, the default language translation will be taken +//If there's no default language translation, the first one will be taken + +//Sets company name +void version_info_editor::set_company_name(const std::wstring& value, const std::wstring& translation) +{ + set_property(L"CompanyName", value, translation); +} + +//Sets file description +void version_info_editor::set_file_description(const std::wstring& value, const std::wstring& translation) +{ + set_property(L"FileDescription", value, translation); +} + +//Sets file version +void version_info_editor::set_file_version(const std::wstring& value, const std::wstring& translation) +{ + set_property(L"FileVersion", value, translation); +} + +//Sets internal file name +void version_info_editor::set_internal_name(const std::wstring& value, const std::wstring& translation) +{ + set_property(L"InternalName", value, translation); +} + +//Sets legal copyright +void version_info_editor::set_legal_copyright(const std::wstring& value, const std::wstring& translation) +{ + set_property(L"LegalCopyright", value, translation); +} + +//Sets original file name +void version_info_editor::set_original_filename(const std::wstring& value, const std::wstring& translation) +{ + set_property(L"OriginalFilename", value, translation); +} + +//Sets product name +void version_info_editor::set_product_name(const std::wstring& value, const std::wstring& translation) +{ + set_property(L"ProductName", value, translation); +} + +//Sets product version +void version_info_editor::set_product_version(const std::wstring& value, const std::wstring& translation) +{ + set_property(L"ProductVersion", value, translation); +} + +//Sets version info property value +//property_name - property name +//value - property value +//If translation does not exist, it will be added +//If property does not exist, it will be added +void version_info_editor::set_property(const std::wstring& property_name, const std::wstring& value, const std::wstring& translation) +{ + lang_string_values_map::iterator it = strings_edit_.begin(); + + if(translation.empty()) + { + //If no translation was specified + it = strings_edit_.find(default_language_translation); //Find default translation table + if(it == strings_edit_.end()) //If there's no default translation table, take the first one + { + it = strings_edit_.begin(); + if(it == strings_edit_.end()) //If there's no any translation table, add default one + { + it = strings_edit_.insert(std::make_pair(default_language_translation, string_values_map())).first; + //Also add it to translations list + add_translation(default_language_translation); + } + } + } + else + { + it = strings_edit_.find(translation); //Find specified translation table + if(it == strings_edit_.end()) //If there's no translation, add it + { + it = strings_edit_.insert(std::make_pair(translation, string_values_map())).first; + //Also add it to translations list + add_translation(translation); + } + } + + //Change value of the required property + ((*it).second)[property_name] = value; +} + +//Adds translation to translation list +void version_info_editor::add_translation(const std::wstring& translation) +{ + std::pair<uint16_t, uint16_t> translation_ids(translation_from_string(translation)); + add_translation(translation_ids.first, translation_ids.second); +} + +void version_info_editor::add_translation(uint16_t language_id, uint16_t codepage_id) +{ + std::pair<translation_values_map::const_iterator, translation_values_map::const_iterator> + range(translations_edit_.equal_range(language_id)); + + //If translation already exists + for(translation_values_map::const_iterator it = range.first; it != range.second; ++it) + { + if((*it).second == codepage_id) + return; + } + + translations_edit_.insert(std::make_pair(language_id, codepage_id)); +} + +//Removes translation from translations and strings lists +void version_info_editor::remove_translation(const std::wstring& translation) +{ + std::pair<uint16_t, uint16_t> translation_ids(translation_from_string(translation)); + remove_translation(translation_ids.first, translation_ids.second); +} + +void version_info_editor::remove_translation(uint16_t language_id, uint16_t codepage_id) +{ + { + //Erase string table (if exists) + std::wstringstream ss; + ss << std::hex + << std::setw(4) << std::setfill(L'0') << language_id + << std::setw(4) << std::setfill(L'0') << codepage_id; + + strings_edit_.erase(ss.str()); + } + + //Find and erase translation from translations table + std::pair<translation_values_map::iterator, translation_values_map::iterator> + it_pair = translations_edit_.equal_range(language_id); + + for(translation_values_map::iterator it = it_pair.first; it != it_pair.second; ++it) + { + if((*it).second == codepage_id) + { + translations_edit_.erase(it); + break; + } + } +} +} diff --git a/tools/pe_bliss/version_info_editor.h b/tools/pe_bliss/version_info_editor.h new file mode 100644 index 0000000000..53d3dc62c1 --- /dev/null +++ b/tools/pe_bliss/version_info_editor.h @@ -0,0 +1,79 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include "version_info_types.h" +#include "version_info_viewer.h" + +namespace pe_bliss +{ + //Helper class to read and edit version information + //lang_string_values_map: map of version info strings with encodings + //translation_values_map: map of translations + class version_info_editor : public version_info_viewer + { + public: + //Default constructor + //strings - version info strings with charsets + //translations - version info translations map + version_info_editor(lang_string_values_map& strings, translation_values_map& translations); + + //Below functions have parameter translation + //If it's empty, the default language translation will be taken + //If there's no default language translation, the first one will be taken + + //Sets company name + void set_company_name(const std::wstring& value, const std::wstring& translation = std::wstring()); + //Sets file description + void set_file_description(const std::wstring& value, const std::wstring& translation = std::wstring()); + //Sets file version + void set_file_version(const std::wstring& value, const std::wstring& translation = std::wstring()); + //Sets internal file name + void set_internal_name(const std::wstring& value, const std::wstring& translation = std::wstring()); + //Sets legal copyright + void set_legal_copyright(const std::wstring& value, const std::wstring& translation = std::wstring()); + //Sets original file name + void set_original_filename(const std::wstring& value, const std::wstring& translation = std::wstring()); + //Sets product name + void set_product_name(const std::wstring& value, const std::wstring& translation = std::wstring()); + //Sets product version + void set_product_version(const std::wstring& value, const std::wstring& translation = std::wstring()); + + //Sets version info property value + //property_name - property name + //value - property value + //If translation does not exist, it will be added to strings and translations lists + //If property does not exist, it will be added + void set_property(const std::wstring& property_name, const std::wstring& value, const std::wstring& translation = std::wstring()); + + //Adds translation to translation list + void add_translation(const std::wstring& translation); + void add_translation(uint16_t language_id, uint16_t codepage_id); + + //Removes translation from translations and strings lists + void remove_translation(const std::wstring& translation); + void remove_translation(uint16_t language_id, uint16_t codepage_id); + + private: + lang_string_values_map& strings_edit_; + translation_values_map& translations_edit_; + }; +} diff --git a/tools/pe_bliss/version_info_types.h b/tools/pe_bliss/version_info_types.h new file mode 100644 index 0000000000..6010c9691e --- /dev/null +++ b/tools/pe_bliss/version_info_types.h @@ -0,0 +1,38 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <map> +#include <string> +#include "stdint_defs.h" + +namespace pe_bliss +{ + //Typedef for version info functions: Name - Value + typedef std::map<std::wstring, std::wstring> string_values_map; + //Typedef for version info functions: Language string - String Values Map + //Language String consists of LangID and CharsetID + //E.g. 041904b0 for Russian UNICODE, 040004b0 for Process Default Language UNICODE + typedef std::map<std::wstring, string_values_map> lang_string_values_map; + + //Typedef for version info functions: Language - Character Set + typedef std::multimap<uint16_t, uint16_t> translation_values_map; +} diff --git a/tools/pe_bliss/version_info_viewer.cpp b/tools/pe_bliss/version_info_viewer.cpp new file mode 100644 index 0000000000..6e2d0d5c5b --- /dev/null +++ b/tools/pe_bliss/version_info_viewer.cpp @@ -0,0 +1,180 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#include <iomanip> +#include <sstream> +#include "pe_exception.h" +#include "version_info_viewer.h" + +namespace pe_bliss +{ +//Default process language, UNICODE +const std::wstring version_info_viewer::default_language_translation(L"040904b0"); + +//Default constructor +//strings - version info strings with charsets +//translations - version info translations map +version_info_viewer::version_info_viewer(const lang_string_values_map& strings, const translation_values_map& translations) + :strings_(strings), translations_(translations) +{} + +//Below functions have parameter translation +//If it's empty, the default language translation will be taken +//If there's no default language translation, the first one will be taken + +//Returns company name +const std::wstring version_info_viewer::get_company_name(const std::wstring& translation) const +{ + return get_property(L"CompanyName", translation); +} + +//Returns file description +const std::wstring version_info_viewer::get_file_description(const std::wstring& translation) const +{ + return get_property(L"FileDescription", translation); +} + +//Returns file version +const std::wstring version_info_viewer::get_file_version(const std::wstring& translation) const +{ + return get_property(L"FileVersion", translation); +} + +//Returns internal file name +const std::wstring version_info_viewer::get_internal_name(const std::wstring& translation) const +{ + return get_property(L"InternalName", translation); +} + +//Returns legal copyright +const std::wstring version_info_viewer::get_legal_copyright(const std::wstring& translation) const +{ + return get_property(L"LegalCopyright", translation); +} + +//Returns original file name +const std::wstring version_info_viewer::get_original_filename(const std::wstring& translation) const +{ + return get_property(L"OriginalFilename", translation); +} + +//Returns product name +const std::wstring version_info_viewer::get_product_name(const std::wstring& translation) const +{ + return get_property(L"ProductName", translation); +} + +//Returns product version +const std::wstring version_info_viewer::get_product_version(const std::wstring& translation) const +{ + return get_property(L"ProductVersion", translation); +} + +//Returns list of translations in string representation +const version_info_viewer::translation_list version_info_viewer::get_translation_list() const +{ + translation_list ret; + + //Enumerate all translations + for(translation_values_map::const_iterator it = translations_.begin(); it != translations_.end(); ++it) + { + //Create string representation of translation value + std::wstringstream ss; + ss << std::hex + << std::setw(4) << std::setfill(L'0') << (*it).first + << std::setw(4) << std::setfill(L'0') << (*it).second; + + //Save it + ret.push_back(ss.str()); + } + + return ret; +} + +//Returns version info property value +//property_name - required property name +//If throw_if_absent = true, will throw exception if property does not exist +//If throw_if_absent = false, will return empty string if property does not exist +const std::wstring version_info_viewer::get_property(const std::wstring& property_name, const std::wstring& translation, bool throw_if_absent) const +{ + std::wstring ret; + + //If there're no strings + if(strings_.empty()) + { + if(throw_if_absent) + throw pe_exception("Version info string does not exist", pe_exception::version_info_string_does_not_exist); + + return ret; + } + + lang_string_values_map::const_iterator it = strings_.begin(); + + if(translation.empty()) + { + //If no translation was specified + it = strings_.find(default_language_translation); //Find default translation table + if(it == strings_.end()) //If there's no default translation table, take the first one + it = strings_.begin(); + } + else + { + it = strings_.find(translation); //Find specified translation table + if(it == strings_.end()) + { + if(throw_if_absent) + throw pe_exception("Version info string does not exist", pe_exception::version_info_string_does_not_exist); + + return ret; + } + } + + //Find value of the required property + string_values_map::const_iterator str_it = (*it).second.find(property_name); + + if(str_it == (*it).second.end()) + { + if(throw_if_absent) + throw pe_exception("Version info string does not exist", pe_exception::version_info_string_does_not_exist); + + return ret; + } + + ret = (*str_it).second; + + return ret; +} + +//Converts translation HEX-string to pair of language ID and codepage ID +const version_info_viewer::translation_pair version_info_viewer::translation_from_string(const std::wstring& translation) +{ + uint32_t translation_id = 0; + + { + //Convert string to DWORD + std::wstringstream ss; + ss << std::hex << translation; + ss >> translation_id; + } + + return std::make_pair(static_cast<uint16_t>(translation_id >> 16), static_cast<uint16_t>(translation_id & 0xFFFF)); +} +} diff --git a/tools/pe_bliss/version_info_viewer.h b/tools/pe_bliss/version_info_viewer.h new file mode 100644 index 0000000000..bc2f6f2ba7 --- /dev/null +++ b/tools/pe_bliss/version_info_viewer.h @@ -0,0 +1,89 @@ +/*************************************************************************/ +/* Copyright (c) 2015 dx, http://kaimi.ru */ +/* */ +/* Permission is hereby granted, free of charge, to any person */ +/* obtaining a copy of this software and associated documentation */ +/* files (the "Software"), to deal in the Software without */ +/* restriction, including without limitation the rights to use, */ +/* copy, modify, merge, publish, distribute, sublicense, and/or */ +/* sell copies of the Software, and to permit persons to whom the */ +/* Software is furnished to do so, subject to the following conditions: */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ +#pragma once +#include <map> +#include <vector> +#include <string> +#include "pe_resource_viewer.h" +#include "pe_structures.h" +#include "version_info_types.h" + +namespace pe_bliss +{ +//Helper class to read version information +//lang_string_values_map: map of version info strings with encodings +//translation_values_map: map of translations +class version_info_viewer +{ +public: + //Useful typedefs + typedef std::pair<uint16_t, uint16_t> translation_pair; + typedef std::vector<std::wstring> translation_list; + +public: + //Default constructor + //strings - version info strings with charsets + //translations - version info translations map + version_info_viewer(const lang_string_values_map& strings, const translation_values_map& translations); + + //Below functions have parameter translation + //If it's empty, the default language translation will be taken + //If there's no default language translation, the first one will be taken + + //Returns company name + const std::wstring get_company_name(const std::wstring& translation = std::wstring()) const; + //Returns file description + const std::wstring get_file_description(const std::wstring& translation = std::wstring()) const; + //Returns file version + const std::wstring get_file_version(const std::wstring& translation = std::wstring()) const; + //Returns internal file name + const std::wstring get_internal_name(const std::wstring& translation = std::wstring()) const; + //Returns legal copyright + const std::wstring get_legal_copyright(const std::wstring& translation = std::wstring()) const; + //Returns original file name + const std::wstring get_original_filename(const std::wstring& translation = std::wstring()) const; + //Returns product name + const std::wstring get_product_name(const std::wstring& translation = std::wstring()) const; + //Returns product version + const std::wstring get_product_version(const std::wstring& translation = std::wstring()) const; + + //Returns list of translations in string representation + const translation_list get_translation_list() const; + + //Returns version info property value + //property_name - required property name + //If throw_if_absent = true, will throw exception if property does not exist + //If throw_if_absent = false, will return empty string if property does not exist + const std::wstring get_property(const std::wstring& property_name, const std::wstring& translation = std::wstring(), bool throw_if_absent = false) const; + + //Converts translation HEX-string to pair of language ID and codepage ID + static const translation_pair translation_from_string(const std::wstring& translation); + +public: + //Default process language, UNICODE + static const std::wstring default_language_translation; + +private: + const lang_string_values_map& strings_; + const translation_values_map& translations_; +}; +} diff --git a/tools/scripts/file-hex-array.py b/tools/scripts/file-hex-array.py new file mode 100755 index 0000000000..05352396f1 --- /dev/null +++ b/tools/scripts/file-hex-array.py @@ -0,0 +1,52 @@ +import binascii +import os.path +import sys + +def tof(filepath): + with open(filepath, 'r') as f: + content = f.read() + content = content.replace("0x","") + content = content.split(',') + for i in range(len(content)): + if len(content[i]) == 1: content[i] = "0" + content[i] + content = "".join(content) + with open(filepath+".file", 'wb') as f: + content = f.write(content.decode("hex")) + print(os.path.basename(filepath)+".file created.") + exit(0) + +def toa(filepath): + with open(filepath, 'rb') as f: + content = f.read() + content = binascii.hexlify(content) + content = [content[i:i+2] for i in range(0, len(content), 2)] + content = ",0x".join(content) + content = "0x" + content + content = content.replace("0x00","0x0") + with open(filepath+".array", 'w') as f: + content = f.write(content) + print(os.path.basename(filepath)+".array created.") + exit(0) + +def usage(): + print("========================================================\n\ +#\n\ +# Usage: python file-hex-array.py [action] [option]\n\ +#\n\ +# Arguments:\n\ +# action ==> toa # convert file to array [option is file path]\n\ +# tof # convert array to file [option is array file path]\n\ +#\n\ +# Example : python file-hex-array.py toa 1.png\n\ +#\n\ +========================================================") + exit(1) + +if len(sys.argv) != 3: + usage() +if sys.argv[1] == "toa" and os.path.isfile(sys.argv[2]): + toa(sys.argv[2]) +elif sys.argv[1] == "tof" and os.path.isfile(sys.argv[2]): + tof(sys.argv[2]) +else: + usage()
\ No newline at end of file |