pax_global_header00006660000000000000000000000064131163111260014505gustar00rootroot0000000000000052 comment=08f161d3ee11c924417378a8b4e54950133681aa gir-to-d-0.10.0/000077500000000000000000000000001311631112600132055ustar00rootroot00000000000000gir-to-d-0.10.0/COPYING000066400000000000000000000167431311631112600142530ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. gir-to-d-0.10.0/GNUmakefile000066400000000000000000000015361311631112600152640ustar00rootroot00000000000000SHELL=/bin/sh OS=$(shell uname || uname -s) ARCH=$(shell arch || uname -m) ifndef DC ifneq ($(strip $(shell which dmd 2>/dev/null)),) DC=dmd else ifneq ($(strip $(shell which ldc 2>/dev/null)),) DC=ldc else ifneq ($(strip $(shell which ldc2 2>/dev/null)),) DC=ldc2 else DC=gdc endif endif ifeq ("$(DC)","gdc") DCFLAGS=-O2 LINKERFLAG=-Xlinker DDOCFLAGS=-fsyntax-only -c -fdoc -fdoc-file=$@ DDOCINC=-fdoc-inc= output=-o $@ else DCFLAGS=-O LINKERFLAG=-L DDOCFLAGS=-o- -Df$@ output=-of$@ endif ####################################################################### .DEFAULT_GOAL = $(BINNAME) SOURCES = $(wildcard source/*.d) $(wildcard source/gtd/*.d) BINNAME = girtod $(BINNAME): $(SOURCES) $(DC) $^ $(output) $(DCFLAGS) $(LDFLAGS) rm -f *.o clean: -rm -f $(BINNAME) gir-to-d-0.10.0/Readme_APILookup000066400000000000000000000131101311631112600162040ustar00rootroot00000000000000The GTK binding is generated by the gtkwrap utility using the APILookup files in this directory and the GIR files from GObject Introspection. The gtkwrap utility parses APILookup.txt which tells it what to do/parse using the commands listed bellow. There to two types of commands key value pares and block commands which are denoted with "command: start" and "command: end". license: (block) Sets the license text used at the top of the generated files. includeComments: (true/false) If true the generated code includes comments/documentation for the classes, funtions, etc. alias: ctype dtype Replace ctype with dtype in the generated code. outputRoot: path Directory where the generated code is stored. srcDir: directory The source for the following component is placed in this directory. copy: filename Copies filename form inputRoot to outputRoot/srcDir. lookup: filename Continue parsing in filename. wrap: packageName Starts wrapping a package, and uses packageName as it's name. After this command and until the end of the file, all commands only affect the package. and only the commands listed below can be used. addAliases: (block) Add the contained text the the alias section of the c definitions. addEnums: (block) Add the contained text the the enum section of the c definitions. addStructs: (block) Add the contained text the the struct section of the c definitions. addFuncts: (block) Add the contained text the the function/callback section of the c definitions. addConstants: (block) Add the contained text the the alias constant of the c definitions. file: path/filename Parse the a GIR file, the command can be used multiple times to combine different GIR files. move: src dest [new_name] Move function src to struct dest. optionaly set a new name for the function. dest will be created if it doesn't exist. Currently only works for global functions, you can list the global functions that haven't been moved by running gtkwrap with the --print-free argument. struct: name Sets the struct to which the following commands apply. If the struct doesn't exist it will be created. The name can be left blank, in wich case class and interface can be used to create a new class or interface. class: name Overwrite the settings in the gir file and generate this struct as a class using the specified name. Or create a new class if the struct isn't set. interface: name Overwrite the settings in the gir file and generate this struct as a interface using the specified name. Or create a new interface if the struct isn't set. namespace: name Put the functions in a struct that is used as a namespace. name can be blank to generate the functions in module scope. cType: type Override the cType used in the GIR file. extend: base_class Explicitly set the base class for this class. base_class should match the name used in the GIR files eg: GObject.Object. implements: interface Explicitly set an interface implemented by this class. This command can be used more than once. merge: name merge struct 'name' with the struct set by struct:. import: package.module Explicitly add imports to the generated file. structWrap: ctype dtype Wrap ctype as dtype, insted of whats defined by the GIR files. alias: ctype dtype Replace ctype with dtype in the generated code. override: func_name Explicitly add the override attribute to function func_name. func_name should be the name specified in the GIR file. noAlias: name Don't generate any code for alias name. name should be the name specified in the GIR file. noEnum: name Don't generate any code for enum name. name should be the name specified in the GIR file. noCallback: name Don't generate any code for callback name. name should be the name specified in the GIR file. noCode: name Don't generate any code for function name. name should be the name specified in the GIR file. noCode: true Don't generate any code for the struct set by struct: noExternal: true Don't generate the c declaration for the struct set by struct: noSignal: name Don't generate any code for signal name. name should be the name specified in the GIR file. noStruct: true Don't generate any D code for struct set by struct: code: (block) Add the contained code/text the the generated struct/class. interfaceCode: (block) Add the contained code/text the the generated interface. in: func_name param_name Override the GIR file and don't generate the specified parameter of func_name as out or ref. out: func_name param_name Override the GIR file and generate the specified parameter of func_name as out. ref: func_name param_name Override the GIR file and generate the specified parameter of func_name as ref. inout: func_name param_name Ditto, Deprecated. array: func_name param_array [param_length] Override the GIR file and handle param_array of function func_name as an array who's length is specified by param_length. If param_length isn't secified the wrapper asumes the array is zero terminated. "Return" can be used fo either param_array or param_length for when one of them is returned by the function. copy: filename Copies filename form inputRoot to outputRoot/srcDir. version X.XX: command: value Only include the command if the version specified in the Gir file is >= X.XX. version X.XX: (block) The same as above but applies to all commands between the start and end tag. For the end tag the version number is optional. gir-to-d-0.10.0/meson.build000066400000000000000000000011231311631112600153440ustar00rootroot00000000000000project('GIR-D-Generator', 'd') source = [ 'source/girtod.d', 'source/gtd/DefReader.d', 'source/gtd/GlibTypes.d', 'source/gtd/GirAlias.d', 'source/gtd/GirEnum.d', 'source/gtd/GirFunction.d', 'source/gtd/GirPackage.d', 'source/gtd/GirStruct.d', 'source/gtd/GirType.d', 'source/gtd/GirVersion.d', 'source/gtd/GirWrapper.d', 'source/gtd/IndentedStringBuilder.d', 'source/gtd/LinkedHasMap.d', 'source/gtd/WrapError.d', 'source/gtd/XMLReader.d' ] sources_dir = include_directories('source/') executable( 'girtod', [source], include_directories : [sources_dir], install : true ) gir-to-d-0.10.0/source/000077500000000000000000000000001311631112600145055ustar00rootroot00000000000000gir-to-d-0.10.0/source/girtod.d000066400000000000000000000051451311631112600161470ustar00rootroot00000000000000/* * This file is part of gtkD. * * gtkD is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version, with * some exceptions, please read the COPYING file. * * gtkD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with gtkD; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA */ module girtod; import std.array; import std.getopt; import std.path; import std.stdio; import core.stdc.stdlib; import gtd.GirWrapper; void main(string[] args) { bool printFree; bool useRuntimeLinker; bool useBindDir; string inputDir; string outputDir; string girDir; try { auto helpInformation = getopt( args, "input|i", "Directory containing the API description. (Default: ./)", &inputDir, "output|o", "Output directory for the generated binding. (Default: {input dir}/out)", &outputDir, "use-runtime-linker", "Link the gtk functions with the runtime linker.", &useRuntimeLinker, "gir-directory|g", "Directory to search for gir files before the system directory.", &girDir, "print-free", "Print functions that don't have a parrent module.", &printFree, "use-bind-dir", "Include public imports for the old gtkc package.", &useBindDir ); if (helpInformation.helpWanted) { defaultGetoptPrinter("gir-d-generator is an utility that generates D bindings using the GObject introspection files.\nOptions:", helpInformation.options); exit(0); } } catch (GetOptException e) { writeln ("Unable to parse parameters: ", e.msg); exit (1); } if ( inputDir.empty ) inputDir = "./"; if ( outputDir.empty ) outputDir = buildPath(inputDir, "out"); //Read in the GIR and API files. GirWrapper wrapper = new GirWrapper(inputDir, outputDir, useRuntimeLinker); wrapper.commandlineGirPath = girDir; wrapper.useBindDir = useBindDir; wrapper.proccess("APILookup.txt"); if ( printFree ) wrapper.printFreeFunctions(); //Generate the D binding foreach(pack; wrapper.packages) { if ( pack.name == "cairo" ) continue; if ( useRuntimeLinker ) pack.writeLoaderTable(); else pack.writeExternalFunctions(); pack.writeTypes(); pack.writeClasses(); } } gir-to-d-0.10.0/source/gtd/000077500000000000000000000000001311631112600152635ustar00rootroot00000000000000gir-to-d-0.10.0/source/gtd/DefReader.d000066400000000000000000000051261311631112600172550ustar00rootroot00000000000000/* * This file is part of gtkD. * * gtkD is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version, with * some exceptions, please read the COPYING file. * * gtkD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with gtkD; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA */ module gtd.DefReader; import std.algorithm; import std.array; import std.file; import std.string : splitLines, strip, indexOf; import gtd.WrapError; public class DefReader { string filename; string key; string subKey; string value; int lineNumber; string[] lines; public this(string filename) { this.filename = filename; lines = readText(filename).splitLines(); //Skip utf8 BOM. lines[0].skipOver(x"efbbbf"); this.popFront(); } public void popFront() { string line; if ( !lines.empty ) { line = lines.front.strip(); lines.popFront(); lineNumber++; while ( !lines.empty && ( line.empty || line.startsWith("#") ) ) { line = lines.front.strip(); lines.popFront(); lineNumber++; } } if ( !line.empty && !line.startsWith("#") ) { size_t index = line.indexOf(':'); key = line[0 .. max(index, 0)].strip(); value = line[index +1 .. $].strip(); index = key.indexOf(' '); if ( index != -1 ) { subKey = key[index +1 .. $].strip(); key = key[0 .. index].strip(); } } else { key.length = 0; value.length = 0; } } /** * Gets the contends of a block value */ public string[] readBlock(string key = "") { string[] block; if ( key.empty ) key = this.key; while ( !lines.empty ) { if ( startsWith(lines.front.strip(), key) ) { lines.popFront(); lineNumber++; return block; } block ~= lines.front ~ '\n'; lines.popFront(); lineNumber++; } throw new WrapError(this, "Found EOF while expecting: \""~key~": end\""); } /** * Gets the current value as a bool */ public @property bool valueBool() { return !!value.among("1", "ok", "OK", "Ok", "true", "TRUE", "True", "Y", "y", "yes", "YES", "Yes"); } public @property bool empty() { return lines.empty && key.empty; } } gir-to-d-0.10.0/source/gtd/GirAlias.d000066400000000000000000000042161311631112600171260ustar00rootroot00000000000000/* * This file is part of gtkD. * * gtkD is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version, with * some exceptions, please read the COPYING file. * * gtkD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with gtkD; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA */ module gtd.GirAlias; import std.string : splitLines, strip; import gtd.GirType; import gtd.GirWrapper; import gtd.XMLReader; final class GirAlias { string name; string cType; string doc; GirType baseType; GirWrapper wrapper; this(GirWrapper wrapper) { this.wrapper = wrapper; } void parse(T)(XMLReader!T reader) { name = reader.front.attributes["name"]; cType = reader.front.attributes["c:type"]; reader.popFront(); while( !reader.empty && !reader.endTag("alias") ) { switch(reader.front.value) { case "type": baseType = new GirType(wrapper); baseType.parse(reader); break; case "doc": reader.popFront(); doc ~= reader.front.value; reader.popFront(); break; case "doc-deprecated": reader.popFront(); doc ~= "\n\nDeprecated: "~ reader.front.value; reader.popFront(); break; default: throw new XMLException(reader, "Unexpected tag: "~ reader.front.value ~" in GirAlias: "~ name); } reader.popFront(); } } string[] getAliasDeclaration() { string[] buff; if ( doc !is null && wrapper.includeComments ) { buff ~= "/**"; foreach ( line; doc.splitLines() ) buff ~= " * "~ line.strip(); buff ~= " */"; } buff ~= "public alias "~ stringToGtkD(baseType.cType, wrapper.aliasses) ~" "~ tokenToGtkD(cType, wrapper.aliasses) ~";"; return buff; } } gir-to-d-0.10.0/source/gtd/GirEnum.d000066400000000000000000000105631311631112600170030ustar00rootroot00000000000000/* * This file is part of gtkD. * * gtkD is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version, with * some exceptions, please read the COPYING file. * * gtkD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with gtkD; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA */ module gtd.GirEnum; import std.algorithm; import std.string : splitLines, strip, toUpper; import gtd.GirPackage; import gtd.GirWrapper; import gtd.XMLReader; final class GirEnum { string name; string cName; string libVersion; string doc; GirEnumMember[] members; GirWrapper wrapper; GirPackage pack; this(GirWrapper wrapper, GirPackage pack) { this.wrapper = wrapper; this.pack = pack; } void parse(T)(XMLReader!T reader) { name = reader.front.attributes["name"]; cName = reader.front.attributes["c:type"]; if ( "version" in reader.front.attributes ) libVersion = reader.front.attributes["version"]; reader.popFront(); while ( !reader.empty && !reader.endTag("bitfield", "enumeration") ) { switch (reader.front.value) { case "doc": reader.popFront(); doc ~= reader.front.value; reader.popFront(); break; case "doc-deprecated": reader.popFront(); doc ~= "\n\nDeprecated: "~ reader.front.value; reader.popFront(); break; case "member": if ( reader.front.attributes["name"].startsWith("2bu", "2bi", "3bu") ) { reader.skipTag(); break; } GirEnumMember member = GirEnumMember(wrapper); member.parse(reader); members ~= member; break; case "function": //Skip these functions for now //as they are also availabe as global functions. //pack.parseFunction(reader); reader.skipTag(); break; default: throw new XMLException(reader, "Unexpected tag: "~ reader.front.value ~" in GirEnum: "~ name); } reader.popFront(); } } string[] getEnumDeclaration() { string[] buff; if ( doc !is null && wrapper.includeComments ) { buff ~= "/**"; foreach ( line; doc.splitLines() ) buff ~= " * "~ line.strip(); if ( libVersion ) { buff ~= " *"; buff ~= " * Since: "~ libVersion; } buff ~= " */"; } buff ~= "public enum "~ cName ~(name.among("ParamFlags", "MessageType") ? " : uint" : ""); buff ~= "{"; foreach ( member; members ) { buff ~= member.getEnumMemberDeclaration(); } buff ~= "}"; if ( name !is null && pack.name.among("glgdk", "glgtk") ) buff ~= "alias "~ cName ~" GL"~ name ~";"; else if ( name !is null && pack.name != "pango" ) buff ~= "alias "~ cName ~" "~ name ~";"; return buff; } } struct GirEnumMember { string name; string value; string doc; GirWrapper wrapper; @disable this(); this(GirWrapper wrapper) { this.wrapper = wrapper; } void parse(T)(XMLReader!T reader) { name = reader.front.attributes["name"]; value = reader.front.attributes["value"]; if ( reader.front.type == XMLNodeType.EmptyTag ) return; reader.popFront(); while ( !reader.empty && !reader.endTag("member", "constant") ) { switch (reader.front.value) { case "doc": reader.popFront(); doc ~= reader.front.value; reader.popFront(); break; case "doc-deprecated": reader.popFront(); doc ~= "\n\nDeprecated: "~ reader.front.value; reader.popFront(); break; case "type": if ( reader.front.attributes["name"] == "utf8" ) value = "\""~ value ~"\""; break; default: throw new XMLException(reader, "Unexpected tag: "~ reader.front.value ~" in GirEnumMember: "~ name); } reader.popFront(); } } string[] getEnumMemberDeclaration() { string[] buff; if ( doc !is null && wrapper.includeComments ) { buff ~= "/**"; foreach ( line; doc.splitLines() ) buff ~= " * "~ line.strip(); buff ~= " */"; } buff ~= tokenToGtkD(name.toUpper(), wrapper.aliasses, false) ~" = "~ value ~","; return buff; } } gir-to-d-0.10.0/source/gtd/GirFunction.d000066400000000000000000001215721311631112600176670ustar00rootroot00000000000000/* * This file is part of gtkD. * * gtkD is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version, with * some exceptions, please read the COPYING file. * * gtkD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with gtkD; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA */ module gtd.GirFunction; import std.algorithm: among, startsWith, endsWith; import std.conv; import std.range; import std.string : chomp, splitLines, strip, removechars; import std.uni: toUpper, toLower; import gtd.GirEnum; import gtd.GirStruct; import gtd.GirType; import gtd.GirVersion; import gtd.GirWrapper; import gtd.XMLReader; enum GirFunctionType : string { Constructor = "constructor", Method = "method", Function = "function", Callback = "callback", Signal = "glib:signal" } enum GirTransferOwnership : string { None = "none", /// Gtk owns the returned reference. Full = "full", /// We own the returned reference. Container = "container" /// The container in which the references reside has ownership. } final class GirFunction { string name; GirFunctionType type; string doc; string cType; string libVersion; string movedTo; bool virtual = false; bool throws = false; bool lookupOverride; /// Force marking this function with override. bool noCode; /// Don't generate any class code for this function. GirType returnType; GirTransferOwnership returnOwnership = GirTransferOwnership.None; GirParam instanceParam; GirParam[] params; GirWrapper wrapper; GirStruct strct; this (GirWrapper wrapper, GirStruct strct) { this.wrapper = wrapper; this.strct = strct; } GirFunction dup() { GirFunction copy = new GirFunction(wrapper, strct); foreach ( i, field; this.tupleof ) copy.tupleof[i] = field; return copy; } void parse(T)(XMLReader!T reader) { name = reader.front.attributes["name"]; // Special case for g_iconv wich doesnt have a name. if ( name.empty && "moved-to" in reader.front.attributes ) name = reader.front.attributes["moved-to"]; type = cast(GirFunctionType)reader.front.value; if ( "c:type" in reader.front.attributes ) cType = reader.front.attributes["c:type"]; if ( "c:identifier" in reader.front.attributes ) cType = reader.front.attributes["c:identifier"]; if ( "version" in reader.front.attributes ) { libVersion = reader.front.attributes["version"]; if ( strct ) strct.pack.checkVersion(libVersion); } if ( "throws" in reader.front.attributes ) throws = reader.front.attributes["throws"] == "1"; if ( "moved-to" in reader.front.attributes ) movedTo = reader.front.attributes["moved-to"]; reader.popFront(); while( !reader.empty && !reader.endTag("constructor", "method", "function", "callback", "glib:signal") ) { switch ( reader.front.value ) { case "doc": reader.popFront(); doc ~= reader.front.value; reader.popFront(); break; case "doc-deprecated": reader.popFront(); doc ~= "\n\nDeprecated: "~ reader.front.value; reader.popFront(); break; case "doc-version": reader.skipTag(); break; case "return-value": if ( "transfer-ownership" in reader.front.attributes ) returnOwnership = cast(GirTransferOwnership)reader.front.attributes["transfer-ownership"]; returnType = new GirType(wrapper); reader.popFront(); while( !reader.empty && !reader.endTag("return-value") ) { switch ( reader.front.value ) { case "doc": reader.popFront(); returnType.doc ~= reader.front.value; reader.popFront(); break; case "array": case "type": returnType.parse(reader); break; default: throw new XMLException(reader, "Unexpected tag: "~ reader.front.value ~" in GirFunction: "~ name); } reader.popFront(); } break; case "parameters": reader.popFront(); while( !reader.empty && !reader.endTag("parameters") ) { switch ( reader.front.value ) { case "instance-parameter": instanceParam = new GirParam(wrapper); instanceParam.parse(reader); break; case "parameter": GirParam param = new GirParam(wrapper); param.parse(reader); params ~= param; break; default: throw new XMLException(reader, "Unexpected tag: "~ reader.front.value ~" in GirFunction: "~ name); } reader.popFront(); } break; default: throw new XMLException(reader, "Unexpected tag: "~ reader.front.value ~" in GirFunction: "~ name); } reader.popFront(); } if ( type == GirFunctionType.Function && name.startsWith("new") && returnType.cType != "void" ) type = GirFunctionType.Constructor; if ( cType.among("gst_init", "gst_init_check") ) { params[1].type.cType = "char***"; params[1].type.elementType.cType = "char**"; } } bool isVariadic() { if ( params.empty ) return false; else if ( params[$-1].name == "..." ) return true; return false; } string[] getCallbackDeclaration() { string[] buff; writeDocs(buff); buff ~= "public alias extern(C) "~ getExternalFunctionType() ~" "~ tokenToGtkD(cType, wrapper.aliasses, localAliases()) ~";"; return buff; } string[] getFunctionPointerDecleration() { string[] buff; writeDocs(buff); buff ~= "extern(C) "~ getExternalFunctionType() ~" "~ tokenToGtkD(name, wrapper.aliasses, localAliases()) ~";"; return buff; } string getLinkerExternal() { assert(type != GirFunctionType.Callback); assert(type != GirFunctionType.Signal); if (strct.pack.name == "glgdk") return getExternalFunctionType() ~" glc_"~ cType ~";"; else return getExternalFunctionType() ~" c_"~ cType ~";"; } string getExternal() { assert(type != GirFunctionType.Callback); assert(type != GirFunctionType.Signal); string ext; string type = stringToGtkD(returnType.cType, wrapper.aliasses, localAliases()); if ( type.startsWith("bool") ) ext ~= type.replaceFirst("bool", "int"); else ext ~= type; ext ~= " "~ cType ~"("~ getExternalParameters() ~");"; return ext; } private string getExternalFunctionType() { string ext; string type = stringToGtkD(returnType.cType, wrapper.aliasses, localAliases()); if ( type.startsWith("bool") ) ext ~= type.replaceFirst("bool", "int"); else ext ~= type; ext ~= " function("~ getExternalParameters() ~")"; return ext; } private string getExternalParameters() { string ext, type; if ( instanceParam ) { ext ~= stringToGtkD(instanceParam.type.cType, wrapper.aliasses, localAliases()); ext ~= " "; ext ~= tokenToGtkD(instanceParam.name, wrapper.aliasses, localAliases()); } foreach ( i, param; params ) { if ( i > 0 || instanceParam ) ext ~= ", "; type = stringToGtkD(param.type.cType, wrapper.aliasses, localAliases()); if ( type.startsWith("bool") ) ext ~= type.replaceFirst("bool", "int"); else ext ~= type; ext ~= " "; //Both name and type are ... for Variadic functions. if ( param.name != "..." ) ext ~= tokenToGtkD(param.name, wrapper.aliasses, localAliases()); } if ( throws ) ext ~= ", GError** err"; return ext; } string[] getDeclaration() { string[] buff; string dec = "public "; resolveLength(); writeDocs(buff); if ( type == GirFunctionType.Constructor ) { dec ~= "this("; } else { if ( isStatic() ) dec ~= "static "; if ( lookupOverride || checkOverride() ) dec ~= "override "; dec ~= getType(returnType) ~" "; dec ~= tokenToGtkD(name, wrapper.aliasses, localAliases()) ~"("; } size_t paramCount; if ( instanceParam && ((type == GirFunctionType.Method && (strct.isNamespace() || strct.noNamespace )) || type == GirFunctionType.Constructor) ) { dec ~= getType(instanceParam.type) ~" "~ tokenToGtkD(instanceParam.name, wrapper.aliasses, localAliases()); paramCount++; } foreach( param; params ) { if ( param.lengthFor ) continue; if ( returnType.length > -1 && param == params[returnType.length] ) continue; if ( paramCount == 0 && strct.type == GirStructType.Record && isInstanceParam(param) ) continue; if ( paramCount++ > 0 ) dec ~= ", "; if ( param.direction == GirParamDirection.Out ) dec ~= "out "; else if ( param.direction == GirParamDirection.InOut ) dec ~= "ref "; dec ~= getType(param.type, param.direction) ~" "; dec ~= tokenToGtkD(param.name, wrapper.aliasses, localAliases()); } dec ~= ")"; buff ~= dec; return buff; } string[] getBody() { string[] buff; string[] outToD; string gtkCall = cType ~"("; GirStruct returnDType; if ( returnType.isArray() ) { returnDType = strct.pack.getStruct(returnType.elementType.name); if ( returnDType && returnType.elementType.cType.empty ) returnType.elementType.cType = returnDType.cType ~"*"; } else { returnDType = strct.pack.getStruct(returnType.name); if ( returnDType && returnType.cType.empty ) returnType.cType = returnDType.cType ~"*"; } if ( instanceParam || ( !params.empty && isInstanceParam(params[0])) ) { GirStruct dType; if ( instanceParam ) { dType = strct.pack.getStruct(instanceParam.type.name); if ( dType.cType != instanceParam.type.cType.removechars("*") && !instanceParam.type.cType.among("gpointer", "gconstpointer") ) gtkCall ~= "cast("~ stringToGtkD(instanceParam.type.cType, wrapper.aliasses, localAliases()) ~")"; } else { dType = strct.pack.getStruct(params[0].type.name); if ( dType.cType != params[0].type.cType.removechars("*") && !params[0].type.cType.among("gpointer", "gconstpointer") ) gtkCall ~= "cast("~ stringToGtkD(params[0].type.cType, wrapper.aliasses, localAliases()) ~")"; } if ( instanceParam && instanceParam.type.name in strct.structWrap ) { GirStruct insType = strct.pack.getStruct(strct.structWrap[instanceParam.type.name]); if ( insType ) dType = insType; } if ( type == GirFunctionType.Constructor || strct.isNamespace() || strct.noNamespace ) { string id = tokenToGtkD(instanceParam.name, wrapper.aliasses, localAliases()); if ( dType && !(dType.isNamespace() || dType.noNamespace) ) gtkCall ~= "("~ id ~" is null) ? null : "~ id ~"."~ dType.getHandleFunc() ~"()"; else gtkCall ~= id; } else if ( dType.type == GirStructType.Interface || dType.lookupInterface ) { gtkCall ~= strct.getHandleFunc() ~"()"; } else { gtkCall ~= strct.getHandleVar(); } } foreach( i, param; params ) { GirStruct dType; string id = tokenToGtkD(param.name, wrapper.aliasses, localAliases()); if ( param.type.isArray() ) dType = strct.pack.getStruct(param.type.elementType.name); else if ( auto dStrct = strct.pack.getStruct(strct.structWrap.get(param.type.name, "")) ) dType = dStrct; else dType = strct.pack.getStruct(param.type.name); if ( i == 0 && isInstanceParam(param) ) continue; if ( instanceParam || i > 0 ) gtkCall ~= ", "; if ( isStringType(param.type) ) { if ( isStringArray(param.type, param.direction) ) { // out string[], ref string[] if ( param.direction != GirParamDirection.Default ) { buff ~= "char** out"~ id ~" = "; if ( param.direction == GirParamDirection.Out ) buff[$-1] ~= "null;"; else buff[$-1] ~= "Str.toStringzArray("~ id ~");"; string len = lenId(param.type); if ( !len.empty ) len = ", "~ len; gtkCall ~= "&out"~ id; outToD ~= id ~" = Str.toStringArray(out"~ id ~ len ~");"; } // string[] else { gtkCall ~= "Str.toStringzArray("~ id ~")"; } } else { if ( param.direction != GirParamDirection.Default ) { string len = lenId(param.type); // A buffer to fill. if ( !param.type.cType.endsWith("**") ) { gtkCall ~= id ~".ptr"; if ( !len.empty && params[param.type.length].direction != GirParamDirection.Default ) outToD ~= id ~" = "~ id ~"[0.."~ len ~"];"; } // out string, ref string else { buff ~= "char* out"~ id ~" = "; if ( param.direction == GirParamDirection.Out ) buff[$-1] ~= "null;"; else buff[$-1] ~= "Str.toStringz("~ id ~");"; if ( !len.empty ) len = ", "~ len; gtkCall ~= "&out"~ id; outToD ~= id ~" = Str.toString(out"~ id ~ len ~");"; } } // string else { gtkCall ~= "Str.toStringz("~ id ~")"; } } } else if ( isDType(dType) ) { if ( param.type.isArray() ) { GirType elementType = param.type.elementType; GirStruct dElementType = strct.pack.getStruct(elementType.name); if ( elementType.cType.empty ) elementType.cType = stringToGtkD(param.type.cType, wrapper.aliasses, localAliases())[0 .. $-1]; // out gtkdType[], ref gtkdType[] if ( param.direction != GirParamDirection.Default ) { if ( param.direction == GirParamDirection.Out ) { buff ~= elementType.cType ~" out"~ id ~" = null;"; } else { if ( !buff.empty ) buff ~= ""; buff ~= elementType.cType.removechars("*") ~ "**[] inout"~ id ~" = new "~ elementType.cType.removechars("*") ~"*["~ id ~".length];"; buff ~= "for ( int i = 0; i < "~ id ~".length; i++ )"; buff ~= "{"; buff ~= "inout"~ id ~"[i] = "~ id~ "[i]."~ dElementType.getHandleFunc() ~"();"; buff ~= "}"; buff ~= ""; buff ~= elementType.cType.removechars("*") ~ "** out"~ id ~" = inout"~ id ~".ptr;"; } gtkCall ~= "&out"~ id; if ( !outToD.empty ) outToD ~= ""; outToD ~= id ~" = new "~ dElementType.name ~"["~ lenId(param.type, "out"~ id) ~"];"; outToD ~= "for(size_t i = 0; i < "~ lenId(param.type, "out"~ id) ~"; i++)"; outToD ~= "{"; if ( elementType.cType.endsWith("**") ) outToD ~= id ~"[i] = " ~ construct(elementType.name) ~ "(cast(" ~ elementType.cType[0..$-1] ~ ") out"~ id ~"[i]);"; else outToD ~= id ~"[i] = " ~ construct(elementType.name) ~ "(cast(" ~ elementType.cType ~ ") &out"~ id ~"[i]);"; outToD ~= "}"; } // gtkdType[] else { //TODO: zero-terminated see: g_signal_chain_from_overridden if ( !buff.empty ) buff ~= ""; buff ~= elementType.cType ~ "[] "~ id ~"Array = new "~ elementType.cType ~"["~ id ~".length];"; buff ~= "for ( int i = 0; i < "~ id ~".length; i++ )"; buff ~= "{"; if ( elementType.cType.endsWith("*") ) buff ~= id ~"Array[i] = "~ id ~"[i]."~ dElementType.getHandleFunc() ~"();"; else buff ~= id ~"Array[i] = *("~ id ~"[i]."~ dElementType.getHandleFunc() ~"());"; buff ~= "}"; buff ~= ""; gtkCall ~= id ~"Array.ptr"; } } else { // out gtkdType, ref gtkdType if ( param.direction != GirParamDirection.Default && param.type.cType.endsWith("**") ) { buff ~= param.type.cType.removechars("*") ~"* out"~ id ~" = "; if ( param.direction == GirParamDirection.Out ) buff[$-1] ~= "null;"; else buff[$-1] ~= id ~"."~ dType.getHandleFunc() ~"();"; gtkCall ~= "&out"~ id; outToD ~= id ~" = "~ construct(param.type.name) ~"(out"~ id ~");"; } else if ( param.direction == GirParamDirection.Out ) { buff ~= param.type.cType.removechars("*") ~"* out"~ id ~" = gMalloc!"~ param.type.cType.removechars("*") ~"();"; gtkCall ~= "out"~ id; outToD ~= id ~" = "~ construct(param.type.name) ~"(out"~ id ~", true);"; } // gtkdType else { gtkCall ~= "("~ id ~" is null) ? null : "; if ( dType.cType != param.type.cType.removechars("*") && !param.type.cType.among("gpointer", "gconstpointer") ) gtkCall ~= "cast("~ stringToGtkD(param.type.cType, wrapper.aliasses, localAliases()) ~")"; if ( param.ownership == GirTransferOwnership.Full && dType.shouldFree() ) gtkCall ~= id ~"."~ dType.getHandleFunc ~"(true)"; else gtkCall ~= id ~"."~ dType.getHandleFunc ~"()"; } } } else if ( param.lengthFor || returnType.length == i ) { string arrId; string lenType = tokenToGtkD(param.type.cType.removechars("*"), wrapper.aliasses, localAliases()); if ( param.lengthFor ) arrId = tokenToGtkD(param.lengthFor.name, wrapper.aliasses, localAliases()); final switch ( param.direction ) with (GirParamDirection) { case Default: gtkCall ~= "cast("~ lenType ~")"~ arrId ~".length"; break; case Out: buff ~= lenType ~" "~ id ~";"; gtkCall ~= "&"~id; break; case InOut: buff ~= lenType ~" "~ id ~" = cast("~ lenType ~")"~ arrId ~".length;"; gtkCall ~= "&"~id; break; } } else if ( param.type.name.among("bool", "gboolean") || ( param.type.isArray && param.type.elementType.name.among("bool", "gboolean") ) ) { if ( param.type.isArray() ) { // out bool[], ref bool[] if ( param.direction != GirParamDirection.Default ) { if ( param.direction == GirParamDirection.Out ) { buff ~= "int* out"~ id ~" = null;"; } else { if ( !buff.empty ) buff ~= ""; buff ~= "int[] inout"~ id ~" = new int["~ id ~".length];"; buff ~= "for ( int i = 0; i < "~ id ~".length; i++ )"; buff ~= "{"; buff ~= "inout"~ id ~"[i] = "~ id~ "[i] ? 1 : 0;"; buff ~= "}"; buff ~= ""; buff ~= "int* out"~ id ~" = inout"~ id ~".ptr;"; } gtkCall ~= "&out"~ id; if ( !outToD.empty ) outToD ~= ""; outToD ~= id ~" = new bool["~ lenId(param.type, "out"~ id) ~"];"; outToD ~= "for(size_t i = 0; i < "~ lenId(param.type, "out"~ id) ~"; i++)"; outToD ~= "{"; outToD ~= id ~"[i] = out"~ id ~"[i] != 0);"; outToD ~= "}"; } // bool[] else { if ( !buff.empty ) buff ~= ""; buff ~= "int[] "~ id ~"Array = new int["~ id ~".length];"; buff ~= "for ( int i = 0; i < "~ id ~".length; i++ )"; buff ~= "{"; buff ~= id ~"Array[i] = "~ id ~"[i] ? 1 : 0;"; buff ~= "}"; buff ~= ""; gtkCall ~= id ~"Array.ptr"; } } else { // out bool, ref bool if ( param.direction != GirParamDirection.Default ) { buff ~= "int out"~ id; if ( param.direction == GirParamDirection.Out ) buff[$-1] ~= ";"; else buff[$-1] ~= " = ("~ id ~" ? 1 : 0);"; gtkCall ~= "&out"~ id ~""; outToD ~= id ~" = (out"~ id ~" == 1);"; } // bool else { gtkCall ~= id; } } } else { if ( param.type.isArray() ) { // out T[], ref T[] if ( param.direction != GirParamDirection.Default ) { string outType = param.type.elementType.cType; if ( outType.empty ) outType = param.type.elementType.name ~"*"; buff ~= stringToGtkD(outType, wrapper.aliasses, localAliases) ~" out"~ id ~" = "; if ( param.direction == GirParamDirection.Out ) buff[$-1] ~= "null;"; else buff[$-1] ~= id ~".ptr"; if ( param.type.elementType.cType.empty ) gtkCall ~= "cast("~stringToGtkD(param.type.cType, wrapper.aliasses, localAliases) ~")&out"~ id ~""; else gtkCall ~= "&out"~ id ~""; outToD ~= id ~" = out"~ id ~"[0 .. "~ lenId(param.type, "out"~ id) ~"];"; } // T[] else { gtkCall ~= id ~".ptr"; } } else { if ( param.type.name in strct.structWrap ) { gtkCall ~= "("~ id ~" is null) ? null : "~ id ~".get"~ strct.structWrap[param.type.name] ~"Struct()"; } else { // out T, ref T if ( param.direction != GirParamDirection.Default ) { gtkCall ~= "&"~ id; } // T else { gtkCall ~= id; } } } } } if ( throws ) { buff ~= "GError* err = null;"; gtkCall ~= ", &err"; } enum throwGException = [ "", "if (err !is null)", "{", "throw new GException( new ErrorG(err) );", "}"]; gtkCall ~= ")"; if ( !buff.empty && buff[$-1] != "" ) buff ~= ""; if ( returnType.name == "none" ) { buff ~= gtkCall ~";"; if ( throws ) { buff ~= throwGException; } if ( !outToD.empty ) { buff ~= ""; buff ~= outToD; } if ( name == "free" && strct && strct.shouldFree() ) { buff ~= "ownedRef = false;"; } return buff; } else if ( type == GirFunctionType.Constructor ) { buff ~= "auto p = " ~ gtkCall ~";"; if ( throws ) { buff ~= throwGException; } buff ~= ""; buff ~= "if(p is null)"; buff ~= "{"; buff ~= "throw new ConstructionException(\"null returned by " ~ name ~ "\");"; buff ~= "}"; buff ~= ""; if ( !outToD.empty ) { buff ~= outToD; buff ~= ""; } /* * Casting is needed because some GTK+ functions * can return void pointers or base types. */ if ( returnOwnership == GirTransferOwnership.Full && strct.getAncestor().name == "ObjectG" ) buff ~= "this(cast(" ~ strct.cType ~ "*) p, true);"; else buff ~= "this(cast(" ~ strct.cType ~ "*) p);"; return buff; } else if ( isStringType(returnType) ) { if ( outToD.empty && !throws && !(returnOwnership == GirTransferOwnership.Full) ) { if ( isStringArray(returnType) ) buff ~= "return Str.toStringArray(" ~ gtkCall ~");"; else buff ~= "return Str.toString(" ~ gtkCall ~");"; return buff; } buff ~= "auto retStr = "~ gtkCall ~";"; if ( throws ) { buff ~= throwGException; } buff ~= ""; if ( !outToD.empty ) { buff ~= outToD; buff ~= ""; } if ( returnOwnership == GirTransferOwnership.Full ) { if ( isStringArray(returnType) ) buff ~= "scope(exit) Str.freeStringArray(retStr);"; else buff ~= "scope(exit) Str.freeString(retStr);"; } string len = lenId(returnType); if ( !len.empty ) len = ", "~ len; if ( isStringArray(returnType) ) buff ~= "return Str.toStringArray(retStr"~ len ~");"; else buff ~= "return Str.toString(retStr"~ len ~");"; return buff; } else if ( isDType(returnDType) ) { buff ~= "auto p = "~ gtkCall ~";"; if ( throws ) { buff ~= throwGException; } if ( !outToD.empty ) { buff ~= ""; buff ~= outToD; } buff ~= ""; buff ~= "if(p is null)"; buff ~= "{"; buff ~= "return null;"; buff ~= "}"; buff ~= ""; if ( returnType.isArray() ) { buff ~= returnDType.name ~"[] arr = new "~ returnDType.name ~"["~ lenId(returnType) ~"];"; buff ~= "for(int i = 0; i < "~ lenId(returnType) ~"; i++)"; buff ~= "{"; if ( returnType.elementType.cType.endsWith("*") ) buff ~= "\tarr[i] = "~ construct(returnType.elementType.name) ~"(cast("~ returnType.elementType.cType ~") p[i]);"; else buff ~= "\tarr[i] = "~ construct(returnType.elementType.name) ~"(cast("~ returnType.elementType.cType ~"*) &p[i]);"; buff ~= "}"; buff ~= ""; buff ~= "return arr;"; } else { if ( returnOwnership == GirTransferOwnership.Full && !(returnDType.pack.name == "cairo") ) buff ~= "return "~ construct(returnType.name) ~"(cast("~ returnDType.cType ~"*) p, true);"; else buff ~= "return "~ construct(returnType.name) ~"(cast("~ returnDType.cType ~"*) p);"; } return buff; } else { if ( returnType.name == "gboolean" ) gtkCall ~= " != 0"; if ( !returnType.isArray && outToD.empty && !throws ) { buff ~= "return "~ gtkCall ~";"; return buff; } buff ~= "auto p = "~ gtkCall ~";"; if ( throws ) { buff ~= throwGException; } if ( !outToD.empty ) { buff ~= ""; buff ~= outToD; } buff ~= ""; if ( returnType.isArray() ) { if ( returnType.elementType.name == "gboolean" ) { buff ~= "bool[] r = new bool["~ lenId(returnType) ~"];"; buff ~= "for(size_t i = 0; i < "~ lenId(returnType) ~"; i++)"; buff ~= "{"; buff ~= "r[i] = p[i] != 0;"; buff ~= "}"; buff ~= "return r;"; } else if ( returnType.elementType.cType.empty && returnType.cType[0..$-1] != returnType.elementType.name ) { buff ~= "return cast("~ getType(returnType) ~")p[0 .. "~ lenId(returnType) ~"];"; } else { buff ~= "return p[0 .. "~ lenId(returnType) ~"];"; } } else buff ~= "return p;"; return buff; } assert(false, "Unexpected function: "~ name); } string getSignalName() { assert(type == GirFunctionType.Signal); char pc; string signalName; foreach ( size_t count, char c; name ) { if ( count == 0 ) { signalName ~= toUpper(c); } else { if ( c!='-' && c!='_' ) { if ( pc=='-' || pc=='_' ) signalName ~= toUpper(c); else signalName ~= c; } } pc = c; } if ( !signalName.among("MapEvent", "UnmapEvent", "DestroyEvent") && endsWith(signalName, "Event") ) { signalName = signalName[0..signalName.length-5]; } return signalName; } string getDelegateWrapperName() { return "On" ~ getSignalName() ~ "DelegateWrapper"; } string[] getDelegateWrapperDeclaration() { assert(type == GirFunctionType.Signal); string[] buff; buff ~= "protected class "~ getDelegateWrapperName(); buff ~= "{"; buff ~= "static "~ getDelegateWrapperName() ~"[] listeners;"; buff ~= getDelegateDecleration() ~" dlg;"; buff ~= "gulong handlerId;"; buff ~= ""; buff ~= "this("~ getDelegateDecleration() ~" dlg)"; buff ~= "{"; buff ~= "this.dlg = dlg;"; buff ~= "this.listeners ~= this;"; buff ~= "}"; buff ~= ""; buff ~= "void remove("~ getDelegateWrapperName ~" source)"; buff ~= "{"; buff ~= "foreach(index, wrapper; listeners)"; buff ~= "{"; buff ~= "if (wrapper.handlerId == source.handlerId)"; buff ~= "{"; buff ~= "listeners[index] = null;"; buff ~= "listeners = std.algorithm.remove(listeners, index);"; buff ~= "break;"; buff ~= "}"; buff ~= "}"; buff ~= "}"; buff ~= "}"; return buff; } string getDelegateDecleration() { assert(type == GirFunctionType.Signal); string buff = getType(returnType) ~ " delegate("; foreach ( param; params ) { //TODO: Signals with arrays. if ( param.type.cType == "gpointer" && param.type.isArray() ) buff ~= "void*, "; else buff ~= getType(param.type) ~ ", "; } if ( strct.type == GirStructType.Interface ) buff ~= strct.name ~"IF)"; else buff ~= strct.name ~")"; return buff; } string[] getAddListenerDeclaration() { string[] buff; writeDocs(buff); buff ~= "gulong addOn"~ getSignalName() ~"("~ getDelegateDecleration() ~" dlg, ConnectFlags connectFlags=cast(ConnectFlags)0)"; return buff; } string[] getAddListenerBody() { string[] buff; string realName = name; if ( name.endsWith("-generic-event") ) realName = name[0..$-14]; buff ~= "{"; if ( strct.hasFunction("add_events") ) { switch ( realName ) { case "button-press-event": buff ~= "addEvents(EventMask.BUTTON_PRESS_MASK);"; break; case "button-release-event": buff ~= "addEvents(EventMask.BUTTON_RELEASE_MASK);"; break; case "enter-notify-event": buff ~= "addEvents(EventMask.ENTER_NOTIFY_MASK);"; break; case "focus-in-event": buff ~= "addEvents(EventMask.FOCUS_CHANGE_MASK);"; break; case "focus-out-event": buff ~= "addEvents(EventMask.FOCUS_CHANGE_MASK);"; break; case "key-press-event": buff ~= "addEvents(EventMask.KEY_PRESS_MASK);"; break; case "key-release-event": buff ~= "addEvents(EventMask.KEY_RELEASE_MASK);"; break; case "leave-notify-event": buff ~= "addEvents(EventMask.LEAVE_NOTIFY_MASK);"; break; case "motion-notify-event": buff ~= "addEvents(EventMask.POINTER_MOTION_MASK);"; break; case "property-notify-event": buff ~= "addEvents(EventMask.PROPERTY_CHANGE_MASK);"; break; case "proximity-in-event": buff ~= "addEvents(EventMask.PROXIMITY_IN_MASK);"; break; case "proximity-out-event": buff ~= "addEvents(EventMask.PROXIMITY_OUT_MASK);"; break; case "scroll-event": buff ~= "addEvents(EventMask.SCROLL_MASK);"; break; case "visibility-notify-event": buff ~= "addEvents(EventMask.VISIBILITY_NOTIFY_MASK);"; break; default: break; } } buff ~= "auto wrapper = new "~ getDelegateWrapperName() ~"(dlg);"; buff ~= "wrapper.handlerId = Signals.connectData("; buff ~= "this,"; buff ~= "\""~ realName ~"\","; buff ~= "cast(GCallback)&callBack"~ getSignalName() ~","; buff ~= "cast(void*)wrapper,"; buff ~= "cast(GClosureNotify)&callBack" ~ getSignalName() ~ "Destroy,"; buff ~= "connectFlags);"; buff ~= "return wrapper.handlerId;"; buff ~= "}"; buff ~= "\n"; return buff; } string[] getSignalCallback() { string[] buff; string type = getType(returnType); GirStruct dType = strct.pack.getStruct(returnType.name); if ( dType ) type = dType.cType ~"*"; buff ~= "extern(C) static "~ (type == "bool" ? "int" : type) ~" callBack"~ getSignalName() ~"("~ getCallbackParams() ~")"; buff ~= "{"; if (type == "void") { buff ~= "wrapper.dlg("~ getCallbackVars() ~");"; } else if (dType) { buff ~= "auto r = wrapper.dlg("~ getCallbackVars() ~");"; buff ~= "return r."~ dType.getHandleFunc() ~"();"; } else { buff ~= "return wrapper.dlg("~ getCallbackVars() ~");"; } buff ~= "}"; buff ~= "\n"; return buff; } string[] getSignalDestroyCallback() { string[] buff; buff ~= "extern(C) static void callBack"~ getSignalName() ~"Destroy(" ~ getDelegateWrapperName() ~ " wrapper, GClosure* closure)"; buff ~= "{"; buff ~= "wrapper.remove(wrapper);"; buff ~= "}"; return buff; } void writeDocs(ref string[] buff) { if ( (doc || returnType.doc) && wrapper.includeComments ) { buff ~= "/**"; foreach ( line; doc.splitLines() ) buff ~= " * "~ line.strip(); if ( !params.empty || (instanceParam && type == GirFunctionType.Constructor) ) { buff ~= " *"; buff ~= " * Params:"; if ( type == GirFunctionType.Constructor && instanceParam && !instanceParam.doc.empty ) { string[] lines = instanceParam.doc.splitLines(); buff ~= " * "~ tokenToGtkD(instanceParam.name, wrapper.aliasses, localAliases()) ~" = "~ lines[0]; foreach( line; lines[1..$] ) buff ~= " * "~ line.strip(); } foreach ( param; params ) { if ( param.doc.empty ) continue; if ( returnType.length > -1 && param == params[returnType.length] ) continue; if ( isInstanceParam(param) ) continue; string[] lines = param.doc.splitLines(); buff ~= " * "~ tokenToGtkD(param.name, wrapper.aliasses, localAliases()) ~" = "~ lines[0]; foreach( line; lines[1..$] ) buff ~= " * "~ line.strip(); } if ( buff.endsWith(" * Params:") ) buff = buff[0 .. $-2]; } if ( returnType.doc ) { string[] lines = returnType.doc.splitLines(); if ( doc ) buff ~= " *"; buff ~= " * Returns: "~ lines[0]; foreach( line; lines[1..$] ) buff ~= " * "~ line.strip(); } if ( libVersion ) { buff ~= " *"; buff ~= " * Since: "~ libVersion; } if ( throws || type == GirFunctionType.Constructor ) buff ~= " *"; if ( throws ) buff ~= " * Throws: GException on failure."; if ( type == GirFunctionType.Constructor ) buff ~= " * Throws: ConstructionException GTK+ fails to create the object."; buff ~= " */"; } else if ( wrapper.includeComments ) { buff ~= "/** */\n"; } } private void resolveLength() { foreach( param; params ) { if ( param.type.length > -1 ) params[param.type.length].lengthFor = param; } } private string[string] localAliases() { if ( strct ) return strct.aliases; return null; } /** * Get an string representation of the type. */ private string getType(GirType type, GirParamDirection direction = GirParamDirection.Default) { if ( isStringType(type) ) { if ( direction != GirParamDirection.Default && !type.cType.endsWith("**") ) return "char[]"; else if ( direction == GirParamDirection.Default && type.cType.endsWith("***") ) return "string[][]"; else if ( type.isArray && isStringArray(type.elementType, direction) ) return getType(type.elementType, direction) ~"[]"; else if ( isStringArray(type, direction) ) return "string[]"; return "string"; } else if ( type.isArray() ) { string size; //Special case for GBytes and GVariant. if ( type.cType == "gconstpointer" && type.elementType.cType == "gconstpointer" ) return "void[]"; if ( type.cType == "guchar*" ) return "char[]"; if ( type.size > -1 ) size = to!string(type.size); string elmType = getType(type.elementType, direction); if ( elmType == type.cType ) elmType = elmType[0..$-1]; return elmType ~"["~ size ~"]"; } else if ( !type.elementType && type.zeroTerminated ) { return getType(type, GirParamDirection.Out) ~"[]"; } else { if ( type is null || type.name == "none" ) return "void"; else if ( type.name in strct.structWrap ) return strct.structWrap[type.name]; else if ( type.name == type.cType ) return stringToGtkD(type.name, wrapper.aliasses, localAliases()); GirStruct dType = strct.pack.getStruct(type.name); if ( isDType(dType) ) { if ( dType.type == GirStructType.Interface ) return dType.name ~"IF"; else return dType.name; } else if ( type.cType.empty && dType && dType.type == GirStructType.Record ) return dType.cType ~ "*"; } if ( type.cType.empty ) { if ( auto enum_ = strct.pack.getEnum(type.name) ) return enum_.cName; return stringToGtkD(type.name, wrapper.aliasses, localAliases()); } if ( direction != GirParamDirection.Default ) return stringToGtkD(type.cType[0..$-1], wrapper.aliasses, localAliases()); return stringToGtkD(type.cType, wrapper.aliasses, localAliases()); } private bool isDType(GirStruct dType) { if ( dType is null ) return false; if ( dType.type.among(GirStructType.Class, GirStructType.Interface) ) return true; if ( dType.type == GirStructType.Record && (dType.lookupClass || dType.lookupInterface) ) return true; return false; } private bool isStringType(GirType type) { if ( type.cType.startsWith("gchar*", "char*", "const(char)*") ) return true; if ( type.name.among("utf8", "filename") ) return true; if ( type.isArray() && type.elementType.cType.startsWith("gchar", "char", "const(char)") ) return true; return false; } private bool isStringArray(GirType type, GirParamDirection direction = GirParamDirection.Default) { if ( direction == GirParamDirection.Default && type.cType.endsWith("**") ) return true; if ( type.elementType is null ) return false; if ( !type.elementType.cType.endsWith("*") ) return false; if ( direction != GirParamDirection.Default && type.cType.among("char**", "gchar**", "guchar**") ) return false; return true; } private bool isInstanceParam(GirParam param) { if ( param !is params[0] ) return false; if ( strct is null || strct.type != GirStructType.Record ) return false; if ( !(strct.lookupClass || strct.lookupInterface) ) return false; if ( param.direction != GirParamDirection.Default ) return false; if ( param.lengthFor !is null ) return false; if ( strct.cType is null ) return false; if ( param.type.cType == strct.cType ~"*" ) return true; return false; } private string lenId(GirType type, string paramName = "p") { if ( type.length > -1 ) return tokenToGtkD(params[type.length].name, wrapper.aliasses, localAliases()); //The c function returns the length. else if ( type.length == -2 ) return "p"; else if ( type.size > -1 ) return to!string(type.size); if ( isStringType(type) ) return null; return "getArrayLength("~ paramName ~")"; } /** * Is this function a static function. */ private bool isStatic() { if ( strct.noNamespace ) return false; if ( type == GirFunctionType.Function && !(!params.empty && isInstanceParam(params[0])) ) return true; if ( type == GirFunctionType.Method && strct.isNamespace() ) return true; return false; } /** * Check if any of the ancestors contain the function functionName. */ private bool checkOverride() { if ( name == "get_type" ) return false; if ( name == "to_string" && params.empty ) return true; GirStruct ancestor = strct.getParent(); while(ancestor) { if ( name in ancestor.functions && name !in strct.aliases ) { GirFunction func = ancestor.functions[name]; if ( !(func.noCode || func.isVariadic() || func.type == GirFunctionType.Callback) && paramsEqual(func) ) return true; } ancestor = ancestor.getParent(); } return false; } /** * Return true if the params of func match the params of this function. */ private bool paramsEqual(GirFunction func) { if ( params.length != func.params.length ) return false; foreach ( i, param; params ) { if ( getType(param.type) != getType(func.params[i].type) ) return false; } return true; } private string construct(string type) { GirStruct dType = strct.pack.getStruct(type); debug assert(dType, "Only call construct for valid GtkD types"); string name = dType.name; if ( type in strct.structWrap ) name = strct.structWrap[type]; if ( dType.pack.name.among("cairo", "glib", "gthread") ) return "new "~name; else if( dType.type == GirStructType.Interface ) return "ObjectG.getDObject!("~ name ~", "~ name ~"IF)"; else return "ObjectG.getDObject!("~ name ~")"; } private string getCallbackParams() { string buff; buff = strct.cType ~"* "~ strct.name.toLower() ~"Struct"; foreach( param; params ) { if ( auto par = strct.pack.getStruct(param.type.name) ) buff ~= stringToGtkD(", "~ par.cType ~"* "~ param.name, wrapper.aliasses, localAliases()); else if ( auto enum_ = strct.pack.getEnum(param.type.name) ) buff ~= stringToGtkD(", "~ enum_.cName ~" "~ param.name, wrapper.aliasses, localAliases()); else if ( !param.type.cType.empty ) buff ~= stringToGtkD(", "~ param.type.cType ~" "~ param.name, wrapper.aliasses, localAliases()); else buff ~= stringToGtkD(", "~ param.type.name ~" "~ param.name, wrapper.aliasses, localAliases()); } buff ~= ", " ~ getDelegateWrapperName() ~ " wrapper"; return buff; } private string getCallbackVars() { string buff; foreach( i, param; params ) { if ( i > 0 ) buff ~= ", "; GirStruct par = strct.pack.getStruct(param.type.name); if ( isDType(par) ) { buff ~= construct(param.type.name) ~"("~ tokenToGtkD(param.name, wrapper.aliasses, localAliases()) ~")"; } else if ( isStringType(param.type) ) { if ( isStringArray(param.type) ) buff ~= "Str.toStringArray("~ tokenToGtkD(param.name, wrapper.aliasses, localAliases()) ~")"; else buff ~= "Str.toString("~ tokenToGtkD(param.name, wrapper.aliasses, localAliases()) ~")"; } else { buff ~= tokenToGtkD(param.name, wrapper.aliasses, localAliases()); } } if ( !buff.empty ) buff ~= ", "; buff ~= "wrapper.outer"; return buff; } } enum GirParamDirection : string { Default = "", Out = "out", InOut = "inout", } final class GirParam { string doc; string name; GirType type; GirTransferOwnership ownership = GirTransferOwnership.None; GirParamDirection direction = GirParamDirection.Default; GirParam lengthFor; GirWrapper wrapper; this(GirWrapper wrapper) { this.wrapper = wrapper; } void parse(T)(XMLReader!T reader) { name = reader.front.attributes["name"]; if ( "transfer-ownership" in reader.front.attributes ) ownership = cast(GirTransferOwnership)reader.front.attributes["transfer-ownership"]; if ( "direction" in reader.front.attributes ) direction = cast(GirParamDirection)reader.front.attributes["direction"]; reader.popFront(); while( !reader.empty && !reader.endTag("parameter", "instance-parameter") ) { if ( reader.front.type == XMLNodeType.EndTag ) { reader.popFront(); continue; } switch(reader.front.value) { case "doc": reader.popFront(); doc ~= reader.front.value; reader.popFront(); break; case "doc-deprecated": reader.popFront(); doc ~= "\n\nDeprecated: "~ reader.front.value; reader.popFront(); break; case "array": case "type": type = new GirType(wrapper); type.parse(reader); break; case "varargs": type = new GirType(wrapper); type.name = "..."; type.cType = "..."; break; default: throw new XMLException(reader, "Unexpected tag: "~ reader.front.value ~" in GirParam: "~ name); } reader.popFront(); } } } gir-to-d-0.10.0/source/gtd/GirPackage.d000066400000000000000000000370371311631112600174370ustar00rootroot00000000000000/* * This file is part of gtkD. * * gtkD is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version, with * some exceptions, please read the COPYING file. * * gtkD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with gtkD; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA */ module gtd.GirPackage; import std.algorithm; import std.array : join; import std.conv; import std.file; import std.path; import std.range : array, back, empty; import std.regex : ctRegex, matchFirst; import std.stdio; import std.string : split, splitLines, strip; import std.uni; import gtd.GirAlias; import gtd.GirEnum; import gtd.GirFunction; import gtd.GirStruct; import gtd.GirVersion; import gtd.GirWrapper; import gtd.IndentedStringBuilder; import gtd.XMLReader; import gtd.LinkedHasMap: Map = LinkedHashMap; class GirPackage { string name; string cTypePrefix; string srcDir; GirVersion _version; GirWrapper wrapper; string[] lookupAliases; /// Aliases defined in the lookupfile. string[] lookupEnums; /// Enums defined in the lookupfile. string[] lookupStructs; /// Structs defined in the lookupfile. string[] lookupFuncts; /// Functions defined in the lookupfile. string[] lookupConstants; /// Constants defined in the lookupfile. static GirPackage[string] namespaces; string[] libraries; Map!(string, GirAlias) collectedAliases; /// Aliases defined in the gir file. Map!(string, GirEnum) collectedEnums; /// Enums defined in the gir file. Map!(string, GirStruct) collectedStructs; Map!(string, GirFunction) collectedCallbacks; Map!(string, GirFunction) collectedFunctions; GirEnum stockIDs; /// The StockID enum (Deprecated). GirEnum GdkKeys; /// The GdkKey enum. public this(string pack, GirWrapper wrapper, string srcDir) { this.name = pack; this.wrapper = wrapper; this.srcDir = srcDir; this.stockIDs = new GirEnum(wrapper, this); this.GdkKeys = new GirEnum(wrapper, this); try { if ( !exists(buildPath(wrapper.outputRoot, srcDir, pack)) ) mkdirRecurse(buildPath(wrapper.outputRoot, srcDir, pack)); } catch (Exception) { throw new Exception("Failed to create directory: "~ buildPath(wrapper.outputRoot, srcDir, pack)); } try { if ( !exists(buildPath(wrapper.outputRoot, srcDir, pack, "c")) ) mkdirRecurse(buildPath(wrapper.outputRoot, srcDir, pack, "c")); } catch (Exception) { throw new Exception("Failed to create directory: "~ buildPath(wrapper.outputRoot, srcDir, pack, "c")); } } void parseGIR(string girFile) { auto reader = new XMLReader!string(readText(girFile), girFile); while ( !reader.empty && reader.front.value != "repository" ) reader.popFront(); reader.popFront(); while ( !reader.empty && reader.front.value == "include" ) { //TODO: parse imports. reader.popFront(); } while ( !reader.empty && reader.front.value != "namespace" ) reader.popFront(); namespaces[reader.front.attributes["name"]] = this; checkVersion(reader.front.attributes["version"]); cTypePrefix = reader.front.attributes["c:identifier-prefixes"]; libraries ~= reader.front.attributes["shared-library"].split(','); version(OSX) libraries = sort(libraries).uniq.map!(a => baseName(a)).array; else libraries = sort(libraries).uniq.array; reader.popFront(); while ( !reader.empty && !reader.endTag("namespace") ) { if ( reader.front.type == XMLNodeType.EndTag ) { reader.popFront(); continue; } switch (reader.front.value) { case "alias": GirAlias gtkAlias = new GirAlias(wrapper); gtkAlias.parse(reader); if ( gtkAlias.cType == "GType" ) break; collectedAliases[gtkAlias.name] = gtkAlias; break; case "glib:boxed": reader.skipTag(); break; case "bitfield": case "enumeration": GirEnum gtkEnum = new GirEnum(wrapper, this); gtkEnum.parse(reader); collectedEnums[gtkEnum.name] = gtkEnum; break; case "class": case "interface": case "record": case "union": GirStruct gtkStruct = new GirStruct(wrapper, this); gtkStruct.parse(reader); //Workaround: Dont overwrite the regular pango classes. if ( gtkStruct.cType.among("PangoCairoFont", "PangoCairoFontMap") ) { collectedStructs["FcFontMap"].merge(gtkStruct); break; } collectedStructs[gtkStruct.name] = gtkStruct; if ( name == "pango" ) gtkStruct.name = "Pg"~gtkStruct.name; break; case "callback": GirFunction callback = new GirFunction(wrapper, null); callback.parse(reader); collectedCallbacks[callback.name] = callback; break; case "constant": parseConstant(reader); break; case "function": parseFunction(reader); break; default: throw new XMLException(reader, "Unexpected tag: "~ reader.front.value ~" in GirPackage: "~ name); } reader.popFront(); } } void parseConstant(T)(XMLReader!T reader) { if ( reader.front.attributes["name"].startsWith("STOCK_") ) { GirEnumMember member = GirEnumMember(wrapper); member.parse(reader); member.name = member.name[6..$]; stockIDs.members ~= member; return; } else if ( reader.front.attributes["c:type"].startsWith("GDK_KEY_") ) { GirEnumMember member = GirEnumMember(wrapper); member.parse(reader); member.name = "GDK_"~ member.name[4..$]; GdkKeys.members ~= member; return; } // The version attribute of the namspace tag is usualy set to MAJOR.0. else if ( reader.front.attributes["name"].startsWith("MAJOR_VERSION") ) { _version.major = to!uint(reader.front.attributes["value"]); } else if ( reader.front.attributes["name"].startsWith("MINOR_VERSION") ) { _version.minor = to!uint(reader.front.attributes["value"]); } else if ( reader.front.attributes["name"].startsWith("MICRO_VERSION") ) { _version.micro = to!uint(reader.front.attributes["value"]); } //TODO: other constants. reader.skipTag(); } void parseFunction(T)(XMLReader!T reader) { GirFunction funct = new GirFunction(wrapper, null); funct.parse(reader); collectedFunctions[funct.name] = funct; checkVersion(funct.libVersion); } GirStruct getStruct(string name) { GirPackage pack = this; if ( name.canFind(".") ) { string[] vals = name.split("."); if ( vals[0] !in namespaces ) return null; pack = namespaces[vals[0]]; name = vals[1]; } return pack.collectedStructs.get(name, pack.collectedStructs.get("lookup"~name, null)); } GirEnum getEnum(string name) { GirPackage pack = this; if ( name.canFind(".") ) { string[] vals = name.split("."); if ( vals[0] !in namespaces ) return null; pack = namespaces[vals[0]]; name = vals[1]; } return pack.collectedEnums.get(name, null); } void checkVersion(string _version) { if (this._version < _version) this._version = GirVersion(_version); } void checkVersion(GirVersion _version) { if (this._version < _version) this._version = _version; } void writeClasses() { foreach ( strct; collectedStructs ) strct.writeClass(); } void writeTypes() { string buff = wrapper.licence; auto indenter = new IndentedStringBuilder(); buff ~= "module "~ name ~".c.types;\n\n"; buff ~= indenter.format(lookupAliases); foreach ( a; collectedAliases ) { buff ~= "\n"; buff ~= indenter.format(a.getAliasDeclaration()); } buff ~= indenter.format(lookupEnums); foreach ( e; collectedEnums ) { buff ~= "\n"; buff ~= indenter.format(e.getEnumDeclaration()); } buff ~= indenter.format(lookupStructs); foreach ( s; collectedStructs ) { if ( s.noExternal || s.noDecleration ) continue; buff ~= "\n"; buff ~= indenter.format(s.getStructDeclaration()); } buff ~= indenter.format(lookupFuncts); foreach ( f; collectedCallbacks ) { buff ~= "\n"; buff ~= indenter.format(f.getCallbackDeclaration()); } buff ~= indenter.format(lookupConstants); if ( stockIDs.members !is null ) { stockIDs.cName = "StockID"; stockIDs.doc = "StockIds"; buff ~= "\n"; buff ~= indenter.format(stockIDs.getEnumDeclaration()); } if ( GdkKeys.members !is null ) writeGdkKeys(); std.file.write(buildPath(wrapper.outputRoot, srcDir, name, "c/types.d"), buff); } void writeGdkKeys() { string buff = wrapper.licence; buff ~= "module "~ name ~".Keysyms;\n\n"; buff ~= "/**\n"; buff ~= " * GdkKeysyms.\n"; buff ~= " */\n"; buff ~= "public enum GdkKeysyms\n"; buff ~= "{\n"; foreach ( member; GdkKeys.members ) { buff ~= "\t"~ tokenToGtkD(member.name, wrapper.aliasses, false) ~" = "~ member.value ~",\n"; } buff ~= "}\n"; std.file.write(buildPath(wrapper.outputRoot, srcDir, name, "Keysyms.d"), buff); } void writeLoaderTable() { string buff = wrapper.licence; buff ~= "module "~ name ~".c.functions;\n\n"; buff ~= "import std.stdio;\n"; buff ~= "import "~ name ~".c.types;\n"; if ( name == "glib" ) buff ~= "import gobject.c.types;\n"; if ( name == "gdk" || name == "pango" ) buff ~= "import cairo.c.types;\n"; buff ~= "import gtkd.Loader;\n\n"; buff ~= getLibraries(); buff ~= "\n\nshared static this()\n{"; foreach ( strct; collectedStructs ) { if ( strct.functions.empty || strct.noExternal ) continue; buff ~= "\n\t// "~ name ~"."~ strct.name ~"\n\n"; foreach ( funct; strct.functions ) { if ( funct.type == GirFunctionType.Callback || funct.type == GirFunctionType.Signal || funct.name.empty ) continue; buff ~= "\tLinker.link("~ funct.cType ~", \""~ funct.cType ~"\", LIBRARY_"~ name.toUpper() ~");\n"; } } //WORKAROUND: Windows has two functions with different names in the 32 and 64 bit versions. if (name == "glib") { buff ~= "\n\tversion(Win64)\n"; buff ~= "\t{\n"; buff ~= "\t\tLinker.link(g_module_name, \"g_module_name_uft8\", LIBRARY.GLIB, LIBRARY.GMODULE);\n"; buff ~= "\t\tLinker.link(g_module_open, \"g_module_open_utf8\", LIBRARY.GLIB, LIBRARY.GMODULE);\n"; buff ~= "\t}\n"; } buff ~= "}\n\n" ~ "__gshared extern(C)\n" ~ "{\n"; foreach ( strct; collectedStructs ) { if ( strct.functions.empty || strct.noExternal ) continue; buff ~= "\n\t// "~ name ~"."~ strct.name ~"\n\n"; foreach ( funct; strct.functions ) { if ( funct.type == GirFunctionType.Callback || funct.type == GirFunctionType.Signal || funct.name.empty ) continue; buff ~= "\t"~ funct.getLinkerExternal() ~"\n"; } } buff ~= "}\n\n"; foreach ( strct; collectedStructs ) { if ( strct.functions.empty || strct.noExternal ) continue; buff ~= "\n// "~ name ~"."~ strct.name ~"\n\n"; foreach ( funct; strct.functions ) { if ( funct.type == GirFunctionType.Callback || funct.type == GirFunctionType.Signal || funct.name.empty ) continue; if (name == "glgdk") buff ~= "alias glc_"~ funct.cType ~" "~ funct.cType ~";\n"; else buff ~= "alias c_"~ funct.cType ~" "~ funct.cType ~";\n"; } } std.file.write(buildPath(wrapper.outputRoot, srcDir, name, "c", "functions.d"), buff); } void writeExternalFunctions() { string buff = wrapper.licence; buff ~= "module "~ name ~".c.functions;\n\n"; buff ~= "import std.stdio;\n"; buff ~= "import "~ name ~".c.types;\n"; if ( name == "glib" ) buff ~= "import gobject.c.types;\n"; if ( name == "gdk" || name == "pango" ) buff ~= "import cairo.c.types;\n\n"; buff ~= getLibraries(); buff ~= "\n\n__gshared extern(C)\n" ~ "{\n"; foreach ( strct; collectedStructs ) { if ( strct.functions.empty || strct.noExternal ) continue; buff ~= "\n\t// "~ name ~"."~ strct.name ~"\n\n"; foreach ( funct; strct.functions ) { if ( funct.type == GirFunctionType.Callback || funct.type == GirFunctionType.Signal || funct.name.empty ) continue; buff ~= "\t"~ funct.getExternal() ~"\n"; } } buff ~= "}"; std.file.write(buildPath(wrapper.outputRoot, srcDir, name, "c", "functions.d"), buff); } private string getLibraries() { string lib = "version (Windows)\n\t"; lib ~= "static immutable LIBRARY_"~ name.toUpper() ~" = ["~ getDllNames() ~"];"; lib ~= "\nelse version (OSX)\n\t"; lib ~= "static immutable LIBRARY_"~ name.toUpper() ~" = ["~ getDylibNames() ~"];"; lib ~= "\nelse\n\t"; lib ~= "static immutable LIBRARY_"~ name.toUpper() ~" = ["~ getSoNames() ~"];"; return lib; } private auto dllRegex = ctRegex!(`([a-z0-9_]+)(-[0-9\.]+)?(-[0-9]+)?\.dll`); private auto dylibRegex = ctRegex!(`([a-z0-9_]+)(-[0-9\.]+?)?(\.[0-9]+)?\.dylib`); private auto soRegex = ctRegex!(`([a-z0-9_]+)(-[0-9\.]+)?\.so(\.[0-9]+)?`); private string getDllNames() { version (Windows) { return "\""~ libraries.join("\", \"") ~"\""; } else version (OSX) { string libs; foreach ( lib; libraries ) { auto match = matchFirst(lib, dylibRegex); libs ~= "\""~ match[1]; if ( !match[2].empty ) libs ~= "-"~ match[2][1..$]; if ( !match[3].empty ) libs ~= "-"~ match[3][1..$]; libs ~= ".dll\""; if ( lib != libraries.back ) libs ~= ", "; } return libs; } else { string libs; foreach ( lib; libraries ) { auto match = matchFirst(lib, soRegex); libs ~= "\""~ match[1]; if ( !match[2].empty ) libs ~= "-"~ match[2][1..$]; if ( !match[3].empty ) libs ~= "-"~ match[3][1..$]; libs ~= ".dll\""; if ( lib != libraries.back ) libs ~= ", "; } return libs; } } private string getDylibNames() { version (Windows) { string libs; foreach ( lib; libraries ) { auto match = matchFirst(lib, dllRegex); libs ~= "\""~ match[1]; if ( !match[2].empty ) libs ~= "-"~ match[2][1..$]; if ( !match[3].empty ) libs ~= "."~ match[3][1..$]; libs ~= ".dylib\""; if ( lib != libraries.back ) libs ~= ", "; } return libs; } else version (OSX) { return "\""~ libraries.join("\", \"") ~"\""; } else { string libs; foreach ( lib; libraries ) { auto match = matchFirst(lib, soRegex); libs ~= "\""~ match[1]; if ( !match[2].empty ) libs ~= "-"~ match[2][1..$]; if ( !match[3].empty ) libs ~= "."~ match[3][1..$]; libs ~= ".dylib\""; if ( lib != libraries.back ) libs ~= ", "; } return libs; } } private string getSoNames() { version (Windows) { string libs; foreach ( lib; libraries ) { auto match = matchFirst(lib, dllRegex); libs ~= "\""~ match[1]; if ( !match[2].empty && !match[3].empty ) libs ~= "-"~ match[2][1..$]; libs ~= ".so"; if ( !match[2].empty && match[3].empty ) libs ~= "."~ match[2][1..$]; if ( !match[3].empty ) libs ~= "."~ match[3][1..$]; libs ~= "\""; if ( lib != libraries.back ) libs ~= ", "; } return libs; } else version (OSX) { string libs; foreach ( lib; libraries ) { auto match = matchFirst(lib, dylibRegex); libs ~= "\""~ match[1]; if ( !match[2].empty ) libs ~= "-"~ match[2][1..$]; libs ~= ".so"; if ( !match[3].empty ) libs ~= "."~ match[3][1..$]; libs ~= "\""; if ( lib != libraries.back ) libs ~= ", "; } return libs; } else { return "\""~ libraries.join("\", \"") ~"\""; } } } gir-to-d-0.10.0/source/gtd/GirStruct.d000066400000000000000000000712161311631112600173650ustar00rootroot00000000000000/* * This file is part of gtkD. * * gtkD is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version, with * some exceptions, please read the COPYING file. * * gtkD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with gtkD; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA */ module gtd.GirStruct; import std.algorithm: among, sort, uniq, startsWith, endsWith, canFind; import std.array : replace; import std.conv; import std.file : write; import std.path: buildPath; import std.uni: toUpper, toLower; import std.range; import std.string: capitalize, splitLines, strip, chomp; import gtd.GirFunction; import gtd.GirPackage; import gtd.GirType; import gtd.GirVersion; import gtd.GirWrapper; import gtd.XMLReader; import gtd.LinkedHasMap: Map = LinkedHashMap; import gtd.IndentedStringBuilder; enum GirStructType : string { Class = "class", Interface = "interface", Record = "record", Union = "union" } final class GirStruct { string name; GirStructType type; string doc; string cType; string parent; string libVersion; bool lookupClass = false; bool lookupInterface = false; bool lookupParent = false; // is the parent set with the lookup file. bool noCode = false; bool noDecleration = false; bool noExternal = false; bool noNamespace = false; string[string] structWrap; string[string] aliases; string[] lookupCode; string[] lookupInterfaceCode; string[] implements; string[] imports; GirField[] fields; string[] virtualFunctions; Map!(string, GirFunction) functions; GirWrapper wrapper; GirPackage pack; private GirStruct parentStruct; this(GirWrapper wrapper, GirPackage pack) { this.wrapper = wrapper; this.pack = pack; } GirStruct dup() { GirStruct copy = new GirStruct(wrapper, pack); foreach ( i, field; this.tupleof ) copy.tupleof[i] = field; return copy; } void parse(T)(XMLReader!T reader) { name = reader.front.attributes["name"]; type = cast(GirStructType)reader.front.value; if ( "c:type" in reader.front.attributes ) cType = reader.front.attributes["c:type"]; if ( "parent" in reader.front.attributes ) parent = reader.front.attributes["parent"]; if ( "version" in reader.front.attributes ) { libVersion = reader.front.attributes["version"]; pack.checkVersion(libVersion); } if ( !parent.empty ) { if ( parent == "GObject.InitiallyUnowned" ) parent = "GObject.Object"; else if ( parent == "InitiallyUnowned" ) parent = "Object"; } if ( pack && pack.name != "glib" && "glib:get-type" in reader.front.attributes && reader.front.attributes["glib:get-type"].endsWith("_get_type") ) functions["get_type"] = getTypeFunction(reader.front.attributes["glib:get-type"]); if ( reader.front.type == XMLNodeType.EmptyTag ) return; reader.popFront(); while( !reader.empty && !reader.endTag("class", "interface", "record", "union") ) { switch(reader.front.value) { case "doc": reader.popFront(); doc ~= reader.front.value; reader.popFront(); break; case "doc-deprecated": reader.popFront(); doc ~= "\n\nDeprecated: "~ reader.front.value; reader.popFront(); break; case "field": GirField field = new GirField(wrapper); field.parse(reader); fields ~= field; break; case "record": GirField field = new GirField(wrapper); GirStruct strct = new GirStruct(wrapper, null); strct.parse(reader); strct.cType = strct.cType.toUpper()[0..1] ~ strct.cType[1 .. $]; field.gtkStruct = strct; fields ~= field; break; case "union": GirField field = new GirField(wrapper); GirUnion uni = new GirUnion(wrapper); uni.parse(reader); field.gtkUnion = uni; fields ~= field; break; case "constructor": case "method": case "glib:signal": if ( type == GirStructType.Record ) type = GirStructType.Class; goto case "function"; case "function": GirFunction func = new GirFunction(wrapper, this); func.parse(reader); if ( func.type == GirFunctionType.Signal ) functions[func.name~"-signal"] = func; else functions[func.name] = func; break; case "virtual-method": // Virtual methods in the gir file are mirrored // as regular methods, so we only collect whitch are virtual; virtualFunctions ~= reader.front.attributes["name"]; reader.skipTag(); break; case "implements": implements ~= reader.front.attributes["name"]; break; case "prerequisite": // Determines whitch base class the implementor of an interface must implement. case "property": reader.skipTag(); break; default: throw new XMLException(reader, "Unexpected tag: "~ reader.front.value ~" in GirStruct: "~ name); } reader.popFront(); } foreach( func; virtualFunctions ) { if ( auto vFunc = func in functions ) vFunc.virtual = true; } if ( type == GirStructType.Union ) { GirField field = new GirField(wrapper); GirUnion uni = new GirUnion(wrapper); uni.fields = fields; field.gtkUnion = uni; fields = [field]; //special case for "_Value__data__union" if ( cType.empty ) cType = name; type = GirStructType.Record; foreach ( funct; functions ) { if ( funct.type != GirFunctionType.Function ) type = GirStructType.Class; } } } GirStruct getParent() { if ( !parentStruct ) parentStruct = pack.getStruct(parent); return parentStruct; } string[] getStructDeclaration() { if ( noExternal || cType.empty ) return null; string[] buff; if ( doc !is null && wrapper.includeComments && type == GirStructType.Record ) { buff ~= "/**"; foreach ( line; doc.splitLines() ) buff ~= " * "~ line.strip(); if ( libVersion ) { buff ~= " *"; buff ~= " * Since: "~ libVersion; } buff ~= " */"; } if ( !fields.empty ) { buff ~= "struct "~ tokenToGtkD(cType, wrapper.aliasses); buff ~= "{"; buff ~= GirField.getFieldDeclarations(fields, wrapper); buff ~= "}"; } else { buff ~= "struct "~ tokenToGtkD(cType, wrapper.aliasses) ~";"; } return buff; } void writeClass() { bool[string] ctors; if ( noCode ) return; if ( type == GirStructType.Record && !(lookupClass || lookupInterface) && (functions.empty && lookupCode.empty ) ) return; parentStruct = pack.getStruct(parent); resolveImports(); if ( type == GirStructType.Record && !(lookupClass || lookupInterface) ) { writeDStruct(); return; } if ( isInterface() ) writeInterface(); string buff = wrapper.licence; auto indenter = new IndentedStringBuilder(); if ( isInterface() ) buff ~= "module "~ pack.name ~"."~ name ~"T;\n\n"; else buff ~= "module "~ pack.name ~"."~ name ~";\n\n"; writeImports(buff, isInterface() ); writeDocs(buff); if ( isInterface() ) buff ~= "public template "~ name ~"T(TStruct)"; else buff ~= "public class "~ name; if ( lookupParent && !parentStruct ) buff ~= " : "~ parent; else if ( parentStruct && parentStruct.name != name ) buff ~= " : "~ parentStruct.name; else if ( parentStruct ) buff ~= " : "~ parentStruct.pack.name.capitalize() ~ parentStruct.name; bool first = !parentStruct; foreach ( interf; implements ) { if ( parentStruct && parentStruct.implements.canFind(interf) ) continue; // If the parentStruct is in an different package compare without package name. if ( parentStruct && interf.canFind(".") && parentStruct.implements.canFind(interf.split('.')[1]) ) continue; GirStruct strct = pack.getStruct(interf); if ( strct && first ) { buff ~= " :"; first = false; } else if ( strct ) buff ~= ","; if ( strct ) buff ~= " "~ strct.name ~"IF"; } buff ~= "\n"; buff ~= indenter.format("{"); if ( !cType.empty ) { if ( !isInterface() ) { buff ~= indenter.format("/** the main Gtk struct */"); buff ~= indenter.format("protected "~ cType ~"* "~ getHandleVar() ~";"); if ( !parentStruct ) { buff ~= indenter.format("protected bool ownedRef;"); } buff ~= "\n"; } buff ~= indenter.format("/** Get the main Gtk struct */"); buff ~= indenter.format("public "~ cType ~"* "~ getHandleFunc() ~"(bool transferOwnership = false)"); buff ~= indenter.format("{"); buff ~= indenter.format("if (transferOwnership)"); buff ~= indenter.format("ownedRef = false;"); if ( isInterface() ) buff ~= indenter.format("return cast("~ cType ~"*)getStruct();"); else buff ~= indenter.format("return "~ getHandleVar ~";"); buff ~= indenter.format("}"); buff ~= "\n"; if ( !isInterface() ) { buff ~= indenter.format("/** the main Gtk struct as a void* */"); if ( parentStruct ) buff ~= indenter.format("protected override void* getStruct()"); else buff ~= indenter.format("protected void* getStruct()"); buff ~= indenter.format("{"); buff ~= indenter.format("return cast(void*)"~ getHandleVar ~";"); buff ~= indenter.format("}"); buff ~= "\n"; } if ( !isInterface() && cType != "GObject" && cType != "cairo_t" ) { if ( parentStruct && pack.name != "cairo" ) { buff ~= indenter.format("protected override void setStruct(GObject* obj)"); buff ~= indenter.format("{"); buff ~= indenter.format(getHandleVar ~" = cast("~ cType ~"*)obj;"); buff ~= indenter.format("super.setStruct(obj);"); buff ~= indenter.format("}"); buff ~= "\n"; } buff ~= indenter.format("/**"); buff ~= indenter.format(" * Sets our main struct and passes it to the parent class."); buff ~= indenter.format(" */"); buff ~= indenter.format("public this ("~ cType ~"* "~ getHandleVar() ~", bool ownedRef = false)"); buff ~= indenter.format("{"); buff ~= indenter.format("this."~ getHandleVar() ~" = "~ getHandleVar() ~";"); if ( parentStruct ) buff ~= indenter.format("super(cast("~ parentStruct.cType ~"*)"~ getHandleVar() ~", ownedRef);"); else buff ~= indenter.format("this.ownedRef = ownedRef;"); buff ~= indenter.format("}"); buff ~= "\n"; if ( shouldFree() ) { buff ~= indenter.format("~this ()"); buff ~= indenter.format("{"); if ( wrapper.useRuntimeLinker ) buff ~= indenter.format("if ( Linker.isLoaded(LIBRARY_"~ pack.name.toUpper() ~") && ownedRef )"); else buff ~= indenter.format("if ( ownedRef )"); if ( "unref" in functions ) buff ~= indenter.format(functions["unref"].cType ~"("~ getHandleVar ~");"); else buff ~= indenter.format(functions["free"].cType ~"("~ getHandleVar ~");"); buff ~= indenter.format("}"); buff ~= "\n"; } } foreach ( interf; implements ) { if ( parentStruct && parentStruct.implements.canFind(interf) ) continue; if ( parentStruct && interf.canFind(".") && parentStruct.implements.canFind(interf.split('.')[1]) ) continue; GirStruct strct = pack.getStruct(interf); if ( strct ) { buff ~= indenter.format("// add the "~ strct.name ~" capabilities"); buff ~= indenter.format("mixin "~ strct.name ~"T!("~ cType.chomp("*") ~");"); buff ~= "\n"; } } } if ( !lookupCode.empty ) { buff ~= indenter.format(lookupCode); buff ~= "\n"; buff ~= indenter.format(["/**", "*/"]); } bool firstSignal = true; foreach ( func; functions ) { if ( func.noCode || func.isVariadic() || func.type == GirFunctionType.Callback ) continue; if ( isInterface() && func.type == GirFunctionType.Constructor ) continue; if ( func.type == GirFunctionType.Signal ) { buff ~= "\n"; buff ~= indenter.format(func.getDelegateWrapperDeclaration()); buff ~= "\n"; buff ~= indenter.format(func.getAddListenerDeclaration()); buff ~= indenter.format(func.getAddListenerBody()); buff ~= indenter.format(func.getSignalCallback()); buff ~= indenter.format(func.getSignalDestroyCallback()); foreach ( param; func.params ) { if ( param.type.name.startsWith("Gdk.Event") && param.type.name != "Gdk.Event" ) { buff ~= "\n"; buff ~= indenter.format(getGenericEventSignal(func)); break; } } } else { buff ~= "\n"; buff ~= indenter.format(func.getDeclaration()); buff ~= indenter.format("{"); buff ~= indenter.format(func.getBody()); buff ~= indenter.format("}"); } } buff ~= indenter.format("}"); if ( isInterface() ) write(buildPath(wrapper.outputRoot, pack.srcDir, pack.name, name ~"T.d"), buff); else write(buildPath(wrapper.outputRoot, pack.srcDir, pack.name, name ~".d"), buff); } void writeInterface() { string buff = wrapper.licence; auto indenter = new IndentedStringBuilder(); buff ~= "module "~ pack.name ~"."~ name ~"IF;\n\n"; writeImports(buff); writeDocs(buff); buff ~= "public interface "~ name ~"IF"; buff ~= indenter.format("{"); if ( cType ) { buff ~= indenter.format("/** Get the main Gtk struct */"); buff ~= indenter.format("public "~ cType ~"* "~ getHandleFunc() ~"(bool transferOwnership = false);"); buff ~= "\n"; buff ~= indenter.format("/** the main Gtk struct as a void* */"); buff ~= indenter.format("protected void* getStruct();"); buff ~= "\n"; if ( !lookupInterfaceCode.empty ) { buff ~= indenter.format(lookupInterfaceCode); buff ~= "\n"; buff ~= indenter.format(["/**", "*/"]); } foreach ( func; functions ) { if ( func.noCode || func.isVariadic() || func.type == GirFunctionType.Callback || func.type == GirFunctionType.Constructor ) continue; if ( func.type == GirFunctionType.Signal ) { string[] dec = func.getAddListenerDeclaration(); dec[$-1] ~= ";"; buff ~= "\n"; buff ~= indenter.format(dec); } else { string[] dec = func.getDeclaration(); dec[$-1] = dec[$-1].replace("override ", ""); dec[$-1] ~= ";"; buff ~= "\n"; buff ~= indenter.format(dec); } } buff ~= indenter.format("}"); } write(buildPath(wrapper.outputRoot, pack.srcDir, pack.name, name ~"IF.d"), buff); } void writeDStruct() { string buff = wrapper.licence; auto indenter = new IndentedStringBuilder(); buff ~= "module "~ pack.name ~"."~ name ~";\n\n"; writeImports(buff); writeDocs(buff); if ( !noNamespace ) { buff ~= "public struct "~ name ~"\n"; buff ~= indenter.format("{"); } if ( !lookupCode.empty ) { buff ~= indenter.format(lookupCode); buff ~= "\n"; buff ~= indenter.format(["/**", "*/"]); } foreach ( func; functions ) { if ( func.noCode || func.isVariadic() || !( func.type == GirFunctionType.Function || func.type == GirFunctionType.Method ) ) continue; buff ~= "\n"; buff ~= indenter.format(func.getDeclaration()); buff ~= indenter.format("{"); buff ~= indenter.format(func.getBody()); buff ~= indenter.format("}"); } if ( !noNamespace ) buff ~= indenter.format("}"); write(buildPath(wrapper.outputRoot, pack.srcDir, pack.name, name ~".d"), buff); } /** * Return the variable name the c type is stored in. */ string getHandleVar() { if (cType.length == 0) return ""; string p = to!string(toLower(cType[0])); if ( cType.endsWith("_t") ) { return p ~ cType[1 .. $ - 2]; } else { return p ~ cType[1 .. $]; } } /** * Returns the name of the function that returns the cType. */ string getHandleFunc() { if ( parentStruct && parentStruct.name == name ) return "get"~ cast(char)pack.name[0].toUpper ~ pack.name[1..$] ~ name ~"Struct"; else return "get"~ name ~"Struct"; } bool isInterface() { if ( lookupInterface ) return true; if ( lookupClass ) return false; if ( type == GirStructType.Interface ) return true; return false; } bool isNamespace() { return type == GirStructType.Record && !(lookupClass || lookupInterface) && !noNamespace; } void merge(GirStruct mergeStruct) { foreach ( func; mergeStruct.functions ) { func.strct = this; functions[func.name] = func; } } GirStruct getAncestor() { if ( parent.empty ) return this; if ( !parentStruct ) parentStruct = pack.getStruct(parent); return parentStruct.getAncestor(); } bool hasFunction(string funct) { if ( funct in functions ) return true; if ( parent.empty ) return false; if ( !parentStruct ) parentStruct = pack.getStruct(parent); return parentStruct.hasFunction(funct); } bool shouldFree() { if ( !parent.empty && parent != "Boxed" ) return false; if ( name.among("Object", "Boxed") ) return false; if ( auto u = "unref" in functions ) { if ( u.noCode == false && u.params.empty ) return true; } if ( auto f = "free" in functions ) { if ( f.noCode == false && f.params.empty ) return true; } return false; } private void resolveImports() { if ( parentStruct && parentStruct.name != name) { imports ~= parentStruct.pack.name ~"."~ parentStruct.name; } else if ( parentStruct ) { string QParent = parentStruct.pack.name.capitalize() ~ parentStruct.name; imports ~= parentStruct.pack.name ~"."~ parentStruct.name ~" : "~ QParent ~" = "~ parentStruct.name; structWrap[parent] = QParent; } imports ~= pack.name ~".c.functions"; imports ~= pack.name ~".c.types"; //Temporarily import the old bindDir.*types modules for backwards compatibility. string[string] bindDirs = ["atk": "gtkc", "cairo": "gtkc", "gdk": "gtkc", "gdkpixbuf": "gtkc", "gio": "gtkc", "glib": "gtkc", "gobject": "gtkc", "gtk": "gtkc", "pango": "gtkc", "gsv": "gsvc", "vte": "vtec", "gstinterfaces": "gstreamerc", "gstreamer": "gstreamerc"]; if ( pack.wrapper.useBindDir ) { if ( auto dir = pack.name in bindDirs ) imports ~= *dir ~"."~ pack.name ~"types"; } if ( wrapper.useRuntimeLinker && shouldFree() ) { imports ~= "gtkd.Loader"; } foreach( func; functions ) { if ( func.noCode ) continue; if ( func.throws ) { imports ~= "glib.ErrorG"; imports ~= "glib.GException"; } void getReturnImport(GirType type) { if ( type.name in structWrap || type.name in aliases ) return; GirStruct dType = pack.getStruct(type.name); if ( dType && (dType.type != GirStructType.Record || dType.lookupClass || dType.lookupInterface) ) { if ( !dType.pack.name.among("cairo", "glib", "gthread") ) imports ~= "gobject.ObjectG"; if ( dType.type == GirStructType.Interface && func.name.startsWith("new") ) return; if ( dType is this && dType.type != GirStructType.Interface ) return; imports ~= dType.pack.name ~"."~ dType.name; if ( dType.type == GirStructType.Interface || dType.lookupInterface ) imports ~= dType.pack.name ~"."~ dType.name ~"IF"; } else if ( type.name.among("utf8", "filename") || type.cType.among("guchar**") ) imports ~= "glib.Str"; } if ( func.returnType && func.returnType.cType !in structWrap ) { getReturnImport(func.returnType); if ( func.returnType.isArray() ) getReturnImport(func.returnType.elementType); } void getParamImport(GirType type) { if ( type.name in structWrap || type.name in aliases ) return; GirStruct dType = pack.getStruct(type.name); if ( dType is this ) return; if ( func.type == GirFunctionType.Signal && type.name.startsWith("Gdk.Event") ) imports ~= "gdk.Event"; if ( dType && (dType.type != GirStructType.Record || dType.lookupClass || dType.lookupInterface) ) { if ( dType.type == GirStructType.Interface || dType.lookupInterface ) { imports ~= dType.pack.name ~"."~ dType.name ~"IF"; if ( func.type == GirFunctionType.Signal ) imports ~= dType.pack.name ~"."~ dType.name; } else { imports ~= dType.pack.name ~"."~ dType.name; } } else if ( type.name.among("utf8", "filename") || type.cType.among("guchar**") ) imports ~= "glib.Str"; } foreach ( param; func.params ) { if ( param.type.cType in structWrap ) continue; getParamImport(param.type); if ( param.type.elementType ) getParamImport(param.type.elementType); if ( param.direction != GirParamDirection.Default ) getReturnImport(param.type); } if ( func.type == GirFunctionType.Signal ) { imports ~= "std.algorithm"; imports ~= "gobject.Signals"; } if ( func.type == GirFunctionType.Constructor ) imports ~= "glib.ConstructionException"; } foreach ( interf; implements ) { if ( parentStruct && parentStruct.implements.canFind(interf) ) continue; GirStruct strct = pack.getStruct(interf); if ( strct ) { imports ~= strct.pack.name ~"."~ strct.name ~"IF"; imports ~= strct.pack.name ~"."~ strct.name ~"T"; } } imports = uniq(sort(imports)).array; } private void writeImports(ref string buff, bool _public = false) { foreach ( imp; imports ) { if ( _public || imp.endsWith("types") ) buff ~= "public import "~ imp ~";\n"; else buff ~= "private import "~ imp ~";\n"; } buff ~= "\n\n"; } private void writeDocs(ref string buff) { if ( doc !is null && wrapper.includeComments ) { buff ~= "/**\n"; foreach ( line; doc.splitLines() ) buff ~= " * "~ line.strip() ~"\n"; if ( libVersion ) { buff ~= " *\n * Since: "~ libVersion ~"\n"; } buff ~= " */\n"; } else if ( wrapper.includeComments ) { buff ~= "/** */\n"; } } private GirFunction getTypeFunction(string cIdentifier) { GirType returnType = new GirType(wrapper); returnType.name = "GObject.GType"; returnType.cType = "GType"; GirFunction func = new GirFunction(wrapper, this); func.type = GirFunctionType.Function; func.name = "get_type"; func.cType = cIdentifier; func.returnType = returnType; if ( type == GirStructType.Interface ) func.noCode = true; return func; } /** * Get an overload of events that accept an generic Gdk Event * instead of the spesific type listed in the gir files. * * This for backwards compatibility with the documentation based wrapper. */ private string[] getGenericEventSignal(GirFunction func) { GirFunction signal = func.dup(); string[] buff; for ( size_t i; i < signal.params.length; i++ ) { if ( signal.params[i].type.name.startsWith("Gdk.Event") ) { GirType eventType = new GirType(wrapper); eventType.name = "Gdk.Event"; GirParam newParam = new GirParam(wrapper); newParam.name = signal.params[i].name; newParam.doc = signal.params[i].doc; newParam.type = eventType; signal.params[i] = newParam; break; } } string[] declaration = signal.getAddListenerDeclaration(); signal.name = signal.name ~ "-generic-event"; buff ~= signal.getDelegateWrapperDeclaration(); buff ~= "\n"; buff ~= declaration; buff ~= signal.getAddListenerBody(); buff ~= signal.getSignalCallback(); buff ~= signal.getSignalDestroyCallback(); return buff; } } final class GirField { string name; string doc; GirType type; int bits = -1; GirFunction callback; GirUnion gtkUnion; GirStruct gtkStruct; GirWrapper wrapper; this(GirWrapper wrapper) { this.wrapper = wrapper; } void parse(T)(XMLReader!T reader) { name = reader.front.attributes["name"]; if ( "bits" in reader.front.attributes ) bits = to!int(reader.front.attributes["bits"]); //TODO: readable private? reader.popFront(); while( !reader.empty && !reader.endTag("field") ) { if ( reader.front.type == XMLNodeType.EndTag ) { reader.popFront(); continue; } switch(reader.front.value) { case "doc": reader.popFront(); doc ~= reader.front.value; reader.popFront(); break; case "doc-deprecated": reader.popFront(); doc ~= "\n\nDeprecated: "~ reader.front.value; reader.popFront(); break; case "array": case "type": type = new GirType(wrapper); type.parse(reader); break; case "callback": callback = new GirFunction(wrapper, null); callback.parse(reader); break; default: throw new XMLException(reader, "Unexpected tag: "~ reader.front.value ~" in GirField: "~ name); } reader.popFront(); } } /** * A special case for fields, we need to know about all of then * to properly construct the bitfields. */ static string[] getFieldDeclarations(GirField[] fields, GirWrapper wrapper) { string[] buff; int bitcount; void endBitfield() { //AFAIK: C bitfields are padded to a multiple of sizeof uint. int padding = 32 - (bitcount % 32); if ( padding > 0 && padding < 32) { buff[buff.length-1] ~= ","; buff ~= "uint, \"\", "~ to!string(padding); buff ~= "));"; } else { buff ~= "));"; } bitcount = 0; } foreach ( field; fields ) { if ( field.callback ) { if ( bitcount > 0 ) endBitfield(); buff ~= field.callback.getFunctionPointerDecleration(); continue; } if ( field.gtkUnion ) { if ( bitcount > 0 ) endBitfield(); buff ~= field.gtkUnion.getUnionDeclaration(); continue; } if ( field.gtkStruct ) { if ( bitcount > 0 ) endBitfield(); buff ~= field.gtkStruct.getStructDeclaration(); buff ~= stringToGtkD(field.gtkStruct.cType ~" "~ field.gtkStruct.name ~";", wrapper.aliasses); continue; } if ( field.bits > 0 ) { if ( bitcount == 0 ) { buff ~= "import std.bitmanip: bitfields;"; buff ~= "mixin(bitfields!("; } else { buff[buff.length-1] ~= ","; } bitcount += field.bits; buff ~=stringToGtkD(field.type.cType ~", \""~ field.name ~"\", "~ to!string(field.bits), wrapper.aliasses); continue; } else if ( bitcount > 0) { endBitfield(); } if ( field.doc !is null && wrapper.includeComments && field.bits < 0 ) { buff ~= "/**"; foreach ( line; field.doc.splitLines() ) buff ~= " * "~ line.strip(); buff ~= " */"; } string dType; if ( field.type.size == -1 ) { if ( field.type.cType.empty ) dType = stringToGtkD(field.type.name, wrapper.aliasses); else dType = stringToGtkD(field.type.cType, wrapper.aliasses); } else if ( field.type.elementType.cType.empty ) { //Special case for GObject.Value. dType = stringToGtkD(field.type.elementType.name, wrapper.aliasses); dType ~= "["~ to!string(field.type.size) ~"]"; } else { dType = stringToGtkD(field.type.elementType.cType, wrapper.aliasses); dType ~= "["~ to!string(field.type.size) ~"]"; } buff ~= dType ~" "~ tokenToGtkD(field.name, wrapper.aliasses) ~";"; } if ( bitcount > 0) { endBitfield(); } return buff; } } final class GirUnion { string name; string doc; GirField[] fields; GirWrapper wrapper; this(GirWrapper wrapper) { this.wrapper = wrapper; } void parse(T)(XMLReader!T reader) { if ( "name" in reader.front.attributes ) name = reader.front.attributes["name"]; reader.popFront(); while( !reader.empty && !reader.endTag("union") ) { switch(reader.front.value) { case "doc": reader.popFront(); doc ~= reader.front.value; reader.popFront(); break; case "doc-deprecated": reader.popFront(); doc ~= "\n\nDeprecated: "~ reader.front.value; reader.popFront(); break; case "field": GirField field = new GirField(wrapper); field.parse(reader); fields ~= field; break; case "record": GirField field = new GirField(wrapper); GirStruct strct = new GirStruct(wrapper, null); strct.parse(reader); strct.cType = strct.cType.toUpper()[0..1] ~ strct.cType[1 .. $]; field.gtkStruct = strct; fields ~= field; break; default: throw new XMLException(reader, "Unexpected tag: "~ reader.front.value ~" in GirUnion: "~ name); } reader.popFront(); } } string[] getUnionDeclaration() { string[] buff; if ( doc !is null && wrapper.includeComments ) { buff ~= "/**"; foreach ( line; doc.splitLines() ) buff ~= " * "~ line.strip(); buff ~= " */"; } if ( name ) buff ~= "union "~ tokenToGtkD(name.toUpper()[0..1] ~ name[1 .. $], wrapper.aliasses); else buff ~= "union"; buff ~= "{"; buff ~= GirField.getFieldDeclarations(fields, wrapper); buff ~= "}"; if ( name ) buff ~= tokenToGtkD(name.toUpper()[0..1] ~ name[1 .. $], wrapper.aliasses) ~" "~ tokenToGtkD(name.toLower(), wrapper.aliasses) ~";"; return buff; } } gir-to-d-0.10.0/source/gtd/GirType.d000066400000000000000000000104751311631112600170220ustar00rootroot00000000000000/* * This file is part of gtkD. * * gtkD is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version, with * some exceptions, please read the COPYING file. * * gtkD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with gtkD; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA */ module gtd.GirType; import gtd.GirWrapper; import gtd.XMLReader; import std.algorithm: among, canFind; import std.array: replace; import std.conv: to; /** * Represent sthe type of an field or a parameter. */ final class GirType { string name; string cType; string dType; string doc; bool constType; int size = -1; /// The size of a fixed size array. int length = -1; /// The index of the param representing the length, not counting the instance param. bool zeroTerminated; /// Is this array zero-terminated. GirType elementType; /// The type of the array elements, also set for Glib.List, Glib.SList Glib.Array and GLib.HashTable. GirType keyType; /// The key type of a HashTable; GirWrapper wrapper; this(GirWrapper wrapper) { this.wrapper = wrapper; } void parse(T)(XMLReader!T reader) { if ( "c:type" in reader.front.attributes ) cType = reader.front.attributes["c:type"]; if ( "length" in reader.front.attributes ) length = to!int(reader.front.attributes["length"]); if ( "zero-terminated" in reader.front.attributes ) zeroTerminated = to!int(reader.front.attributes["zero-terminated"]) == 1; if ( "fixed-size" in reader.front.attributes ) size = to!int(reader.front.attributes["fixed-size"]); if ( "name" in reader.front.attributes ) name = reader.front.attributes["name"]; if ( cType is null && name is null ) { name = "none"; cType = "void"; } if ( cType.canFind("const ") ) { constType = true; fixType(); } if ( cType.canFind("unsigned ") ) { cType = cType.replace("unsigned ", "u"); } cType = cType.replace("volatile ", ""); if ( cType == "unsigned" ) cType = name; removeInitialyUnowned(); if ( cType is null && (name == "filename" || name == "utf8") ) cType = "gchar*"; if ( reader.front.type == XMLNodeType.EmptyTag ) return; reader.popFront(); while ( !reader.empty && !reader.endTag("type", "array") ) { if ( elementType ) keyType = elementType; elementType = new GirType(wrapper); elementType.parse(reader); reader.popFront(); } if ( cType == elementType.cType && !cType.among("void*", "gpointer", "gconstpointer") ) cType ~= "*"; if ( isArray() && cType == "void" ) cType = elementType.cType ~"*"; } bool isArray() { if ( elementType is null ) return false; if ( name.among("GLib.List", "GLib.SList", "GLib.Array", "GLib.ByteArray", "GLib.HashTable", "GLib.PtrArray") ) return false; if ( name.among("List", "SList", "Array", "ByteArray", "HashTable", "PtrArray") ) return false; if ( elementType ) return true; return false; } private void fixType() { if ( name == "utf8" && !cType.canFind("**") ) { cType = "const(char)*"; return; } cType = cType.replace("const ", "").replace(" const", ""); } private void removeInitialyUnowned() { if ( name.among("GObject.InitiallyUnowned", "InitiallyUnowned") ) { if ( name == "GObject.InitiallyUnowned" ) name = "GObject.Object"; else if ( name == "InitiallyUnowned" ) name = "Object"; if ( cType == "GInitiallyUnowned" ) cType = "GObject"; else if ( cType == "GInitiallyUnowned*" ) cType = "GObject*"; } else if ( name.among("GObject.InitiallyUnownedClass", "InitiallyUnownedClass") ) { if ( name == "GObject.InitiallyUnownedClass" ) name = "GObject.ObjectClass"; else if ( name == "InitiallyUnownedClass" ) name = "ObjectClass"; if ( cType == "GInitiallyUnownedClass" ) cType = "GObjectClass"; else if ( cType == "GInitiallyUnownedClass*" ) cType = "GObjectClass*"; } } } gir-to-d-0.10.0/source/gtd/GirVersion.d000066400000000000000000000065271311631112600175310ustar00rootroot00000000000000/* * This file is part of gtkD. * * gtkD is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version, with * some exceptions, please read the COPYING file. * * gtkD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with gtkD; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA */ module gtd.GirVersion; import std.array; import std.conv; import std.format; struct GirVersion { uint major; uint minor; uint micro; this(string _version) { parse(_version); } this(uint major, uint minor, uint micro = 0) { this.major = major; this.minor = minor; this.micro = micro; } void parse(string _version) { string[] parts = split(_version, "."); if ( parts.length >= 1 && !parts[0].empty ) major = to!uint(parts[0]); if ( parts.length >= 2 && !parts[1].empty ) minor = to!uint(parts[1]); if ( parts.length >= 3 && !parts[2].empty ) micro = to!uint(parts[2]); } string toString() const { return format("%s.%s.%s", major, minor, micro); } void toString(scope void delegate(const(char)[]) sink) const { sink(to!string(major)); sink("."); sink(to!string(minor)); sink("."); sink(to!string(micro)); } bool opEquals()(auto ref const GirVersion _version) const { if ( major != _version.major ) return false; else if ( minor != _version.minor ) return false; else if ( micro != _version.micro ) return false; return true; } bool opEquals()(auto ref string _version) const { string[] parts = split(_version, "."); if ( parts.length >= 1 && !parts[0].empty ) { uint maj = to!uint(parts[0]); if ( major != maj ) return false; } if ( parts.length >= 2 && !parts[1].empty ) { uint min = to!uint(parts[1]); if ( minor != min ) return false; } if ( parts.length >= 3 && !parts[2].empty ) { uint mic = to!uint(parts[2]); if ( micro != mic ) return false; } return true; } int opCmp()(auto ref const GirVersion _version) const { if ( major != _version.major ) return major - _version.major; else if ( minor != _version.minor ) return minor - _version.minor; return micro - _version.micro; } int opCmp()(auto ref string _version) const { string[] parts = split(_version, "."); if ( parts.length >= 1 && !parts[0].empty ) { uint maj = to!uint(parts[0]); if ( major != maj ) return major - maj; } if ( parts.length >= 2 && !parts[1].empty ) { uint min = to!uint(parts[1]); if ( minor != min ) return minor - min; } if ( parts.length >= 3 && !parts[2].empty ) { uint mic = to!uint(parts[2]); return micro - mic; } return 0; } } unittest { auto v1 = GirVersion("1.2.3"); auto v2 = GirVersion(2, 3); assert(v1.minor == 2); assert(v1 < v2); assert(v2 == GirVersion("2.3")); assert(v2 > GirVersion("1.2.3")); assert(v2 == "2.3"); assert(v2 > "1.1.2"); assert(v2 < "3.4"); assert(v2 >= "2.3"); } gir-to-d-0.10.0/source/gtd/GirWrapper.d000066400000000000000000000424151311631112600175200ustar00rootroot00000000000000/* * This file is part of gtkD. * * gtkD is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version, with * some exceptions, please read the COPYING file. * * gtkD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with gtkD; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA */ module gtd.GirWrapper; import std.algorithm; import std.array; import std.file; import std.uni; import std.path; import std.stdio; import std.string; import gtd.DefReader; import gtd.IndentedStringBuilder; import gtd.GlibTypes; import gtd.GirPackage; import gtd.GirStruct; import gtd.GirFunction; import gtd.GirType; import gtd.GirVersion; import gtd.WrapError; class GirWrapper { bool includeComments; bool useRuntimeLinker; bool useBindDir; string apiRoot; string outputRoot; string srcDir; string commandlineGirPath; static string licence; static string[string] aliasses; static GirPackage[string] packages; public this(string apiRoot, string outputRoot, bool useRuntimeLinker) { this.apiRoot = apiRoot; this.outputRoot = outputRoot; this.useRuntimeLinker = useRuntimeLinker; } public void proccess(string apiLookupDefinition) { DefReader defReader = new DefReader( buildPath(apiRoot, apiLookupDefinition) ); while ( !defReader.empty ) { switch ( defReader.key ) { case "license": licence = defReader.readBlock().join(); break; case "includeComments": includeComments = defReader.valueBool; break; case "alias": loadAA(aliasses, defReader); break; case "inputRoot": stderr.writefln("Warning %s(%s) : Don't use inputRoot, it has been removed as it was never implemented.", defReader.filename, defReader.lineNumber); break; case "outputRoot": if ( outputRoot == buildPath(apiRoot, "out") ) outputRoot = defReader.value; break; case "srcDir": srcDir = defReader.value; break; case "bindDir": stderr.writefln("Warning %s(%s) : Don't use bindDir, it is no longer used since the c definitions have moved.", defReader.filename, defReader.lineNumber); break; case "copy": if ( srcDir.empty ) throw new WrapError(defReader, "Can't copy the file when srcDir is not set"); string outDir = buildPath(outputRoot, srcDir); if ( !exists(outDir) ) { try mkdirRecurse(outDir); catch (FileException) throw new WrapError(defReader, "Failed to create directory: "~ outDir); } copyFiles(apiRoot, buildPath(outputRoot, srcDir), defReader.value); break; case "lookup": proccess(defReader.value); break; case "wrap": if ( outputRoot.empty ) throw new WrapError(defReader, "Found wrap while outputRoot isn't set"); if ( srcDir.empty ) throw new WrapError(defReader, "Found wrap while srcDir isn't set"); wrapPackage(defReader); break; default: throw new WrapError(defReader, "Unknown key: "~defReader.key); } defReader.popFront(); } } public void wrapPackage(DefReader defReader) { GirPackage pack; GirStruct currentStruct; try { if (defReader.value in packages) throw new WrapError(defReader, "Package: "~ defReader.value ~"already defined."); pack = new GirPackage(defReader.value, this, srcDir); packages[defReader.value] = pack; defReader.popFront(); } catch (Exception e) throw new WrapError(defReader, e.msg); while ( !defReader.empty ) { switch ( defReader.key ) { case "addAliases": pack.lookupAliases ~= defReader.readBlock(); break; case "addEnums": pack.lookupEnums ~= defReader.readBlock(); break; case "addStructs": pack.lookupStructs ~= defReader.readBlock(); break; case "addFuncts": pack.lookupFuncts ~= defReader.readBlock(); break; case "addConstants": pack.lookupConstants ~= defReader.readBlock(); break; case "file": if ( !isAbsolute(defReader.value) ) { pack.parseGIR(getAbsoluteGirPath(defReader.value)); } else { stderr.writefln("Warning %s(%s): Don't use absolute paths for specifying gir files.", defReader.filename, defReader.lineNumber); pack.parseGIR(defReader.value); } break; case "struct": if ( defReader.value.empty ) { currentStruct = null; } else { currentStruct = pack.getStruct(defReader.value); if ( currentStruct is null ) currentStruct = createClass(pack, defReader.value); } break; case "class": if ( currentStruct is null ) currentStruct = createClass(pack, defReader.value); currentStruct.lookupClass = true; currentStruct.name = defReader.value; break; case "interface": if ( currentStruct is null ) currentStruct = createClass(pack, defReader.value); currentStruct.lookupInterface = true; currentStruct.name = defReader.value; break; case "cType": currentStruct.cType = defReader.value; break; case "namespace": currentStruct.type = GirStructType.Record; currentStruct.lookupClass = false; currentStruct.lookupInterface = false; if ( defReader.value.empty ) { currentStruct.noNamespace = true; } else { currentStruct.noNamespace = false; currentStruct.name = defReader.value; } break; case "extend": currentStruct.lookupParent = true; currentStruct.parent = defReader.value; break; case "implements": if ( defReader.value.empty ) currentStruct.implements = null; else currentStruct.implements ~= defReader.value; break; case "merge": GirStruct mergeStruct = pack.getStruct(defReader.value); currentStruct.merge(mergeStruct); GirStruct copy = currentStruct.dup(); copy.noCode = true; copy.noExternal = true; mergeStruct.pack.collectedStructs[mergeStruct.name] = copy; break; case "move": string[] vals = defReader.value.split(); if ( vals.length <= 1 ) throw new WrapError(defReader, "No destination for move: "~ defReader.value); string newFuncName = ( vals.length == 3 ) ? vals[2] : vals[0]; GirStruct dest = pack.getStruct(vals[1]); if ( dest is null ) dest = createClass(pack, vals[1]); if ( currentStruct && vals[0] in currentStruct.functions ) { currentStruct.functions[vals[0]].strct = dest; dest.functions[newFuncName] = currentStruct.functions[vals[0]]; dest.functions[newFuncName].name = newFuncName; if ( newFuncName.startsWith("new") ) dest.functions[newFuncName].type = GirFunctionType.Constructor; if ( currentStruct.virtualFunctions.canFind(vals[0]) ) dest.virtualFunctions ~= newFuncName; currentStruct.functions.remove(vals[0]); } else if ( vals[0] in pack.collectedFunctions ) { pack.collectedFunctions[vals[0]].strct = dest; dest.functions[newFuncName] = pack.collectedFunctions[vals[0]]; dest.functions[newFuncName].name = newFuncName; pack.collectedFunctions.remove(vals[0]); } else throw new WrapError(defReader, "unknown function "~ vals[0]); break; case "import": currentStruct.imports ~= defReader.value; break; case "structWrap": loadAA(currentStruct.structWrap, defReader); break; case "alias": loadAA(currentStruct.aliases, defReader); break; case "override": currentStruct.functions[defReader.value].lookupOverride = true; break; case "noAlias": pack.collectedAliases.remove(defReader.value); break; case "noEnum": pack.collectedEnums.remove(defReader.value); break; case "noCallback": pack.collectedCallbacks.remove(defReader.value); break; case "noCode": if ( defReader.valueBool ) { currentStruct.noCode = true; break; } if ( defReader.value !in currentStruct.functions ) throw new WrapError(defReader, "Unknown function: "~ defReader.value); currentStruct.functions[defReader.value].noCode = true; break; case "noExternal": currentStruct.noExternal = true; break; case "noSignal": currentStruct.functions[defReader.value~"-signal"].noCode = true; break; case "noStruct": currentStruct.noDecleration = true; break; case "code": currentStruct.lookupCode ~= defReader.readBlock; break; case "interfaceCode": currentStruct.lookupInterfaceCode ~= defReader.readBlock; break; case "in": string[] vals = defReader.value.split(); if ( vals[0] !in currentStruct.functions ) throw new WrapError(defReader, "Unknown function: "~ vals[0]); findParam(currentStruct, vals[0], vals[1]).direction = GirParamDirection.Default; break; case "out": string[] vals = defReader.value.split(); if ( vals[0] !in currentStruct.functions ) throw new WrapError(defReader, "Unknown function: "~ vals[0]); findParam(currentStruct, vals[0], vals[1]).direction = GirParamDirection.Out; break; case "inout": case "ref": string[] vals = defReader.value.split(); if ( vals[0] !in currentStruct.functions ) throw new WrapError(defReader, "Unknown function: "~ vals[0]); findParam(currentStruct, vals[0], vals[1]).direction = GirParamDirection.InOut; break; case "array": string[] vals = defReader.value.split(); if ( vals[0] !in currentStruct.functions ) throw new WrapError(defReader, "Unknown function: "~ vals[0]); GirFunction func = currentStruct.functions[vals[0]]; if ( vals[1] == "Return" ) { if ( vals.length < 3 ) { func.returnType.zeroTerminated = true; break; } GirType elementType = new GirType(this); elementType.name = func.returnType.name; elementType.cType = func.returnType.cType[0..$-1]; func.returnType.elementType = elementType; foreach( i, p; func.params ) { if ( p.name == vals[2] ) func.returnType.length = cast(int)i; } } else { GirParam param = findParam(currentStruct, vals[0], vals[1]); GirType elementType = new GirType(this); elementType.name = param.type.name; elementType.cType = param.type.cType[0..$-1]; param.type.elementType = elementType; if ( vals.length < 3 ) { param.type.zeroTerminated = true; break; } if ( vals[2] == "Return" ) { param.type.length = -2; break; } foreach( i, p; func.params ) { if ( p.name == vals[2] ) param.type.length = cast(int)i; } } break; case "copy": if ( srcDir.empty ) throw new WrapError(defReader, "Can't copy the file when srcDir is not set"); copyFiles(apiRoot, buildPath(outputRoot, srcDir), defReader.value); break; case "version": if ( defReader.value == "end" ) break; if ( defReader.subKey.empty ) throw new WrapError(defReader, "Error, no version number specified."); GirVersion vers = GirVersion(defReader.subKey); if ( defReader.value == "start" ) { if ( vers <= pack._version ) break; else defReader.readBlock(); } if ( vers > pack._version ) break; size_t index = defReader.value.indexOf(':'); defReader.key = defReader.value[0 .. max(index, 0)].strip(); defReader.value = defReader.value[index +1 .. $].strip(); if ( !defReader.key.empty ) continue; break; default: throw new WrapError(defReader, "Unknown key: "~defReader.key); } defReader.popFront(); } } void printFreeFunctions() { foreach ( pack; packages ) { foreach ( func; pack.collectedFunctions ) { if ( func.movedTo.empty ) writefln("%s: %s", pack.name, func.name); } } } private string getAbsoluteGirPath(string girFile) { if ( commandlineGirPath ) { string cmdGirFile = buildNormalizedPath(commandlineGirPath, girFile); if ( exists(cmdGirFile) ) return cmdGirFile; } return buildNormalizedPath(getGirDirectory(), girFile); } private string getGirDirectory() { version(Windows) { import std.process : environment; static string path; if (path !is null) return path; foreach (p; splitter(environment.get("PATH"), ';')) { string dllPath = buildNormalizedPath(p, "libgtk-3-0.dll"); if ( exists(dllPath) ) path = p.buildNormalizedPath("../share/gir-1.0"); } return path; } else version(OSX) { import std.process : environment; static string path; if (path !is null) return path; path = environment.get("GTK_BASEPATH"); if(path) { path = path.buildNormalizedPath("../share/gir-1.0"); } else { path = environment.get("HOMEBREW_ROOT"); if(path) { path = path.buildNormalizedPath("share/gir-1.0"); } } return path; } else { return "/usr/share/gir-1.0"; } } private GirParam findParam(GirStruct strct, string func, string name) { foreach( param; strct.functions[func].params ) { if ( param.name == name ) return param; } return null; } private void loadAA (ref string[string] aa, DefReader defReader) { string[] vals = defReader.value.split(); if ( vals.length == 1 ) vals ~= ""; if ( vals.length == 2 ) aa[vals[0]] = vals[1]; else throw new WrapError(defReader, "Unknown key: "~defReader.key); } private void copyFiles(string srcDir, string destDir, string file) { string from = buildNormalizedPath(srcDir, file); string to = buildNormalizedPath(destDir, file); writefln("copying file [%s] to [%s]", from, to); if ( isFile(from) ) { copy(from, to); return; } void copyDir(string from, string to) { if ( !exists(to) ) mkdir(to); foreach ( entry; dirEntries(from, SpanMode.shallow) ) { string dst = buildPath(to, entry.name.baseName); if ( isDir(entry.name) ) copyDir(entry.name, dst); else copy(entry.name, dst); } } copyDir(from, to); if ( file == "cairo" ) { if ( useRuntimeLinker ) copy(buildNormalizedPath(to, "c", "functions-runtime.d"), buildNormalizedPath(to, "c", "functions.d")); else copy(buildNormalizedPath(to, "c", "functions-compiletime.d"), buildNormalizedPath(to, "c", "functions.d")); remove(buildNormalizedPath(to, "c", "functions-runtime.d")); remove(buildNormalizedPath(to, "c", "functions-compiletime.d")); } } private GirStruct createClass(GirPackage pack, string name) { GirStruct strct = new GirStruct(this, pack); strct.name = name; strct.cType = pack.cTypePrefix ~ name; strct.type = GirStructType.Record; strct.noDecleration = true; pack.collectedStructs["lookup"~name] = strct; return strct; } } /** * Apply aliasses to the tokens in the string, and * camelCase underscore separated tokens. */ string stringToGtkD(string str, string[string] aliases, string[string] localAliases = null) { size_t pos, start; string seps = " \n\r\t\f\v()[]*,;"; auto converted = appender!string(); while ( pos < str.length ) { if ( !seps.canFind(str[pos]) ) { start = pos; while ( pos < str.length && !seps.canFind(str[pos]) ) pos++; //Workaround for the tm struct, type and variable have the same name. if ( pos < str.length && str[pos] == '*' && str[start..pos] == "tm" ) converted.put("void"); else converted.put(tokenToGtkD(str[start..pos], aliases, localAliases)); if ( pos == str.length ) break; } converted.put(str[pos]); pos++; } return converted.data; } unittest { assert(stringToGtkD("token", ["token":"tok"]) == "tok"); assert(stringToGtkD("string token_to_gtkD(string token, string[string] aliases)", ["token":"tok"]) == "string tokenToGtkD(string tok, string[string] aliases)"); } string tokenToGtkD(string token, string[string] aliases, bool caseConvert=true) { return tokenToGtkD(token, aliases, null, caseConvert); } string tokenToGtkD(string token, string[string] aliases, string[string] localAliases, bool caseConvert=true) { if ( token in glibTypes ) return glibTypes[token]; else if ( token in localAliases ) return localAliases[token]; else if ( token in aliases ) return aliases[token]; else if ( token.startsWith("cairo_") && token.endsWith("_t", "_t*", "_t**") ) return token; else if ( token == "pid_t" ) return token; else if ( caseConvert ) return tokenToGtkD(removeUnderscore(token), aliases, localAliases, false); else return token; } string removeUnderscore(string token) { char pc; auto converted = appender!string(); while ( !token.empty ) { if ( token[0] == '_' ) { pc = token[0]; token = token[1..$]; continue; } if ( pc == '_' ) converted.put(token[0].toUpper()); else converted.put(token[0]); pc = token[0]; token = token[1..$]; } return converted.data; } unittest { assert(removeUnderscore("this_is_a_test") == "thisIsATest"); } gir-to-d-0.10.0/source/gtd/GlibTypes.d000066400000000000000000000042211311631112600173310ustar00rootroot00000000000000/* * This file is part of gtkD. * * gtkD is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version, with * some exceptions, please read the COPYING file. * * gtkD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with gtkD; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA */ module gtd.GlibTypes; enum string[string] glibTypes = [ "volatile": "", "G_CONST_RETURN": "", "gint": "int", "guint": "uint", "gboolean": "bool", "gpointer": "void*", "gconstpointer": "void*", "gchar": "char", "guchar": "char", "gshort": "short", "gushort": "ushort", "gint8": "byte", "guint8": "ubyte", "gint16": "short", "guint16": "ushort", "gint32": "int", "gint64": "long", "guint32": "uint", "guint64": "ulong", "guintptr": "size_t", "gfloat": "float", "gdouble": "double", "goffset": "long", "gsize": "size_t", "gssize": "ptrdiff_t", "va_list": "void*", "unichar": "dchar", "unichar2": "wchar", "uchar": "ubyte", "XID": "uint", "gunichar": "dchar", "gunichar2": "wchar", "time_t": "uint", "uid_t": "uid_t", "alias": "alias_", "align": "alig", "body": "bod", "continue": "continu", "debug": "dbg", "default": "defaulx", "delete": "delet", "export": "expor", "foreach": "foreac", "function": "funct", "Function": "Funct", "in": "inn", "instance": "instanc", "interface": "iface", "module": "modul", "out": "output", "package": "p", "ref": "doref", "scope": "scop", "string": "str", "switch": "switc", "union": "unio", "version": "versio", "GLIB_SYSDEF_POLLIN": "=1", "GLIB_SYSDEF_POLLOUT": "=4", "GLIB_SYSDEF_POLLPRI": "=2", "GLIB_SYSDEF_POLLHUP": "=16", "GLIB_SYSDEF_POLLERR": "=8", "GLIB_SYSDEF_POLLNVAL": "=32", ]; gir-to-d-0.10.0/source/gtd/IndentedStringBuilder.d000066400000000000000000000054341311631112600216660ustar00rootroot00000000000000/* * This file is part of gtkD. * * gtkD is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version, with * some exceptions, please read the COPYING file. * * gtkD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with gtkD; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA */ module gtd.IndentedStringBuilder; import std.algorithm: canFind, startsWith, endsWith; import std.range: empty; import std.string: strip; /** Keeps track of indentation level while building up a string */ public class IndentedStringBuilder { string tabs; bool statement; bool paramList; this() { this(""); } this(string t) { tabs = t; } /** * Formats the input line while keeping track of indentation. * Params: * lines = The lines to format */ public string format(string line) { string text; line = line.strip(); if ( (endsWith(line, '{') && !startsWith(line, "}")) || endsWith(line, "(") ) { statement = false; } //Don't change the indentation when the line is a comment. if ( startsWith(line, '*') ) { return tabs ~" "~ line ~ "\n"; } if ( endsWith(line, "}", "};") || startsWith(line, "}", "};") || line == "));" || line == "connectFlags);" || (paramList && endsWith(line, ");", ")")) ) { if ( !canFind(line, '{') && tabs.length > 0 ) tabs.length = tabs.length -1; if ( line == "connectFlags);" ) statement = true; if ( endsWith(line, ");") && !endsWith(line, "));") && line != ");" ) statement = true; paramList = false; } if ( line.empty ) { return "\n"; } else if ( statement ) { text = tabs ~"\t"~ line ~"\n"; statement = false; } else { text = tabs ~ line ~"\n"; } if ( startsWith(line, "if", "else", "static if","version", "debug", "do", "while") && !endsWith(line, "}", ";") ) { statement = true; } else if ( (endsWith(line, '{') && !startsWith(line, "}")) ) { tabs ~= '\t'; } else if ( endsWith(line, "(") ) { tabs ~= '\t'; paramList = true; } return text; } /** * Formats the input lines while keeping track of indentation * Params: * lines = The lines to format */ public string format(string[] lines) { string text = ""; foreach(string line ; lines ) text ~= format(line); return text; } public void setIndent(string t) { tabs = t; } } gir-to-d-0.10.0/source/gtd/LinkedHasMap.d000066400000000000000000000150021311631112600177260ustar00rootroot00000000000000/* * This file is part of gtkD. * * gtkD is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version, with * some exceptions, please read the COPYING file. * * gtkD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with gtkD; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA */ module gtd.LinkedHasMap; import core.memory; /** * An hash map that allows iteration in the insertion-order. */ struct LinkedHashMap(Key, Value) { static struct Node { Value val; Key key; Node* next; Node* previous; } private Node*[Key] data; private Node* front; private Node* back; /** * Looks up key, if it exsists returns the corresponding value * else evaluates and returns defaultValue. */ inout(Value) get(Key key, lazy inout(Value) defaultValue = Value.init) inout pure @safe { if ( key !in data ) return defaultValue; return data[key].val; } /** * remove(key) does nothing if the given key does not exist and returns false. * If the given key does exist, it removes it from the HashMap and returns true. */ bool remove(Key key) pure nothrow @trusted { Node** nodeP = key in data; if ( nodeP is null ) return false; Node* node = *nodeP; if ( node is front ) front = node.next; if ( node is back ) back = node.previous; if ( node.previous ) node.previous.next = node.next; if ( node.next ) node.next.previous = node.previous; data.remove(key); GC.free(node); return true; } /** * Removes all contents from the LinkedHashMap */ void clear() pure nothrow @trusted { Node* node = front; Node* previous; while ( node !is null ) { previous = node; node = node.next; GC.free(previous); } data.destroy(); front = null; back = null; } /** * Returns: the number of values in the LinkedHasMap. */ @property size_t length() nothrow pure const @trusted { return data.length; } /** * Returns: true if the LinkedHasmap has no elements. */ @property bool empty() nothrow pure const @safe { return front is null; } /** * Indexing operators yield or modify the value at a specified index. */ inout(Value) opIndex(Key key) inout pure @safe { return data[key].val; } /// ditto void opIndexAssign(Value value, Key key) @safe { Node* node; if ( key !in data ) { node = new Node; } else { node = data[key]; node.val = value; return; } node.val = value; node.key = key; data[key] = node; if ( front is null ) { front = node; back = node; return; } node.previous = back; back.next = node; back = node; } /// ditto Value opIndexUnary(string op)(Key key) @safe { Node* node = data[key]; return mixin(op ~"node.val;"); } /// ditto Value opIndexOpAssign(string op)(Value v, Key key) @safe { Node* node = data[key]; return mixin("node.val" ~ op ~ "=v"); } /** * in operator. Check to see if the given element exists in the container. */ inout(Value)* opBinaryRight(string op)(Key key) inout nothrow pure @safe if (op == "in") { inout(Node*)* node = key in data; if ( node is null ) return null; return &((*node).val); } /** * foreach iteration uses opApply. */ int opApply(scope int delegate(ref Value) dg) { Node* node = front; while ( node !is null ) { int result = dg(node.val); if ( result ) return result; node = node.next; } return 0; } /// ditto int opApply(scope int delegate(ref Key, ref Value) dg) { Node* node = front; while ( node !is null ) { int result = dg(node.key, node.val); if ( result ) return result; node = node.next; } return 0; } /** * Returns: true if this and that are equal. */ bool opEquals(inout typeof(this) that) inout nothrow pure @safe { return data == that.data; } /** * Returns: An dynamic array, the elements of which are the keys in the LinkedHashmap. */ @property inout(Key)[] keys() inout @safe { inout(Key)[] k; inout(Node)* node = front; while ( node !is null ) { k ~= node.key; node = node.next; } return k; } /** * Returns: An dynamic array, the elements of which are the values in the LinkedHashmap. */ @property inout(Value)[] values() inout @safe { inout(Value)[] v; inout(Node)* node = front; while ( node !is null ) { v ~= node.val; node = node.next; } return v; } /** * Reorganizes the LinkedHashMap in place so that lookups are more efficient, * rehash is effective when, for example, the program is done loading up * a symbol table and now needs fast lookups in it. */ void rehash() @trusted { data = data.rehash(); } /** * Create a new LinkedHashMap of the same size and copy the contents of the LinkedHashMap into it. */ LinkedHashMap!(Key, Value) dub() @safe { LinkedHashMap!(Key, Value) copy; Node* node = front; while ( node !is null ) { copy[node.key] = node.val; node = node.next; } return copy; } /** * Returns a delegate suitable for use as a ForeachAggregate to * a ForeachStatement which will iterate over the keys of the LinkedHashMap. */ @property auto byKey() pure nothrow @safe { static struct KeyRange { Node* node; this(Node* node) pure nothrow @safe { this.node = node; } @property Key front() pure nothrow @safe { return node.key; } void popFront() pure nothrow @safe { node = node.next; } @property bool empty() pure const nothrow @safe { return node is null; } } return KeyRange(front); } /** * Returns a delegate suitable for use as a ForeachAggregate to * a ForeachStatement which will iterate over the values of the LinkedHashMap. */ @property auto byValue() pure nothrow @safe { static struct ValueRange { Node* node; this(Node* node) pure nothrow @safe { this.node = node; } @property Value front() pure nothrow @safe { return node.val; } void popFront() pure nothrow @safe { node = node.next; } @property bool empty() pure const nothrow @safe { return node is null; } } return ValueRange(front); } } gir-to-d-0.10.0/source/gtd/WrapError.d000066400000000000000000000017441311631112600173610ustar00rootroot00000000000000/* * This file is part of gtkD. * * gtkD is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version, with * some exceptions, please read the COPYING file. * * gtkD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with gtkD; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA */ module gtd.WrapError; import std.string; import gtd.DefReader; class WrapError : Error { this(DefReader defReader, string msg) { super(msg, defReader.filename, defReader.lineNumber); } } gir-to-d-0.10.0/source/gtd/XMLReader.d000066400000000000000000000232011311631112600172110ustar00rootroot00000000000000/* * This file is part of gtkD. * * gtkD is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version, with * some exceptions, please read the COPYING file. * * gtkD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with gtkD; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA */ module gtd.XMLReader; import std.algorithm; import std.array; import std.conv : to; import std.exception; import std.range; import std.string; import std.traits: isSomeChar; import std.uni; struct XMLNode { XMLNodeType type; string value; string[string] attributes; } enum XMLNodeType { None, PI, StartTag, Text, CData, DocType, Comment, EmptyTag, EndTag, DocumentEnd } class XMLReader(T) if (isInputRange!T && isSomeChar!(ElementType!T) ) { XMLNode front; string fileName; static if ( is( T == string ) ) private CountLines!ByChar document; else private CountLines!T document; /** * Params: * document = The XML document to parse. * fileName = File name to print in diagnostic messages. */ this(T document, string fileName = null) { static if ( is( T == string ) ) this.document = CountLines!ByChar(ByChar(document)); else this.document = CountLines!T(document); this.fileName = fileName; popFront(); } @property size_t line() { return document.line; } void popFront() { front = XMLNode(); if ( document.empty ) { front.type = XMLNodeType.DocumentEnd; return; } if ( document.front == '<' ) parseTag(); else parseText(); } @property bool empty() { return document.empty && front.type == XMLNodeType.DocumentEnd; } private void parseTag() { document.popFront(); switch ( document.front ) { case '!': document.popFront(); switch ( document.front ) { case '[': enforce(document.skipOver("[CDATA[")); parseCDATA(); break; case 'D': enforce(document.skipOver("!DOCTYPE")); parseDocType(); break; case '-': enforce(document.skipOver("--")); parseComment(); break; default: throw new XMLException(this, "Invalid XML tag"); } break; case '?': document.popFront(); parsePI(); break; case '/': document.popFront(); parseStartTag(); front.type = XMLNodeType.EndTag; break; default: parseStartTag(); break; } skipWhitespace(); } private void parseCDATA() { front.type = XMLNodeType.CData; auto buff = appender!string(); while ( !document.empty ) { if ( document.front == ']' ) { document.popFront(); if ( document.front != ']' ) { buff.put(']'); buff.put(document.front); document.popFront(); continue; } document.popFront(); if ( document.front == '>' ) { document.popFront(); return; } } buff.put(document.front); document.popFront(); } front.value = buff.data; } private void parseDocType() { front.type = XMLNodeType.DocType; auto buff = appender!string(); int bracketCount; skipWhitespace(); while ( !document.empty ) { switch ( document.front ) { case '[': bracketCount++; break; case ']': bracketCount--; break; case '>': if ( bracketCount == 0 ) { document.popFront(); return; } break; default: break; } buff.put(document.front); document.popFront(); } front.value = buff.data.stripRight(); } private void parseComment() { front.type = XMLNodeType.Comment; auto buff = appender!string(); while ( !document.empty ) { if ( document.front == '-' ) { document.popFront(); if ( document.front != '-' ) { buff.put('-'); buff.put(document.front); document.popFront(); continue; } document.popFront(); if ( document.front == '>' ) { document.popFront(); return; } throw new XMLException(this, "-- not allowed in comments."); } buff.put(document.front); document.popFront(); } front.value = buff.data.strip(); } private void parsePI() { front.type = XMLNodeType.PI; auto buff = appender!string(); while ( !document.empty ) { if ( document.front == '?' ) { document.popFront(); if ( document.front == '>' ) { document.popFront(); return; } buff.put('?'); } buff.put(document.front); document.popFront(); } front.value = buff.data.stripRight(); } private void parseStartTag() { front.type = XMLNodeType.StartTag; auto buff = appender!string(); while ( !document.empty && !(document.front.isWhite() || document.front == '/' || document.front == '>') ) { buff.put(document.front); document.popFront(); } front.value = buff.data; while ( !document.empty ) { skipWhitespace(); if ( document.front == '/' ) { front.type = XMLNodeType.EmptyTag; document.popFront(); } if ( document.front == '>' ) { document.popFront(); return; } buff = appender!string(); string attName; while ( !document.empty && !(document.front.isWhite() || document.front == '=') ) { buff.put(document.front); document.popFront(); } document.popFront(); if ( document.front == '=' ) document.popFront(); attName = buff.data; buff = appender!string(); if ( document.front.isWhite() ) skipWhitespace(); ElementType!(typeof(document)) quote = document.front; document.popFront(); AttValue: while ( !document.empty ) { switch ( document.front ) { case '\'': case '"': if ( document.front != quote ) goto default; document.popFront(); break AttValue; case '&': parseAmpersand(buff); break; default: buff.put(document.front); break; } document.popFront(); } front.attributes[attName] = buff.data; } } private void parseText() { front.type = XMLNodeType.Text; auto buff = appender!string(); Text: while ( !document.empty ) { switch ( document.front ) { case '<': break Text; case '&': parseAmpersand(buff); break; default: buff.put(document.front); break; } document.popFront(); } front.value = buff.data.stripRight(); } private void skipWhitespace() { while ( !document.empty && isWhite(document.front) ) document.popFront(); } private void parseAmpersand(Appender!(string) buff) { ElementType!(typeof(document))[5] sequence; int index; document.popFront(); while ( document.front != ';' ) { sequence[index++] = document.front; document.popFront(); } switch ( sequence[0 .. index] ) { case "#34": case "quot": buff.put('"'); break; case "#38": case "amp": buff.put('&'); break; case "#39": case "apos": buff.put('\''); break; case "#60": case "lt": buff.put('<'); break; case "#62": case "gt": buff.put('>'); break; default: throw new XMLException(this, "Unregonized escape secuence"); } } unittest { auto reader = new XMLReader("<test>"); assert(reader.front.value == ""); } } /** * Skip the current tag and it's content. * Leaves the reader pointing to the end tag with the same depth. */ void skipTag(T)(XMLReader!T reader) { if ( reader.front.type == XMLNodeType.EmptyTag ) return; if ( reader.front.type != XMLNodeType.StartTag ) { reader.popFront(); return; } string tagName = reader.front.value; size_t depth; while ( !reader.empty ) { if ( reader.front.type == XMLNodeType.StartTag ) depth++; if ( reader.front.type == XMLNodeType.EndTag ) depth--; if ( depth == 0 && reader.front.value == tagName ) return; reader.popFront(); } } /** * Is this an end tag with name tagName. */ bool endTag(T)(XMLReader!T reader, string tagName) { return reader.front.type == XMLNodeType.EndTag && reader.front.value == tagName; } /// ditto. bool endTag(T)(XMLReader!T reader, string[] tagNames ...) { return reader.front.type == XMLNodeType.EndTag && tagNames.canFind(reader.front.value); } class XMLException : Exception { this (T)(XMLReader!T reader, string msg) { super(msg, reader.fileName, reader.line, null); } override string toString() { string s; toString((buf) { s ~= buf; }); return s; } override void toString(scope void delegate(in char[]) sink) const { sink(file); sink("("); sink(to!string(line)); sink(")"); if (msg.length) { sink(": "); sink(msg); } } } struct ByChar { string data; @property char front() { return data[0]; } @property bool empty() { return !data.length; } void popFront() { assert(data.length, "Attempting to popFront() past the end of an array"); data = data[1 .. $]; } @property ByChar save() { return this; } alias data this; } struct CountLines(Source) if (isSomeChar!(ElementType!Source)) { import std.range.primitives : ElementType; Source src; size_t line = 1; this(Source src) { this.src = src; } @property ElementType!Source front() { return src.front; } @property bool empty() { return src.empty; } void popFront() { src.popFront(); if ( src.front == '\n' ) line++; } @property typeof(this) save() { return typeof(this)(src.save); } }