pax_global_header 0000666 0000000 0000000 00000000064 14562767404 0014531 g ustar 00root root 0000000 0000000 52 comment=6f0a6097009d6bf22f29a43e0063de85b4c19b76
gir-to-d-0.23.2/ 0000775 0000000 0000000 00000000000 14562767404 0013237 5 ustar 00root root 0000000 0000000 gir-to-d-0.23.2/COPYING 0000664 0000000 0000000 00000016743 14562767404 0014305 0 ustar 00root root 0000000 0000000 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.23.2/GNUmakefile 0000664 0000000 0000000 00000002115 14562767404 0015310 0 ustar 00root root 0000000 0000000 SHELL=/bin/sh
OS=$(shell uname || uname -s)
ARCH=$(shell arch || uname -m)
GIR_TO_D_VERSION=v0.23.1
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
INCLUDEFLAG=-J
LINKERFLAG=-Xlinker
DDOCFLAGS=-fsyntax-only -c -fdoc -fdoc-file=$@
DDOCINC=-fdoc-inc=
output=-o $@
else
DCFLAGS=-O
INCLUDEFLAG=-J
LINKERFLAG=-L
DDOCFLAGS=-o- -Df$@
output=-of$@
endif
#######################################################################
.DEFAULT_GOAL = $(BINNAME)
SOURCES = $(wildcard source/*.d) $(wildcard source/gtd/*.d)
BINNAME = girtod
$(BINNAME): VERSION $(SOURCES)
$(DC) $(filter-out $<,$^) $(output) $(INCLUDEFLAG)./ $(DCFLAGS) $(LDFLAGS)
rm -f *.o
VERSION: VERSION.in
sed 's/@VCS_TAG@/$(shell git describe --dirty=+ --tags || echo $(GIR_TO_D_VERSION))/g' $< > $@
clean:
-rm -f $(BINNAME)
-rm -f VERSION
gir-to-d-0.23.2/Readme_APILookup 0000664 0000000 0000000 00000015712 14562767404 0016250 0 ustar 00root root 0000000 0000000 The GTK binding is generated by the girtod utility using APILookup
files and the GIR files from GObject Introspection.
The girtod utility parses APILookup.txt which tells it what to do/parse
using the commands listed below.
There to two types of commands key value pairs and block commands which are denoted with
"command: start" and "command: end".
Top level commands:
-------------------
Top level commands can only be set once and apply to everything.
includeComments: (true/false)
If true the generated code includes comments/documentation
for the classes, functions, etc.
license: (block)
Sets the license text used at the top of the generated files.
outputRoot: path
Directory where the generated code is stored.
Global commands:
----------------
Global commands can be set more than once, but also affect everything.
srcDir only affects the packages that come after it.
alias: ctype dtype
Replace ctype with dtype in the generated code.
copy: filename
Copies filename from inputRoot to outputRoot/srcDir.
dependency DEP: skip
When generating code don't assume dependency DEB is available.
dependency DEP: (block)
Apply the lookup definitions in this block to the dependency
before generating any code.
lookup: filename
Continue parsing in filename.
srcDir: directory
The source for the following packages is placed in this directory.
version X.XX: command: value
Only include the command if the version specified in the Gir file is >= X.XX.
An OS identifier can also be used as the version.
Currently supported are: Windows, OSX, Linux and Posix.
The OS versions can de negated.
version X.XX: (block)
The same as above but applies to all commands in the block.
The version can optionaly be used at the end of the block.
wrap: packageName
Starts wrapping a package, and uses packageName as it's name.
After this command and until wrap is used again, all commands
only affect the current package.
When inside a dependency wrap only sets the package name.
Package commands:
-----------------
These commands apply to the package set with wrap.
addAliases: (block)
Add the contained text to the alias section of the c definitions.
addConstants: (block)
Add the contained text to the constant section of the c definitions.
addEnums: (block)
Add the contained text to the enum section of the c definitions.
addFuncts: (block)
Add the contained text to the function/callback section of the c definitions.
addStructs: (block)
Add the contained text to the struct section of the c definitions.
file: girFilename.
Parse the a GIR file, this command can be used multiple times
to combine different GIR files. girtod will detect the gir directory.
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.
You can list the global functions that haven't been moved by running
girtod with the --print-free argument.
noAlias: name
Don't generate any code for alias name.
name should be the name specified in the GIR file.
noConstant: name
Don't generate any code for constant 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.
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 which case class and interface can
be used to create a new class or interface.
Struct commands:
----------------
These commands apply to the struct set with struct.
class and interface will create a struct if it is not set.
alias: ctype dtype
Replace ctype with dtype in the generated code for the current struct.
array: field length_field
Set length_field as the length for the field property.
And handle field as an array and keep the length_field in sync with the actual length.
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.
code: (block)
Add the contained code/text the generated struct/class.
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.
import: package.module
Explicitly add imports to the generated file.
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.
interfaceCode: (block)
Add the contained code/text the generated interface.
merge: name
merge struct 'name' with the struct set by struct:.
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.
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:
noProperty: name
Don't generate a property for field name.
name should be the name specified in the GIR file.
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 the struct declaration for the struct set by struct:
structWrap: ctype dtype
Wrap ctype as dtype, instead of what's defined by the GIR files.
Function commands:
------------------
The Function commands apply to functions of the currently set struct.
They generaly take the function they apply to as there first argument.
array: func_name param_array [param_length]
Override the GIR file and handle param_array of function func_name
as an array whose length is specified by param_length.
If param_length isn't specified the wrapper assumes the array is zero terminated.
"Return" can be used for either param_array or param_length for when
one of them is returned by the function.
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.
override: func_name
Explicitly add the override attribute to function func_name.
func_name should be the name specified in the GIR file.
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.
gir-to-d-0.23.2/VERSION.in 0000664 0000000 0000000 00000000012 14562767404 0014705 0 ustar 00root root 0000000 0000000 @VCS_TAG@
gir-to-d-0.23.2/dub.json 0000664 0000000 0000000 00000000533 14562767404 0014705 0 ustar 00root root 0000000 0000000 {
"name": "girtod",
"description": "A binding generator for libraries supporting gobject-introspection.",
"homepage": "https://gtkd.org",
"license": "LGPL-3.0",
"targetType": "executable",
"mainSourceFile": "source/girtod.d",
"stringImportPaths": ["./"],
"preGenerateCommands": [
"echo $$DUB_PACKAGE_VERSION > $PACKAGE_DIR/VERSION"
]
}
gir-to-d-0.23.2/meson.build 0000664 0000000 0000000 00000001724 14562767404 0015405 0 ustar 00root root 0000000 0000000 project('GIR-to-D', 'd', version: '0.23.2')
source = [
'source/girtod.d',
'source/gtd/DefReader.d',
'source/gtd/GlibTypes.d',
'source/gtd/GirAlias.d',
'source/gtd/GirConstant.d',
'source/gtd/GirEnum.d',
'source/gtd/GirField.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/Log.d',
'source/gtd/LinkedHasMap.d',
'source/gtd/WrapException.d',
'source/gtd/XMLReader.d'
]
sources_dir = include_directories('source/')
version = vcs_tag(command: ['git', 'describe', '--dirty=+', '--tags'], input: 'VERSION.in', output: 'VERSION')
# d_import_dirs was added in meson 0.43 for now add -J manually.
add_project_arguments('-J'+meson.current_build_dir(), language: 'd')
executable(
'girtod',
[source, version],
include_directories : [sources_dir],
# d_import_dirs : meson.build_root(),
install : true
)
gir-to-d-0.23.2/source/ 0000775 0000000 0000000 00000000000 14562767404 0014537 5 ustar 00root root 0000000 0000000 gir-to-d-0.23.2/source/girtod.d 0000664 0000000 0000000 00000010244 14562767404 0016175 0 ustar 00root root 0000000 0000000 /*
* This file is part of gir-to-d.
*
* gir-to-d 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.
*
* gir-to-d 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 gir-to-d. If not, see .
*/
module girtod;
import std.algorithm: canFind, find, findSkip, startsWith;
import std.array;
import std.file : exists, getcwd, isFile;
import std.getopt;
import std.path;
import std.stdio;
import core.stdc.stdlib;
import gtd.GirWrapper;
import gtd.Log;
import gtd.WrapException;
void main(string[] args)
{
bool printFree;
string lookupFile = "APILookup.txt";
GirWrapper wrapper = new GirWrapper("./", "./out");
Option printFilesOption;
wrapper.cwdOrBaseDirectory = getcwd();
printFilesOption.optLong = "--print-files";
printFilesOption.help = "Write a newline separated list of generated files to stdout. Optionally you can pass 'relative[,/base/path] or 'full' to force printing the relative or full paths of the files.";
auto helpInformation = getopt(
args,
std.getopt.config.passThrough,
"input|i", "Directory containing the API description. Or a lookup file (Default: ./)", &wrapper.inputDir,
"output|o", "Output directory for the generated binding. (Default: ./out)", &wrapper.outputDir,
"use-runtime-linker", "Link the gtk functions with the runtime linker.", &wrapper.useRuntimeLinker,
"gir-directory|g", "Directory to search for gir files before the system directory.", &wrapper.commandlineGirPath,
"print-free", "Print functions that don't have a parent module.", &printFree,
"use-bind-dir", "Include public imports for the old gtkc package.", &wrapper.useBindDir,
"version", "Print the version and exit", (){ writeln("GIR to D ", import("VERSION")); exit(0); }
);
if (helpInformation.helpWanted)
{
defaultGetoptPrinter("girtod is an utility that generates D bindings using the GObject introspection files.\n\nOptions:",
helpInformation.options ~ printFilesOption);
exit(0);
}
if ( args.length > 1 )
handlePrintFiles(args, wrapper);
try
{
//Read in the GIR and API files.
if ( wrapper.inputDir.extension == ".gir" )
{
wrapper.proccessGIR(wrapper.inputDir);
}
else
{
if ( wrapper.inputDir.exists && wrapper.inputDir.isFile() )
{
lookupFile = wrapper.inputDir.baseName();
wrapper.inputDir = wrapper.inputDir.dirName();
}
wrapper.proccess(lookupFile);
}
if ( printFree )
wrapper.printFreeFunctions();
//Generate the D binding
foreach(pack; wrapper.packages)
{
if ( pack.name == "cairo" )
continue;
if ( wrapper.useRuntimeLinker )
pack.writeLoaderTable();
else
pack.writeExternalFunctions();
pack.writeTypes();
pack.writeClasses();
}
}
catch (WrapException ex)
{
error(ex);
}
}
void handlePrintFiles(string[] args, GirWrapper wrapper)
{
string value;
args.popFront();
if ( args.front.startsWith("--print-files") )
{
if ( args.front.findSkip("=") )
{
value = args.front;
}
args.popFront();
if ( value.empty && !args.empty && !args.front.startsWith("--") )
{
value = args.front;
args.popFront();
}
}
if ( !args.empty )
{
writeln("Unable to parse parameters: Unrecognized option ", args.front);
exit(0);
}
wrapper.printFiles = true;
if ( value == "absolute" || value == "full" )
{
wrapper.printFileMethod = PrintFileMethod.Absolute;
}
else if ( value.startsWith("relative") )
{
wrapper.printFileMethod = PrintFileMethod.Relative;
if ( value.findSkip(",") )
wrapper.cwdOrBaseDirectory = value;
if ( !isAbsolute(wrapper.cwdOrBaseDirectory) )
error("The base directory passed to relative must be absolute.");
}
else if ( !value.empty )
{
error("Unknown option: '", value, "' for print-files.");
}
}
gir-to-d-0.23.2/source/gtd/ 0000775 0000000 0000000 00000000000 14562767404 0015315 5 ustar 00root root 0000000 0000000 gir-to-d-0.23.2/source/gtd/DefReader.d 0000664 0000000 0000000 00000007125 14562767404 0017310 0 ustar 00root root 0000000 0000000 /*
* This file is part of gir-to-d.
*
* gir-to-d 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.
*
* gir-to-d 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 gir-to-d. If not, see .
*/
module gtd.DefReader;
import std.algorithm;
import std.array;
import std.conv : hexString;
import std.file;
import std.string : splitLines, strip, indexOf;
import gtd.WrapException;
public final class DefReader
{
string fileName;
string key;
string subKey;
string value;
private size_t _lineNumber;
private size_t lineOffset;
private string[] lines;
public this(string fileName)
{
this.fileName = fileName;
lines = readText(fileName).splitLines();
//Skip utf8 BOM.
lines[0].skipOver(hexString!"efbbbf");
this.popFront();
}
/**
* Proccess the _lines defined in lines.
* The fileName and lineOffset are only used for error reporting.
*/
public this(string[] lines, string fileName = "", size_t lineOffset = 0)
{
this.lines = lines;
this.fileName = fileName;
this.lineOffset = lineOffset;
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("#") )
{
ptrdiff_t index = line.indexOf(':');
key = line[0 .. max(index, 0)].strip();
value = line[index +1 .. $].strip();
subKey = "";
index = key.indexOf(' ');
if ( index != -1 )
{
subKey = key[index +1 .. $].strip();
key = key[0 .. index].strip();
}
}
else
{
key.length = 0;
value.length = 0;
subKey.length = 0;
}
}
/**
* Gets the content 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 LookupException(this, "Found EOF while expecting: \""~key~": end\"");
}
/**
* Skip the content of a block. Supports nested blocks.
*/
public void skipBlock(string key = "")
{
if ( key.empty )
key = this.key;
size_t nestedBlocks = 1;
do
{
do lines.popFront; while ( !lines.front.strip().startsWith(key) );
if ( lines.front.strip().endsWith("start") )
nestedBlocks++;
else if ( lines.front.strip().endsWith("end") )
nestedBlocks--;
}
while ( nestedBlocks > 0 );
}
/**
* Gets the current value as a bool
*/
public @property bool valueBool() const
{
return !!value.among("1", "ok", "OK", "Ok", "true", "TRUE", "True", "Y", "y", "yes", "YES", "Yes");
}
public @property bool empty() const
{
return lines.empty && key.empty;
}
public @property size_t lineNumber() const
{
return _lineNumber + lineOffset;
}
}
class LookupException : WrapException
{
this(DefReader defReader, string msg)
{
super(msg, defReader.fileName, defReader.lineNumber);
}
}
gir-to-d-0.23.2/source/gtd/GirAlias.d 0000664 0000000 0000000 00000004151 14562767404 0017156 0 ustar 00root root 0000000 0000000 /*
* This file is part of gir-to-d.
*
* gir-to-d 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.
*
* gir-to-d 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 gir-to-d. If not, see .
*/
module gtd.GirAlias;
import std.string : splitLines, strip;
import gtd.GirType;
import gtd.GirWrapper;
import gtd.Log;
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;
case "source-position":
reader.skipTag();
break;
default:
warning("Unexpected tag: ", reader.front.value, " in GirAlias: ", name, reader);
}
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.23.2/source/gtd/GirConstant.d 0000664 0000000 0000000 00000005544 14562767404 0017725 0 ustar 00root root 0000000 0000000 /*
* This file is part of gir-to-d.
*
* gir-to-d 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.
*
* gir-to-d 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 gir-to-d. If not, see .
*/
module gtd.GirConstant;
import std.algorithm : among, canFind;
import std.array : replace;
import std.string : splitLines, strip;
import gtd.GirPackage;
import gtd.GirType;
import gtd.GirWrapper;
import gtd.Log;
import gtd.XMLReader;
final class GirConstant
{
string name;
string cType;
string value;
string doc;
GirType type;
GirPackage pack;
GirWrapper wrapper;
this(GirWrapper wrapper, GirPackage pack)
{
this.wrapper = wrapper;
this.pack = pack;
}
void parse(T)(XMLReader!T reader)
{
name = reader.front.attributes["name"];
value = reader.front.attributes["value"];
if ( "c:type" in reader.front.attributes )
cType = reader.front.attributes["c:type"];
else
cType = reader.front.attributes["c:identifier"];
reader.popFront();
while( !reader.empty && !reader.endTag("constant") )
{
switch(reader.front.value)
{
case "type":
case "array":
type = new GirType(wrapper);
type.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;
case "source-position":
reader.skipTag();
break;
default:
warning("Unexpected tag: ", reader.front.value, " in GirConstant: ", name, reader);
}
reader.popFront();
}
if ( value.canFind("\\") )
value = value.replace("\\", "\\\\");
if ( type.cType.among("gint64", "guint64") )
// See dmd issue 8929 for why we use UL for signed longs. https://issues.dlang.org/show_bug.cgi?id=8929#c7
value ~= "UL";
}
string[] getConstantDeclaration()
{
string[] buff;
if ( doc !is null && wrapper.includeComments )
{
buff ~= "/**";
foreach ( line; doc.splitLines() )
buff ~= " * "~ line.strip();
buff ~= " */";
}
if ( type.name in pack.collectedAliases && pack.collectedAliases[type.name].baseType.cType.among("gint64", "guint64") )
value ~= "UL";
if ( type.isString() )
buff ~= "enum "~ name ~" = \""~ value ~"\";";
else
buff ~= "enum "~ name ~" = "~ value ~";";
buff ~= "alias "~ cType ~" = "~ name ~";";
return buff;
}
}
gir-to-d-0.23.2/source/gtd/GirEnum.d 0000664 0000000 0000000 00000011237 14562767404 0017034 0 ustar 00root root 0000000 0000000 /*
* This file is part of gir-to-d.
*
* gir-to-d 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.
*
* gir-to-d 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 gir-to-d. If not, see .
*/
module gtd.GirEnum;
import std.array : split;
import std.algorithm;
import std.range : back, empty;
import std.string : splitLines, strip, toUpper;
import std.uni : isNumber;
import gtd.GirPackage;
import gtd.GirWrapper;
import gtd.Log;
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;
case "source-position":
reader.skipTag();
break;
default:
warning("Unexpected tag: ", reader.front.value, " in GirEnum: ", name, reader);
}
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 ( name.empty )
name = reader.front.attributes["c:identifier"].split("_").back;
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 "source-position":
reader.skipTag();
break;
case "type":
if ( reader.front.attributes["name"] == "utf8" )
value = "\""~ value ~"\"";
break;
default:
warning("Unexpected tag: ", reader.front.value, " in GirEnumMember: ", name, reader);
}
reader.popFront();
}
}
string[] getEnumMemberDeclaration()
{
string[] buff;
if ( doc !is null && wrapper.includeComments )
{
buff ~= "/**";
foreach ( line; doc.splitLines() )
buff ~= " * "~ line.strip();
buff ~= " */";
}
if ( name[0].isNumber && name !in wrapper.aliasses )
buff ~= "_"~ name.toUpper() ~" = "~ value ~",";
else
buff ~= tokenToGtkD(name.toUpper(), wrapper.aliasses, false) ~" = "~ value ~",";
return buff;
}
}
gir-to-d-0.23.2/source/gtd/GirField.d 0000664 0000000 0000000 00000046231 14562767404 0017155 0 ustar 00root root 0000000 0000000 /*
* This file is part of gir-to-d.
*
* gir-to-d 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.
*
* gir-to-d 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 gir-to-d. If not, see .
*/
module gtd.GirField;
import std.algorithm: among, endsWith;
import std.conv;
import std.range;
import std.string: splitLines, strip;
import gtd.Log;
import gtd.GirFunction;
import gtd.GirStruct;
import gtd.GirType;
import gtd.GirWrapper;
import gtd.XMLReader;
final class GirField
{
string name;
string doc;
GirType type;
int bits = -1;
bool writable = false;
bool isLength = false; ///This field holds the length of an other field.
bool noProperty = false; ///Don't generate a property for this field.
GirFunction callback;
GirUnion gtkUnion;
GirStruct gtkStruct;
GirWrapper wrapper;
GirStruct strct;
this(GirWrapper wrapper, GirStruct strct)
{
this.wrapper = wrapper;
this.strct = strct;
}
void parse(T)(XMLReader!T reader)
{
name = reader.front.attributes["name"];
if ( "bits" in reader.front.attributes )
bits = to!int(reader.front.attributes["bits"]);
if ( auto write = "writable" in reader.front.attributes )
writable = *write == "1";
//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, strct);
callback.parse(reader);
break;
case "source-position":
reader.skipTag();
break;
default:
warning("Unexpected tag: ", reader.front.value, " in GirField: ", name, reader);
}
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.getFunctionPointerDeclaration();
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, false);
else
dType = stringToGtkD(field.type.cType, wrapper.aliasses, false);
}
else if ( field.type.elementType.cType.empty )
{
//Special case for GObject.Value.
dType = stringToGtkD(field.type.elementType.name, wrapper.aliasses, false);
dType ~= "["~ to!string(field.type.size) ~"]";
}
else
{
dType = stringToGtkD(field.type.elementType.cType, wrapper.aliasses, false);
dType ~= "["~ to!string(field.type.size) ~"]";
}
buff ~= dType ~" "~ tokenToGtkD(field.name, wrapper.aliasses) ~";";
}
if ( bitcount > 0)
{
endBitfield();
}
return buff;
}
string[] getProperty()
{
string[] buff;
if ( !writable || isLength || noProperty )
return null;
writeDocs(buff);
writeGetter(buff);
buff ~= "";
if ( wrapper.includeComments )
buff ~= "/** Ditto */";
writeSetter(buff);
return buff;
}
private void writeGetter(ref string[] buff)
{
GirStruct dType;
string dTypeName;
if ( type.isArray() )
dType = strct.pack.getStruct(type.elementType.name);
else if ( auto dStrct = strct.pack.getStruct(strct.structWrap.get(type.name, "")) )
dType = dStrct;
else
dType = strct.pack.getStruct(type.name);
if ( dType )
{
if ( dType.name in strct.structWrap )
dTypeName = strct.structWrap[dType.name];
else if ( dType.type == GirStructType.Interface )
dTypeName = dType.name ~"IF";
else
dTypeName = dType.name;
}
if ( type.isString() )
{
if ( type.isArray() && type.elementType.isString() )
{
buff ~= "public @property string["~ ((type.size > 0)?type.size.to!string:"") ~"] "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"()";
buff ~= "{";
if ( type.length > -1 )
buff ~= "return Str.toStringArray("~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~", "~ getLengthID(strct) ~");";
else if ( type.size > 0 )
{
buff ~= "string["~ type.size.to!string ~"] arr;";
buff ~= "foreach( i, str; "~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~" )";
buff ~= "{";
buff ~= "arr[i] = Str.toString(str);";
buff ~= "}";
buff ~= "return arr;";
}
else
buff ~= "return Str.toStringArray("~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~");";
buff ~= "}";
}
else
{
if ( type.size > 0 )
{
buff ~= "public @property char["~ type.size.to!string ~"] "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"()";
buff ~= "{";
buff ~= "return "~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~";";
buff ~= "}";
}
else
{
buff ~= "public @property string "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"()";
buff ~= "{";
buff ~= "return Str.toString("~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~");";
buff ~= "}";
}
}
}
else if ( dType && dType.isDClass() && type.cType.endsWith("*") )
{
if ( type.isArray() )
{
buff ~= "public @property "~ dTypeName ~"["~ ((type.size > 0)?type.size.to!string:"") ~"] "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"()";
buff ~= "{";
if ( type.length > -1 )
buff ~= dTypeName ~"[] arr = new "~ dTypeName ~"["~ getLengthID(strct) ~"];";
else if ( type.size > 0 )
buff ~= dTypeName ~"["~ type.size.to!string ~"] arr;";
else
buff ~= dTypeName ~"[] arr = new "~ dTypeName ~"[getArrayLength("~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~")];";
buff ~= "for ( int i = 0; i < arr.length; i++ )";
buff ~= "{";
if ( dType.pack.name.among("cairo", "glib", "gthread") )
buff ~= "arr[i] = new "~ dTypeName ~"("~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~"[i], false);";
else if( dType.type == GirStructType.Interface )
buff ~= "arr[i] = ObjectG.getDObject!("~ dTypeName ~"IF)("~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~"[i], false);";
else
buff ~= "arr[i] = ObjectG.getDObject!("~ dTypeName ~")("~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~"[i], false);";
buff ~= "}";
buff ~= "";
buff ~= "return arr;";
buff ~= "}";
}
else
{
buff ~= "public @property "~ dTypeName ~" "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"()";
buff ~= "{";
if ( dType.pack.name.among("cairo", "glib", "gthread") )
buff ~= "return new "~ dTypeName ~"("~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~", false);";
else if( dType.type == GirStructType.Interface )
buff ~= "return ObjectG.getDObject!("~ dTypeName ~"IF)("~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~", false);";
else
buff ~= "return ObjectG.getDObject!("~ dTypeName ~")("~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~", false);";
buff ~= "}";
}
}
else if ( type.name.among("bool", "gboolean") || ( type.isArray && type.elementType.name.among("bool", "gboolean") ) )
{
if ( type.isArray() )
{
buff ~= "public @property bool["~ ((type.size > 0)?type.size.to!string:"") ~"] "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"()";
buff ~= "{";
if ( type.length > -1 )
buff ~= "return "~ strct.getHandleVar ~"."~ tokenToGtkD(name, wrapper.aliasses) ~"[0.."~ getLengthID(strct) ~"];";
else if ( type.size > 0 )
buff ~= "return "~ strct.getHandleVar ~"."~ tokenToGtkD(name, wrapper.aliasses) ~";";
else
error("Is boolean[] field: ", strct.name, ".", name, " really zero terminated?");
buff ~= "}";
}
else
{
buff ~= "public @property bool "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"()";
buff ~= "{";
buff ~= "return "~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~" != 0;";
buff ~= "}";
}
}
else
{
if ( type.isArray() )
{
if ( type.size > 0 && dType && dType.isDClass() )
{
buff ~= "public @property "~ dTypeName ~"["~ type.size.to!string() ~"] "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"()";
buff ~= "{";
buff ~= dTypeName ~"["~ type.size.to!string() ~"] arr;";
buff ~= "for ( int i = 0; i < arr.length; i++ )";
buff ~= "{";
if ( dType.pack.name.among("cairo", "glib", "gthread") )
buff ~= "arr[i] = new "~ dTypeName ~"(&("~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~"[i]), false);";
else if( dType.type == GirStructType.Interface )
buff ~= "arr[i] = ObjectG.getDObject!("~ dTypeName ~"IF)(&("~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~"[i]), false);";
else
buff ~= "arr[i] = ObjectG.getDObject!("~ dTypeName ~")(&("~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~"[i]), false);";
buff ~= "}";
buff ~= "";
buff ~= "return arr;";
buff ~= "}";
}
else if ( type.size > 0 )
{
buff ~= "public @property "~ stringToGtkD(type.cType, wrapper.aliasses, strct.aliases) ~"["~ ((type.size > 0)?type.size.to!string:"") ~"] "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"()";
buff ~= "{";
buff ~= "return "~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~";";
buff ~= "}";
}
else
{
buff ~= "public @property "~ stringToGtkD(type.cType[0..$-1], wrapper.aliasses, strct.aliases) ~"["~ ((type.size > 0)?type.size.to!string:"") ~"] "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"()";
buff ~= "{";
if ( type.length > -1 )
buff ~= "return "~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~"[0.."~ getLengthID(strct) ~"];";
else
buff ~= "return "~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~"[0..getArrayLength("~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~")];";
buff ~= "}";
}
}
else
{
buff ~= "public @property "~ stringToGtkD(type.cType, wrapper.aliasses, strct.aliases) ~" "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"()";
buff ~= "{";
buff ~= "return "~ strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~";";
buff ~= "}";
}
}
}
private void writeSetter(ref string[] buff)
{
GirStruct dType;
string dTypeName;
if ( type.isArray() )
dType = strct.pack.getStruct(type.elementType.name);
else if ( auto dStrct = strct.pack.getStruct(strct.structWrap.get(type.name, "")) )
dType = dStrct;
else
dType = strct.pack.getStruct(type.name);
if ( dType )
{
if ( dType.name in strct.structWrap )
dTypeName = strct.structWrap[dType.name];
else if ( dType.type == GirStructType.Interface )
dTypeName = dType.name ~"IF";
else
dTypeName = dType.name;
}
if ( type.isString() )
{
if ( type.isArray() && type.elementType.isString() )
{
buff ~= "public @property void "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"(string["~ ((type.size > 0)?type.size.to!string:"") ~"] value)";
buff ~= "{";
if ( type.size > 0 )
{
buff ~= stringToGtkD(type.elementType.cType, wrapper.aliasses) ~"["~ type.size.to!string ~"] arr;";
buff ~= "foreach( i, str; value )";
buff ~= "{";
buff ~= "arr[i] = Str.toStringz(str);";
buff ~= "}";
buff ~= strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~" = arr;";
}
else
{
buff ~= strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~" = Str.toStringzArray(value);";
if ( type.length > -1 )
buff ~= strct.getHandleVar() ~"."~ tokenToGtkD(strct.fields[type.length].name, wrapper.aliasses) ~" = cast("~ stringToGtkD(strct.fields[type.length].type.cType, wrapper.aliasses) ~")value.length;";
}
buff ~= "}";
}
else
{
if ( type.size > 0 )
{
buff ~= "public @property void "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"(char["~ type.size.to!string ~"] value)";
buff ~= "{";
buff ~= strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~" = value;";
buff ~= "}";
}
else
{
buff ~= "public @property void "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"(string value)";
buff ~= "{";
buff ~= strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~" = Str.toStringz(value);";
buff ~= "}";
}
}
}
else if ( dType && dType.isDClass() && type.cType.endsWith("*") )
{
if ( type.isArray() )
{
buff ~= "public @property void "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"("~ dTypeName ~"["~ ((type.size > 0)?type.size.to!string:"") ~"] value)";
buff ~= "{";
if ( type.size > 0 )
buff ~= dType.cType ~"*["~ type.size.to!string ~"] arr;";
else
buff ~= dType.cType ~"*[] arr = new "~ dType.cType ~"*[value.length+1];";
buff ~= "for ( int i = 0; i < value.length; i++ )";
buff ~= "{";
buff ~= "arr[i] = value[i]."~ dType.getHandleFunc() ~"();";
buff ~= "}";
buff ~= "arr[value.length] = null;";
buff ~= "";
buff ~= strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~" = arr.ptr;";
if ( type.length > -1 )
buff ~= strct.getHandleVar() ~"."~ tokenToGtkD(strct.fields[type.length].name, wrapper.aliasses) ~" = cast("~ stringToGtkD(strct.fields[type.length].type.cType, wrapper.aliasses) ~")value.length;";
buff ~= "}";
}
else
{
buff ~= "public @property void "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"("~ dTypeName ~" value)";
buff ~= "{";
buff ~= strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~" = value."~ dType.getHandleFunc() ~"();";
buff ~= "}";
}
}
else if ( type.name.among("bool", "gboolean") || ( type.isArray && type.elementType.name.among("bool", "gboolean") ) )
{
if ( type.isArray() )
{
buff ~= "public @property void "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"(bool["~ ((type.size > 0)?type.size.to!string:"") ~"] value)";
buff ~= "{";
if ( type.size > 0 )
{
buff ~= strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~" = value;";
}
else
{
buff ~= strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~" = value.ptr;";
if ( type.length > -1 )
buff ~= strct.getHandleVar() ~"."~ tokenToGtkD(strct.fields[type.length].name, wrapper.aliasses) ~" = cast("~ stringToGtkD(strct.fields[type.length].type.cType, wrapper.aliasses) ~")value.length;";
}
buff ~= "}";
}
else
{
buff ~= "public @property void "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"(bool value)";
buff ~= "{";
buff ~= strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~" = value;";
buff ~= "}";
}
}
else
{
if ( type.isArray() )
{
if ( type.size > 0 && dType && dType.isDClass() )
{
buff ~= "public @property void "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"("~ dTypeName ~"["~ type.size.to!string() ~"] value)";
buff ~= "{";
buff ~= "for ( int i = 0; i < value.length; i++ )";
buff ~= "{";
buff ~= strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~"[i] = *(value[i]."~ dType.getHandleFunc() ~"());";
buff ~= "}";
buff ~= "}";
}
else if ( type.size > 0 )
{
buff ~= "public @property void "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"("~ stringToGtkD(type.cType, wrapper.aliasses, strct.aliases) ~"["~ ((type.size > 0)?type.size.to!string:"") ~"] value)";
buff ~= "{";
buff ~= strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~" = value;";
buff ~= "}";
}
else
{
buff ~= "public @property void "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"("~ stringToGtkD(type.cType[0..$-1], wrapper.aliasses, strct.aliases) ~"["~ ((type.size > 0)?type.size.to!string:"") ~"] value)";
buff ~= "{";
buff ~= strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~" = value.ptr;";
if ( type.length > -1 )
buff ~= strct.getHandleVar() ~"."~ tokenToGtkD(strct.fields[type.length].name, wrapper.aliasses) ~" = cast("~ stringToGtkD(strct.fields[type.length].type.cType, wrapper.aliasses) ~")value.length;";
buff ~= "}";
}
}
else
{
buff ~= "public @property void "~ tokenToGtkD(name, wrapper.aliasses, strct.aliases) ~"("~ stringToGtkD(type.cType, wrapper.aliasses, strct.aliases) ~" value)";
buff ~= "{";
buff ~= strct.getHandleVar() ~"."~ tokenToGtkD(name, wrapper.aliasses) ~" = value;";
buff ~= "}";
}
}
}
private void writeDocs(ref string[] buff)
{
if ( doc !is null && wrapper.includeComments )
{
buff ~= "/**";
foreach ( line; doc.splitLines() )
buff ~= " * "~ line.strip();
buff ~= " */";
}
else if ( wrapper.includeComments )
{
buff ~= "/** */";
}
}
private string getLengthID(GirStruct strct)
{
if ( type.length > -1 )
return strct.getHandleVar() ~"."~ tokenToGtkD(strct.fields[type.length].name, wrapper.aliasses);
else if ( type.size > 0 )
return to!string(type.size);
return null;
}
}
gir-to-d-0.23.2/source/gtd/GirFunction.d 0000664 0000000 0000000 00000116320 14562767404 0017714 0 ustar 00root root 0000000 0000000 /*
* This file is part of gir-to-d.
*
* gir-to-d 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.
*
* gir-to-d 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 gir-to-d. If not, see .
*/
module gtd.GirFunction;
import std.algorithm: among, startsWith, endsWith;
import std.conv;
import std.range;
import std.string : chomp, splitLines, strip;
import std.uni: toUpper, toLower;
import gtd.GirEnum;
import gtd.GirStruct;
import gtd.GirType;
import gtd.GirVersion;
import gtd.GirWrapper;
import gtd.Log;
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 "attribute":
//TODO: Do we need these attibutes?
//dbus.name ccode.ordering deprecated replacement.
reader.skipTag();
break;
case "doc":
case "doc-stability":
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 "attribute":
//TODO: Do we need these attibutes?
//dbus.name ccode.ordering deprecated replacement.
reader.skipTag();
break;
case "doc":
reader.popFront();
returnType.doc ~= reader.front.value;
reader.popFront();
break;
case "array":
case "type":
returnType.parse(reader);
break;
default:
warning("Unexpected tag: ", reader.front.value, " in GirFunction: ", name, reader);
}
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:
warning("Unexpected tag: ", reader.front.value, " in GirFunction: ", name, reader);
}
reader.popFront();
}
break;
case "source-position":
reader.skipTag();
break;
default:
warning("Unexpected tag: ", reader.front.value, " in GirFunction: ", name, reader);
}
reader.popFront();
}
if ( type == GirFunctionType.Function && name.startsWith("new") && returnType.cType != "void" )
type = GirFunctionType.Constructor;
// For the case where a param is `const gchar* name[]` whitch ends up in the gir files
// as an array with elementType name=utf8 c:type=gchar, missing the [].
switch ( cType )
{
case "gtk_icon_theme_choose_icon":
case "gtk_icon_theme_choose_icon_for_scale":
params[0].type.cType = "char**";
params[0].type.elementType.cType = "char*";
break;
case "g_object_getv":
case "g_object_setv":
params[1].type.cType = "char**";
params[1].type.elementType.cType = "char*";
break;
case "gst_init":
case "gst_init_check":
params[1].type.cType = "char***";
params[1].type.elementType.cType = "char**";
break;
case "g_object_new_with_properties":
params[2].type.cType = "char**";
params[2].type.elementType.cType = "char*";
break;
case "g_key_file_set_locale_string_list":
params[3].type.cType = "char**";
params[3].type.elementType.cType = "char*";
break;
default: break;
}
}
bool isVariadic()
{
if ( params.empty )
return false;
else if ( params[$-1].name == "..." )
return true;
return false;
}
/**
* Is this function a static function.
*/
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;
}
string[] getCallbackDeclaration()
{
string[] buff;
writeDocs(buff);
buff ~= "public alias extern(C) "~ getExternalFunctionType() ~" "~ tokenToGtkD(cType, wrapper.aliasses, localAliases()) ~";";
return buff;
}
string[] getFunctionPointerDeclaration()
{
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(), false);
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(), false);
if ( type.startsWith("bool") )
ext ~= type.replaceFirst("bool", "int");
else
ext ~= type;
// Treat C fixed-size array parameters like pointers
if ( param.type.isArray() && param.type.size > 0 && !type.endsWith("*") )
ext ~= "*";
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] && params[returnType.length].direction != GirParamDirection.Default )
continue;
if ( paramCount == 0 && strct.type == GirStructType.Record && isInstanceParam(param) && type != GirFunctionType.Constructor )
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])) )
{
GirParam instance = instanceParam ? instanceParam : params[0];
GirStruct dType = strct.pack.getStruct(instance.type.name);
if ( dType.cType != instance.type.cType.removePtr() && !instance.type.cType.among("gpointer", "gconstpointer") )
gtkCall ~= "cast("~ stringToGtkD(instance.type.cType, wrapper.aliasses, localAliases()) ~")";
if ( instance && instance.type.name in strct.structWrap )
{
GirStruct insType = strct.pack.getStruct(strct.structWrap[instance.type.name]);
if ( insType )
dType = insType;
}
if ( type == GirFunctionType.Constructor || strct.isNamespace() || strct.noNamespace )
{
string id = tokenToGtkD(instance.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 ( param.type.isString() )
{
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 ( dType && dType.isDClass() )
{
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 )
{
if ( param.type.size > 0 )
buff ~= elementType.cType ~"* out"~ id ~" = cast("~ elementType.cType ~"*)sliceAlloc0("~ elementType.cType ~".sizeof * "~ to!string(param.type.size) ~");";
else if ( !elementType.cType.endsWith("*") )
buff ~= elementType.cType ~"* out"~ id ~" = null;";
else
buff ~= elementType.cType ~" out"~ id ~" = null;";
}
else
{
if ( !buff.empty )
buff ~= "";
buff ~= elementType.cType.removePtr() ~ "**[] inout"~ id ~" = new "~ elementType.cType.removePtr() ~"*["~ 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.removePtr() ~ "** out"~ id ~" = inout"~ id ~".ptr;";
}
if ( !elementType.cType.endsWith("*") )
gtkCall ~= "out"~ id;
else
gtkCall ~= "&out"~ id;
if ( !outToD.empty )
outToD ~= "";
if ( param.type.size <= 0 )
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 if ( !elementType.cType.endsWith("*") )
outToD ~= id ~"[i] = " ~ construct(elementType.name) ~ "(cast(" ~ elementType.cType ~ "*) &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.removePtr() ~"* 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.removePtr() ~"* out"~ id ~" = sliceNew!"~ param.type.cType.removePtr() ~"();";
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.removePtr() && !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 && param.direction != GirParamDirection.Default ) )
{
string arrId;
string lenType = tokenToGtkD(param.type.cType.removePtr(), 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;
string outName = "out" ~ id;
if ( outType.empty )
outType = param.type.elementType.name ~"*";
else if ( param.type.isArray() && param.type.size > 0)
outType = param.type.elementType.name ~ "[" ~ to!string(param.type.size) ~ "]";
buff ~= stringToGtkD(outType, wrapper.aliasses, localAliases) ~" " ~ outName;
if ( param.direction == GirParamDirection.Out )
buff[$-1] ~= ";";
else
buff[$-1] ~=" = "~ id ~".ptr";
if ( param.type.elementType.cType.empty )
gtkCall ~= "cast("~stringToGtkD(param.type.cType, wrapper.aliasses, localAliases) ~")&" ~ outName;
else if ( param.type.isArray() && param.type.size > 0)
gtkCall ~= outName ~ ".ptr";
else
gtkCall ~= "&" ~ outName;
outToD ~= id ~" = "~ outName ~"[0 .. "~ lenId(param.type, outName) ~"];";
}
// 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 ( returnType.isString() )
{
if ( outToD.empty && !throws &&
!(returnOwnership == GirTransferOwnership.Full || returnOwnership == GirTransferOwnership.Container) )
{
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);";
} else if ( returnOwnership == GirTransferOwnership.Container )
{
if ( isStringArray(returnType) )
buff ~= "scope(exit) g_free(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 ( returnDType && returnDType.isDClass() )
{
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 && c != '-')
{
signalName ~= toUpper(c);
}
else
{
if ( c!='-' && c!='_' )
{
if ( pc=='-' || pc=='_' )
signalName ~= toUpper(c);
else
signalName ~= c;
}
}
pc = c;
}
if ( !signalName.among("Event", "MapEvent", "UnmapEvent", "DestroyEvent") &&
endsWith(signalName, "Event") )
{
signalName = signalName[0..signalName.length-5];
}
return signalName;
}
string getDelegateDeclaration()
{
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() ~"("~ getDelegateDeclaration() ~" dlg, ConnectFlags connectFlags=cast(ConnectFlags)0)";
return buff;
}
string[] getAddListenerBody()
{
string[] buff;
buff ~= "{";
if ( strct.hasFunction("add_events") )
{
switch ( name )
{
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 ~= "return Signals.connect(this, \""~ name ~"\", dlg, connectFlags ^ ConnectFlags.SWAPPED);";
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 ( param.lengthFor )
continue;
if ( returnType.length > -1 && param == params[returnType.length] && params[returnType.length].direction != GirParamDirection.Default )
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 ( type.isString() )
{
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.cType == "gunichar2*" )
return "wchar[]";
if ( type.size > -1 )
size = to!string(type.size);
string elmType = getType(type.elementType, direction);
if ( elmType == type.cType && elmType.endsWith("*") )
elmType = elmType[0..$-1];
return elmType ~"["~ size ~"]";
}
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 ( dType && dType.isDClass() )
{
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 && type.cType.endsWith("*") )
return stringToGtkD(type.cType[0..$-1], wrapper.aliasses, localAliases());
return stringToGtkD(type.cType, wrapper.aliasses, localAliases());
}
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 && params[type.length].direction == GirParamDirection.Default && paramName != "__p" )
return "cast("~ tokenToGtkD(params[type.length].type.cType.removePtr(), wrapper.aliasses, localAliases()) ~")"~ paramName.replaceFirst("out", "") ~".length";
else 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 ( type.isString() )
return null;
return "getArrayLength("~ paramName ~")";
}
/**
* 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 ~"IF)";
else
return "ObjectG.getDObject!("~ name ~")";
}
}
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;
case "source-position":
reader.skipTag();
break;
default:
warning("Unexpected tag: ", reader.front.value, " in GirParam: ", name, reader);
}
reader.popFront();
}
if ( direction != GirParamDirection.Default && !type.cType.endsWith("*") )
direction = GirParamDirection.Default;
}
}
private string removePtr(string cType)
{
while ( !cType.empty && cType.back == '*' )
cType.popBack();
return cType;
}
gir-to-d-0.23.2/source/gtd/GirPackage.d 0000664 0000000 0000000 00000052170 14562767404 0017464 0 ustar 00root root 0000000 0000000 /*
* This file is part of gir-to-d.
*
* gir-to-d 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.
*
* gir-to-d 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 gir-to-d. If not, see .
*/
module gtd.GirPackage;
import std.algorithm;
import std.array : join, replace;
import std.conv;
import std.file;
import std.path : baseName, buildNormalizedPath;
import std.range : array, back, chain, empty;
import std.regex : ctRegex, matchFirst;
import std.stdio;
import std.string : split, splitLines, strip;
import std.uni;
import gtd.DefReader;
import gtd.GirAlias;
import gtd.GirConstant;
import gtd.GirEnum;
import gtd.GirFunction;
import gtd.GirStruct;
import gtd.GirVersion;
import gtd.GirWrapper;
import gtd.GlibTypes;
import gtd.IndentedStringBuilder;
import gtd.LinkedHasMap: Map = LinkedHashMap;
import gtd.Log;
import gtd.XMLReader;
final class GirPackage
{
string name;
string cTypePrefix;
string srcDir;
GirVersion _version;
GirWrapper wrapper;
string[] lookupAliases; /// Aliases defined in the lookupfile.
string[] lookupConstants; /// Constants defined in the lookupfile.
string[] lookupEnums; /// Enums defined in the lookupfile.
string[] lookupFuncts; /// Functions defined in the lookupfile.
string[] lookupStructs; /// Structs defined in the lookupfile.
static GirPackage[string] namespaces;
static GirInclude[string] includes;
string[] libraries;
Map!(string, GirAlias) collectedAliases; /// Aliases defined in the gir file.
Map!(string, GirFunction) collectedCallbacks;
Map!(string, GirConstant) collectedConstants;
Map!(string, GirEnum) collectedEnums; /// Enums defined in the gir file.
Map!(string, GirFunction) collectedFunctions;
Map!(string, GirStruct) collectedStructs;
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);
GirInclude gobject;
gobject.name = "GObject";
gobject._version = "2.0";
includes["GObject"] = gobject;
}
void parseGIR(string girFile)
{
if ( !exists(girFile) )
error("GIR file: '", girFile, "' not found.");
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" )
{
string incName = reader.front.attributes["name"];
GirInclude inc = includes.get(incName, GirInclude.init);
inc.name = incName;
inc._version = reader.front.attributes["version"];
includes[incName] = inc;
reader.popFront();
}
while ( !reader.empty && reader.front.value != "namespace" )
reader.popFront();
if ( name.empty )
name = reader.front.attributes["name"].toLower();
namespaces[reader.front.attributes["name"]] = this;
checkVersion(reader.front.attributes["version"]);
if ( "c:identifier-prefixes" in reader.front.attributes )
{
auto p = reader.front.attributes["c:identifier-prefixes"];
if ( p.length )
cTypePrefix = p.split(',')[0];
}
if ( "shared-library" in reader.front.attributes )
{
version(Windows)
libraries ~= reader.front.attributes["shared-library"].split(',').map!(a => a.startsWith("lib")?a:"lib"~a~".dll").array;
else version(OSX)
libraries ~= reader.front.attributes["shared-library"].split(',').map!(a => a.baseName.startsWith("lib")?a.baseName:"lib"~a.baseName~".dylib").array;
else
libraries ~= reader.front.attributes["shared-library"].split(',').map!(a => a.startsWith("lib")?a:"lib"~a~".so").array;
libraries = libraries.sort().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 "attribute":
//TODO: Do we need these attibutes?
//dbus.name ccode.ordering deprecated replacement.
reader.skipTag();
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") )
gtkStruct.name = gtkStruct.cType;
collectedStructs[gtkStruct.name] = gtkStruct;
//Don't generate classes named Object.
if ( gtkStruct.name == "Object" )
gtkStruct.name = "Object"~ cTypePrefix;
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;
case "function-macro":
// We are not able to wrap these.
reader.skipTag();
break;
case "field":
// We are not able to wrap these.
reader.skipTag();
break;
case "docsection":
// General documentation.
reader.skipTag();
break;
default:
warning("Unexpected tag: ", reader.front.value, " in GirPackage: ", name, reader);
}
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 ( "c:type" in reader.front.attributes && 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"]);
}
GirConstant constant = new GirConstant(wrapper, this);
constant.parse(reader);
if (constant.name != "true" && constant.name != "false")
collectedConstants[constant.name] = constant;
}
void parseFunction(T)(XMLReader!T reader)
{
GirFunction funct = new GirFunction(wrapper, null);
funct.parse(reader);
collectedFunctions[funct.name] = funct;
checkVersion(funct.libVersion);
}
GirPackage getNamespace(string name)
{
if ( name.empty )
return null;
if ( name !in namespaces )
{
if ( auto inc = name in includes )
{
if ( inc.skip ) return null;
namespaces[name] = inc.parse(wrapper, srcDir);
}
else
{
foreach ( inc; includes.byValue.filter!(inc => inc.name !in namespaces) )
namespaces[inc.name] = inc.parse(wrapper, srcDir);
if ( !includes.byValue.filter!(inc => inc.name !in namespaces).empty )
return getNamespace(name);
else
return null;
}
}
return namespaces.get(name, null);
}
GirStruct getStruct(string name)
{
GirPackage pack = this;
if ( name.canFind(".") )
{
string[] vals = name.split(".");
if ( !getNamespace(vals[0]) )
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 ( !getNamespace(vals[0]) )
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()
{
try
{
if ( !exists(buildNormalizedPath(wrapper.outputDir, srcDir, name.replace(".","/"))) )
mkdirRecurse(buildNormalizedPath(wrapper.outputDir, srcDir, name.replace(".","/")));
}
catch (FileException ex)
{
error("Failed to create directory: ", ex.msg);
}
foreach ( strct; collectedStructs )
strct.writeClass();
}
void writeTypes()
{
string buff = wrapper.licence;
auto indenter = new IndentedStringBuilder();
buff ~= "module "~ name ~".c.types;\n\n";
buff ~= getTypeImports();
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.noDeclaration )
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);
foreach ( c; collectedConstants )
{
buff ~= "\n";
buff ~= indenter.format(c.getConstantDeclaration());
}
if ( stockIDs.members !is null )
{
stockIDs.cName = "StockID";
stockIDs.doc = "StockIds";
buff ~= "\n";
buff ~= indenter.format(stockIDs.getEnumDeclaration());
}
if ( gdkKeys.members !is null )
writeGdkKeys();
wrapper.writeFile(buildNormalizedPath(wrapper.outputDir, srcDir, name.replace(".","/"), "c/types.d"), buff, true);
}
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";
buff ~= "alias Keysyms = GdkKeysyms;\n";
wrapper.writeFile(buildNormalizedPath(wrapper.outputDir, srcDir, name.replace(".","/"), "Keysyms.d"), buff, true);
}
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.replace(".","").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);\n";
buff ~= "\t\tLinker.link(g_module_open, \"g_module_open_utf8\", LIBRARY_GLIB);\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";
}
}
wrapper.writeFile(buildNormalizedPath(wrapper.outputDir, srcDir, name.replace(".","/"), "c", "functions.d"), buff, true);
}
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 ~= "}";
wrapper.writeFile(buildNormalizedPath(wrapper.outputDir, srcDir, name.replace(".","/"), "c", "functions.d"), buff, true);
}
private string getLibraries()
{
string lib = "version (Windows)\n\t";
lib ~= "static immutable LIBRARY_"~ name.replace(".","").toUpper() ~" = ["~ getDllNames() ~"];";
lib ~= "\nelse version (OSX)\n\t";
lib ~= "static immutable LIBRARY_"~ name.replace(".","").toUpper() ~" = ["~ getDylibNames() ~"];";
lib ~= "\nelse\n\t";
lib ~= "static immutable LIBRARY_"~ name.replace(".","").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)
{
//TODO: Only the gir files form msys are currently supported on windows.
string libs;
foreach ( lib; libraries )
{
auto match = matchFirst(lib, dllRegex);
//Msys
libs ~= "\""~ lib;
//wingtk
libs ~= ";";
libs ~= match[1].replace("lib", "");
if ( !match[2].empty )
libs ~= "-"~ match[2][1..$];
if ( !match[3].empty && match[2].canFind('.') )
libs ~= "-"~ match[3][1..$];
else if ( !match[3].empty && !match[2].empty )
libs ~= "-"~ match[2][$-1] ~"."~ match[3][1..$];
libs ~= ".dll";
//vcpkg
libs ~= ";";
libs ~= match[1].replace("lib", "");
if ( !match[2].empty && match[2].canFind('.') )
libs ~= "-"~ match[2][1..$].split('.')[0];
else if ( !match[2].empty )
libs ~= "-"~ match[2][1..$];
libs ~= ".dll\"";
if ( lib != libraries.back )
libs ~= ", ";
}
return libs;
}
else version (OSX)
{
string libs;
foreach ( lib; libraries )
{
auto match = matchFirst(lib, dylibRegex);
//Msys
libs ~= "\""~ match[1];
if ( !match[2].empty )
libs ~= "-"~ match[2][1..$];
if ( !match[3].empty )
libs ~= "-"~ match[3][1..$];
libs ~= ".dll";
//wingtk
libs ~= ";";
libs ~= match[1].replace("lib", "");
if ( !match[2].empty )
libs ~= "-"~ match[2][1..$];
if ( !match[3].empty && match[2].canFind('.') )
libs ~= "-"~ match[3][1..$];
else if ( !match[3].empty && !match[2].empty )
libs ~= "-"~ match[2][$-1] ~"."~ match[3][1..$];
libs ~= ".dll";
//vcpkg
libs ~= ";";
libs ~= match[1].replace("lib", "");
if ( !match[2].empty && match[2].canFind('.') )
libs ~= "-"~ match[2][1..$].split('.')[0];
else if ( !match[2].empty )
libs ~= "-"~ match[2][1..$];
libs ~= ".dll\"";
if ( lib != libraries.back )
libs ~= ", ";
}
return libs;
}
else
{
string libs;
foreach ( lib; libraries )
{
auto match = matchFirst(lib, soRegex);
//Msys
libs ~= "\""~ match[1];
if ( !match[2].empty )
libs ~= "-"~ match[2][1..$];
if ( !match[3].empty )
libs ~= "-"~ match[3][1..$];
libs ~= ".dll";
//wingtk
libs ~= ";";
libs ~= match[1].replace("lib", "");
if ( !match[2].empty )
libs ~= "-"~ match[2][1..$];
if ( !match[3].empty && match[2].canFind('.') )
libs ~= "-"~ match[3][1..$];
else if ( !match[3].empty && !match[2].empty )
libs ~= "-"~ match[2][$-1] ~"."~ match[3][1..$];
libs ~= ".dll";
//vcpkg
libs ~= ";";
libs ~= match[1].replace("lib", "");
if ( !match[2].empty && match[2].canFind('.') )
libs ~= "-"~ match[2][1..$].split('.')[0];
else if ( !match[2].empty )
libs ~= "-"~ match[2][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("\", \"") ~"\"";
}
}
private string getTypeImports()
{
string imports;
string[] usedNamespaces;
string[] packages;
foreach ( strct; collectedStructs )
{
if ( strct.noExternal )
continue;
usedNamespaces = chain(usedNamespaces, strct.usedNamespaces()).sort.uniq.array;
}
foreach ( ns; usedNamespaces )
{
GirPackage pack = getNamespace(ns);
if ( pack && pack != this && !packages.canFind(pack.name) )
packages ~= pack.name;
}
packages = packages.sort().array;
foreach ( pack; packages )
{
imports ~= "public import "~ pack ~".c.types;\n";
}
if ( !imports.empty )
imports ~= "\n";
return imports;
}
}
struct GirInclude
{
string name;
string _version;
bool skip;
string[] lookupText;
string lookupFile;
size_t lookupLine;
string girFileName()
{
return name ~"-"~ _version ~".gir";
}
GirPackage parse(GirWrapper wrapper, string srcDir)
{
GirPackage inc = new GirPackage(name.toLower, wrapper, srcDir);
inc.parseGIR(wrapper.getAbsoluteGirPath(girFileName()));
if ( auto text = name in defaultLookupText )
wrapper.proccess(new DefReader(*text, "Default rules"), inc, true);
wrapper.proccess(new DefReader(lookupText, lookupFile, lookupLine), inc, true);
return inc;
}
}
gir-to-d-0.23.2/source/gtd/GirStruct.d 0000664 0000000 0000000 00000075133 14562767404 0017421 0 ustar 00root root 0000000 0000000 /*
* This file is part of gir-to-d.
*
* gir-to-d 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.
*
* gir-to-d 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 gir-to-d. If not, see .
*/
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: buildNormalizedPath;
import std.uni: toUpper, toLower;
import std.range;
import std.string: capitalize, splitLines, strip, chomp;
import gtd.GirConstant;
import gtd.GirField;
import gtd.GirFunction;
import gtd.GirPackage;
import gtd.GirType;
import gtd.GirVersion;
import gtd.GirWrapper;
import gtd.IndentedStringBuilder;
import gtd.LinkedHasMap: Map = LinkedHashMap;
import gtd.Log;
import gtd.XMLReader;
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; /// Only generate the C declarations.
bool noDeclaration = false; /// Don't generate a Declaration of the C struct.
bool noExternal = false; /// Don't generate a Declaration of the C struct. And don't generate the C function declarations.
bool noNamespace = false; /// Generate the functions as global functions.
string[string] structWrap;
string[string] aliases;
string[] lookupCode;
string[] lookupInterfaceCode;
string[] implements;
string[] imports;
GirField[] fields;
string[] virtualFunctions;
Map!(string, GirFunction) functions;
bool disguised = false;
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;
}
pure string getFullyQualifiedDName() {
return "D"~ parentStruct.pack.name.capitalize() ~ parentStruct.name;
}
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"];
else if ( "glib:type-name" in reader.front.attributes )
cType = reader.front.attributes["glib:type-name"];
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 ( auto disg = "disguised" in reader.front.attributes )
disguised = *disg == "1";
if ( reader.front.type == XMLNodeType.EmptyTag )
return;
reader.popFront();
while( !reader.empty && !reader.endTag("class", "interface", "record", "union") )
{
switch(reader.front.value)
{
case "attribute":
//TODO: Do we need these attibutes?
//dbus.name ccode.ordering deprecated replacement.
reader.skipTag();
break;
case "constant":
GirConstant constant = new GirConstant(wrapper, pack);
constant.parse(reader);
pack.collectedConstants[constant.name] = constant;
constant.name = name.toUpper() ~"_"~ constant.name;
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;
case "field":
GirField field = new GirField(wrapper, this);
field.parse(reader);
fields ~= field;
break;
case "record":
GirField field = new GirField(wrapper, this);
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, this);
GirUnion uni = new GirUnion(wrapper);
uni.parse(reader);
field.gtkUnion = uni;
fields ~= field;
break;
case "callback":
GirFunction callback = new GirFunction(wrapper, null);
callback.parse(reader);
pack.collectedCallbacks[callback.name] = callback;
callback.name = name.toUpper() ~ callback.name;
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":
case "source-position":
reader.skipTag();
break;
default:
warning("Unexpected tag: ", reader.front.value, " in GirStruct: ", name, reader);
}
reader.popFront();
}
foreach( func; virtualFunctions )
{
if ( auto vFunc = func in functions )
vFunc.virtual = true;
}
if ( type == GirStructType.Union )
{
GirField field = new GirField(wrapper, this);
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, false);
buff ~= "{";
buff ~= GirField.getFieldDeclarations(fields, wrapper);
buff ~= "}";
}
else
{
buff ~= "struct "~ tokenToGtkD(cType, wrapper.aliasses, false) ~";";
}
return buff;
}
void writeClass()
{
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) && !("get_type" in functions && isSimpleStruct()) )
{
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 if ( isSimpleStruct() )
buff ~= "public final class "~ name;
else
buff ~= "public class "~ name;
if ( lookupParent && !parentStruct )
buff ~= " : "~ parent;
else if ( parentStruct && parentStruct.name != name )
buff ~= " : "~ parentStruct.name;
else if ( parentStruct )
buff ~= " : "~ getFullyQualifiedDName();
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() && !hasDefaultConstructor() )
{
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.replace(".","").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";
}
else if ( isSimpleStruct() )
{
buff ~= indenter.format("~this ()");
buff ~= indenter.format("{");
if ( wrapper.useRuntimeLinker )
buff ~= indenter.format("if ( Linker.isLoaded(LIBRARY_"~ pack.name.replace(".","").toUpper() ~") && ownedRef )");
else
buff ~= indenter.format("if ( ownedRef )");
buff ~= indenter.format("sliceFree("~ 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(["/**", "*/"]);
}
if ( isSimpleStruct() )
{
foreach( field; fields )
{
if ( field.name.startsWith("dummy") )
continue;
buff ~= "\n";
buff ~= indenter.format(field.getProperty());
}
}
foreach ( func; functions )
{
if ( func.noCode || func.isVariadic() || func.type == GirFunctionType.Callback )
continue;
if ( isInterface() && func.type == GirFunctionType.Constructor )
continue;
if ( isInterface() && func.isStatic() )
continue;
if ( func.type == GirFunctionType.Signal )
{
buff ~= "\n";
buff ~= indenter.format(func.getAddListenerDeclaration());
buff ~= indenter.format(func.getAddListenerBody());
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";
if ( func.name.among("delete", "export", "foreach", "union") )
buff ~= indenter.format("alias "~ func.name[0..$-1] ~" = "~ tokenToGtkD(func.name, wrapper.aliasses) ~";");
else if ( func.name == "ref" )
buff ~= indenter.format("alias doref = "~ tokenToGtkD(func.name, wrapper.aliasses) ~";");
buff ~= indenter.format(func.getDeclaration());
buff ~= indenter.format("{");
buff ~= indenter.format(func.getBody());
buff ~= indenter.format("}");
}
}
buff ~= indenter.format("}");
if ( isInterface() )
wrapper.writeFile(buildNormalizedPath(wrapper.outputDir, pack.srcDir, pack.name.replace(".","/"), name ~"T.d"), buff);
else
wrapper.writeFile(buildNormalizedPath(wrapper.outputDir, pack.srcDir, pack.name.replace(".","/"), 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 if ( !func.isStatic() )
{
string[] dec = func.getDeclaration();
dec[$-1] = dec[$-1].replace("override ", "");
dec[$-1] ~= ";";
buff ~= "\n";
if ( func.name.among("delete", "export", "foreach", "union") )
buff ~= indenter.format("alias "~ func.name[0..$-1] ~" = "~ tokenToGtkD(func.name, wrapper.aliasses) ~";");
buff ~= indenter.format(dec);
}
else
{
buff ~= "\n";
buff ~= indenter.format(func.getDeclaration());
buff ~= indenter.format("{");
buff ~= indenter.format(func.getBody());
buff ~= indenter.format("}");
}
}
buff ~= indenter.format("}");
}
wrapper.writeFile(buildNormalizedPath(wrapper.outputDir, pack.srcDir, pack.name.replace(".","/"), 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";
if ( func.name.among("delete", "export", "foreach", "union") )
buff ~= indenter.format("alias "~ func.name[0..$-1] ~" = "~ tokenToGtkD(func.name, wrapper.aliasses) ~";");
buff ~= indenter.format(func.getDeclaration());
buff ~= indenter.format("{");
buff ~= indenter.format(func.getBody());
buff ~= indenter.format("}");
}
if ( !noNamespace )
buff ~= indenter.format("}");
wrapper.writeFile(buildNormalizedPath(wrapper.outputDir, pack.srcDir, pack.name.replace(".","/"), 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 ( parent && !parentStruct )
parentStruct = getParent();
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);
if ( !parentStruct )
return false;
return parentStruct.hasFunction(funct);
}
private bool hasDefaultConstructor()
{
foreach ( line; lookupCode )
{
//TODO: Whitespace differences?
if ( line.strip == "public this ("~ cType ~"* "~ getHandleVar() ~", bool ownedRef = false)" )
return true;
}
return false;
}
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;
}
bool isSimpleStruct()
{
//TODO: don't use this workaround.
//TODO: For TestLogMsg, GArray and GByteArray implement array properties that are not zero terminated.
if ( cType == "PangoAttribute" || cType == "GTestLogMsg" || cType == "GArray" || cType == "GByteArray" || cType == "GtkTreeIter" )
return false;
if ( pack.name == "cairo" )
return false;
if ( lookupClass || lookupInterface || noDeclaration || noNamespace )
return false;
if ( disguised || fields.length == 0 )
return false;
if ( !fields.empty && fields[0].type )
{
// If the first field is wraped as a D class and isn't declared
// as a pointer we assume its the parent instance.
GirStruct dStruct = pack.getStruct(fields[0].type.name);
if ( dStruct && dStruct.isDClass() && !fields[0].type.cType.endsWith("*") )
return false;
}
foreach ( field; fields )
{
if ( !field.writable )
return false;
}
return true;
}
bool isDClass()
{
if ( type.among(GirStructType.Class, GirStructType.Interface) )
return true;
if ( type == GirStructType.Record && (lookupClass || lookupInterface) )
return true;
if ( "get_type" in functions && isSimpleStruct() )
return true;
return false;
}
string[] usedNamespaces()
{
string[] namespaces;
string getNamespace(GirType type)
{
if ( type.isArray() )
type = type.elementType;
if ( type.cType in wrapper.aliasses || type.cType in aliases )
return null;
if ( type.name.canFind(".") )
return type.name.split(".")[0];
return null;
}
if ( parent.canFind(".") )
namespaces ~= parent.split(".")[0];
foreach ( func; functions )
{
namespaces ~= getNamespace(func.returnType);
if ( func.instanceParam )
namespaces ~= getNamespace(func.instanceParam.type);
foreach ( param; func.params )
namespaces ~= getNamespace(param.type);
}
return namespaces.sort().uniq.array;
}
private void resolveImports()
{
if ( parentStruct && parentStruct.name != name)
{
imports ~= parentStruct.pack.name ~"."~ parentStruct.name;
}
else if ( parentStruct )
{
string QParent = getFullyQualifiedDName();
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.
const 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 ( isSimpleStruct() )
imports ~= "glib.MemorySlice";
if ( wrapper.useRuntimeLinker && (shouldFree() || isSimpleStruct()) )
imports ~= "gtkd.Loader";
if ( isSimpleStruct() )
{
foreach ( field; fields )
{
if ( field.type.name in structWrap || field.type.name in aliases )
continue;
GirStruct dType;
if ( field.type.isArray() )
dType = pack.getStruct(field.type.elementType.name);
else
dType = pack.getStruct(field.type.name);
if ( dType is this )
continue;
if ( dType && dType.isDClass() )
{
if ( !dType.pack.name.among("cairo", "glib", "gthread") )
imports ~= "gobject.ObjectG";
if ( dType.type == GirStructType.Interface || dType.lookupInterface )
imports ~= dType.pack.name ~"."~ dType.name ~"IF";
else
imports ~= dType.pack.name ~"."~ dType.name;
}
else if ( field.type.isString() || (field.type.isArray() && field.type.elementType.isString()) ) {
imports ~= "glib.Str";
imports ~= "glib.c.functions";
}
}
}
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.isDClass() )
{
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;
if ( dType.type == GirStructType.Interface || dType.lookupInterface )
imports ~= dType.pack.name ~"."~ dType.name ~"IF";
else
imports ~= dType.pack.name ~"."~ dType.name;
}
else if ( type.name.among("utf8", "filename") || type.cType.among("guchar**") ) {
imports ~= "glib.Str";
imports ~= "glib.c.functions";
}
}
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.isDClass() )
{
if ( dType.type == GirStructType.Interface || dType.lookupInterface )
imports ~= dType.pack.name ~"."~ dType.name ~"IF";
else
imports ~= dType.pack.name ~"."~ dType.name;
}
else if ( type.isString() || (type.isArray() && type.elementType.isString()) )
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 ( param.direction == GirParamDirection.Out
&& !param.type.cType.endsWith("**")
&& pack.getStruct(param.type.name) !is null
&& pack.getStruct(param.type.name).isDClass() )
imports ~= "glib.MemorySlice";
if ( param.direction == GirParamDirection.Out
&& param.type.elementType
&& pack.getStruct(param.type.elementType.name) !is null
&& pack.getStruct(param.type.elementType.name).isDClass()
&& param.type.size > 0 )
imports ~= "glib.MemorySlice";
}
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;
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;
}
}
buff ~= signal.getAddListenerDeclaration();
buff ~= signal.getAddListenerBody();
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, null);
field.parse(reader);
fields ~= field;
break;
case "record":
GirField field = new GirField(wrapper, null);
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 "source-position":
reader.skipTag();
break;
default:
warning("Unexpected tag: ", reader.front.value, " in GirUnion: ", name, reader);
}
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.23.2/source/gtd/GirType.d 0000664 0000000 0000000 00000012253 14562767404 0017050 0 ustar 00root root 0000000 0000000 /*
* This file is part of gir-to-d.
*
* gir-to-d 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.
*
* gir-to-d 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 gir-to-d. If not, see .
*/
module gtd.GirType;
import std.algorithm: among, canFind, startsWith;
import std.array: replace, split;
import std.conv: to;
import std.range: empty;
import gtd.GirWrapper;
import gtd.XMLReader;
/**
* 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.
bool girArray = false; /// The gir file specifies this as an array. Use isArray to check if this is actually an array.
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 ( reader.front.value == "array" )
girArray = true;
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";
}
// Some GIR files have a none type name.
if (name == "none") {
cType = "void";
}
if ( cType.canFind(" const") || cType.canFind("const ") )
{
constType = true;
fixType();
}
if ( cType.canFind("unsigned ") )
{
cType = cType.replace("unsigned ", "u");
}
if ( name == "long double" )
{
name = "greal";
cType = "greal";
}
cType = cType.replace("volatile ", "");
if ( cType == "unsigned" )
cType = name;
removeInitialyUnowned();
if ( cType is null && (name == "filename" || name == "utf8") )
cType = "gchar*";
//Vala libraries can have the package name in there name twice, befoer and after the dot.
string[] arr = split(name, '.');
if ( arr.length > 1 && arr[1].startsWith(arr[0]) )
{
name = arr[1][arr[0].length .. $];
}
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") && size < 0 )
cType ~= "*";
if ( isArray() && (cType == "void" || cType.empty) )
{
if ( size > 0 )
cType = elementType.cType;
else
cType = elementType.cType ~"*";
}
}
bool isString()
{
if ( cType.startsWith("gchar*", "char*", "const(char)*") )
return true;
if ( name.among("utf8", "filename") )
return true;
if ( isArray() && elementType.cType.startsWith("gchar", "char", "const(char)") )
return true;
return false;
}
bool isArray()
{
if ( elementType is null )
return false;
// The GLib Arrays are in the GIR files as arrays but they shouldn't be wrapped as such.
if ( name.among("GLib.Array", "Array", "GLib.ByteArray", "ByteArray", "GLib.PtrArray", "PtrArray") )
return false;
if ( girArray )
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.23.2/source/gtd/GirVersion.d 0000664 0000000 0000000 00000006362 14562767404 0017560 0 ustar 00root root 0000000 0000000 /*
* This file is part of gir-to-d.
*
* gir-to-d 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.
*
* gir-to-d 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 gir-to-d. If not, see .
*/
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.23.2/source/gtd/GirWrapper.d 0000664 0000000 0000000 00000055303 14562767404 0017552 0 ustar 00root root 0000000 0000000 /*
* This file is part of gir-to-d.
*
* gir-to-d 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.
*
* gir-to-d 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 gir-to-d. If not, see .
*/
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 std.process : environment;
import gtd.DefReader;
import gtd.GirField;
import gtd.GirFunction;
import gtd.GirPackage;
import gtd.GirStruct;
import gtd.GirType;
import gtd.GirVersion;
import gtd.GlibTypes;
import gtd.IndentedStringBuilder;
import gtd.Log;
enum PrintFileMethod
{
Absolute,
Relative,
Default
}
class GirWrapper
{
bool includeComments = true;
bool useRuntimeLinker;
bool useBindDir;
bool printFiles;
PrintFileMethod printFileMethod = PrintFileMethod.Default;
string cwdOrBaseDirectory;
string inputDir;
string outputDir;
string srcDir = "./";
string commandlineGirPath;
static string licence;
static string[string] aliasses;
static GirPackage[string] packages;
public this(string inputDir, string outputDir)
{
this.inputDir = inputDir;
this.outputDir = outputDir;
}
void proccess(string lookupFileName)
{
if ( !exists(buildPath(inputDir, lookupFileName)) )
error(lookupFileName, " not found, check '--help' for more information.");
DefReader defReader = new DefReader( buildPath(inputDir, lookupFileName) );
proccess(defReader);
}
void proccess(DefReader defReader, GirPackage currentPackage = null, bool isDependency = false, GirStruct currentStruct = null)
{
while ( !defReader.empty )
{
if ( !currentPackage && defReader.key.among(
"addAliases", "addConstants", "addEnums", "addFuncts", "addStructs", "file", "move",
"struct", "class", "interface", "namespace", "noAlias", "noConstant", "noEnum", "noCallback") )
error("Found: '", defReader.key, "' before wrap.", defReader);
if ( !currentStruct && defReader.key.among(
"code", "cType", "extend", "implements", "import", "interfaceCode", "merge",
"noCode", "noExternal", "noProperty", "noSignal", "noStruct", "override", "structWrap",
"array", "in", "out", "inout", "ref") )
error("Found: '", defReader.key, "' without an active struct.", defReader);
switch ( defReader.key )
{
//Toplevel keys.
case "bindDir":
warning("Don't use bindDir, it is no longer used since the c definitions have moved.", defReader);
break;
case "includeComments":
includeComments = defReader.valueBool;
break;
case "inputRoot":
warning("Don't use inputRoot, it has been removed as it was never implemented.", defReader);
break;
case "license":
licence = defReader.readBlock().join();
break;
case "outputRoot":
if ( outputDir == "./out" )
outputDir = defReader.value;
break;
//Global keys.
case "alias":
if ( currentStruct )
loadAA(currentStruct.aliases, defReader);
else
loadAA(aliasses, defReader);
break;
case "copy":
try
copyFiles(inputDir, buildPath(outputDir, srcDir), defReader.value);
catch(FileException ex)
error(ex.msg, defReader);
break;
case "dependency":
loadDependency(defReader);
break;
case "lookup":
DefReader reader = new DefReader( buildPath(inputDir, defReader.value) );
proccess(reader, currentPackage, isDependency, currentStruct);
break;
case "srcDir":
srcDir = defReader.value;
break;
case "version":
if ( defReader.value == "end" )
break;
if ( defReader.subKey.empty )
error("No version specified.", defReader);
bool parseVersion = checkOsVersion(defReader.subKey);
bool smalerThen = false;
if ( defReader.subKey.length > 1 && defReader.subKey[0] == '<' && defReader.subKey[1].isNumber() )
{
smalerThen = true;
defReader.subKey.popFront();
}
if ( !parseVersion && defReader.subKey[0].isNumber() )
{
if ( !currentPackage )
error("Only use OS versions before wrap.", defReader);
parseVersion = defReader.subKey <= currentPackage._version;
if ( smalerThen )
parseVersion = !parseVersion;
}
if ( defReader.value == "start" )
{
if ( parseVersion )
break;
defReader.skipBlock();
}
if ( !parseVersion )
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;
case "wrap":
if ( isDependency )
{
currentPackage.name = defReader.value;
break;
}
if ( outputDir.empty )
error("Found wrap while outputRoot isn't set", defReader);
if (defReader.value in packages)
error("Package '", defReader.value, "' is already defined.", defReader);
currentStruct = null;
currentPackage = new GirPackage(defReader.value, this, srcDir);
packages[defReader.value] = currentPackage;
break;
//Package keys
case "addAliases":
currentPackage.lookupAliases ~= defReader.readBlock();
break;
case "addConstants":
currentPackage.lookupConstants ~= defReader.readBlock();
break;
case "addEnums":
currentPackage.lookupEnums ~= defReader.readBlock();
break;
case "addFuncts":
currentPackage.lookupFuncts ~= defReader.readBlock();
break;
case "addStructs":
currentPackage.lookupStructs ~= defReader.readBlock();
break;
case "file":
if ( !isAbsolute(defReader.value) )
{
currentPackage.parseGIR(getAbsoluteGirPath(defReader.value));
}
else
{
warning("Don't use absolute paths for specifying gir files.", defReader);
currentPackage.parseGIR(defReader.value);
}
break;
case "move":
string[] vals = defReader.value.split();
if ( vals.length <= 1 )
error("No destination for move: ", defReader.value, defReader);
string newFuncName = ( vals.length == 3 ) ? vals[2] : vals[0];
GirStruct dest = currentPackage.getStruct(vals[1]);
if ( dest is null )
dest = createClass(currentPackage, 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 currentPackage.collectedFunctions )
{
currentPackage.collectedFunctions[vals[0]].strct = dest;
dest.functions[newFuncName] = currentPackage.collectedFunctions[vals[0]];
dest.functions[newFuncName].name = newFuncName;
currentPackage.collectedFunctions.remove(vals[0]);
}
else
error("Unknown function ", vals[0], defReader);
break;
case "noAlias":
currentPackage.collectedAliases.remove(defReader.value);
break;
case "noConstant":
currentPackage.collectedConstants.remove(defReader.value);
break;
case "noEnum":
currentPackage.collectedEnums.remove(defReader.value);
break;
case "noCallback":
currentPackage.collectedCallbacks.remove(defReader.value);
break;
case "struct":
if ( defReader.value.empty )
{
currentStruct = null;
}
else
{
currentStruct = currentPackage.getStruct(defReader.value);
if ( currentStruct is null )
currentStruct = createClass(currentPackage, defReader.value);
}
break;
//Struct keys.
case "array":
string[] vals = defReader.value.split();
if ( vals[0] in currentStruct.functions )
{
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;
func.returnType.girArray = true;
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);
if ( !param )
error("Unknown parameter ", vals[1], " in function ", vals[0]);
elementType.name = param.type.name;
elementType.cType = param.type.cType[0..$-1];
param.type.elementType = elementType;
param.type.girArray = true;
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;
}
}
}
else if ( currentStruct.fields.map!(a => a.name).canFind(vals[0]) )
{
GirField arrayField;
int lengthID = -1;
foreach ( size_t i, field; currentStruct.fields )
{
if ( field.name == vals[0] )
arrayField = field;
else if ( field.name == vals[1] )
lengthID = cast(int)i;
if ( arrayField && lengthID > -1 )
break;
}
arrayField.type.length = lengthID;
currentStruct.fields[lengthID].isLength = true;
GirType elementType = new GirType(this);
elementType.name = arrayField.type.name;
elementType.cType = arrayField.type.cType[0..$-1];
arrayField.type.elementType = elementType;
arrayField.type.girArray = true;
}
else
{
error("Field or function: `", vals[0], "' is unknown.", defReader);
}
break;
case "class":
if ( currentStruct is null )
currentStruct = createClass(currentPackage, defReader.value);
currentStruct.lookupClass = true;
currentStruct.name = defReader.value;
break;
case "code":
currentStruct.lookupCode ~= defReader.readBlock;
break;
case "cType":
currentStruct.cType = 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 "import":
currentStruct.imports ~= defReader.value;
break;
case "interface":
if ( currentStruct is null )
currentStruct = createClass(currentPackage, defReader.value);
currentStruct.lookupInterface = true;
currentStruct.name = defReader.value;
break;
case "interfaceCode":
currentStruct.lookupInterfaceCode ~= defReader.readBlock;
break;
case "merge":
GirStruct mergeStruct = currentPackage.getStruct(defReader.value);
currentStruct.merge(mergeStruct);
GirStruct copy = currentStruct.dup();
copy.noCode = true;
copy.noExternal = true;
mergeStruct.pack.collectedStructs[defReader.value] = copy;
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 "noCode":
if ( defReader.valueBool )
{
currentStruct.noCode = true;
break;
}
if ( defReader.value !in currentStruct.functions )
error("Unknown function ", defReader.value, ". Possible values: ", currentStruct.functions.keys, defReader);
currentStruct.functions[defReader.value].noCode = true;
break;
case "noExternal":
currentStruct.noExternal = true;
break;
case "noProperty":
foreach ( field; currentStruct.fields )
{
if ( field.name == defReader.value )
{
field.noProperty = true;
break;
}
else if ( field == currentStruct.fields.back )
error("Unknown field ", defReader.value, defReader);
}
break;
case "noSignal":
currentStruct.functions[defReader.value~"-signal"].noCode = true;
break;
case "noStruct":
currentStruct.noDeclaration = true;
break;
case "structWrap":
loadAA(currentStruct.structWrap, defReader);
break;
//Function keys
case "in":
string[] vals = defReader.value.split();
if ( vals[0] !in currentStruct.functions )
error("Unknown function ", vals[0], ". Possible values: ", currentStruct.functions, defReader);
GirParam param = findParam(currentStruct, vals[0], vals[1]);
if ( !param )
error("Unknown parameter ", vals[1], " in function ", vals[0]);
param.direction = GirParamDirection.Default;
break;
case "out":
string[] vals = defReader.value.split();
if ( vals[0] !in currentStruct.functions )
error("Unknown function ", vals[0], ". Possible values: ", currentStruct.functions, defReader);
GirParam param = findParam(currentStruct, vals[0], vals[1]);
if ( !param )
error("Unknown parameter ", vals[1], " in function ", vals[0]);
param.direction = GirParamDirection.Out;
break;
case "override":
currentStruct.functions[defReader.value].lookupOverride = true;
break;
case "inout":
case "ref":
string[] vals = defReader.value.split();
if ( vals[0] !in currentStruct.functions )
error("Unknown function ", vals[0], ". Possible values: ", currentStruct.functions, defReader);
GirParam param = findParam(currentStruct, vals[0], vals[1]);
if ( !param )
error("Unknown parameter ", vals[1], " in function ", vals[0]);
param.direction = GirParamDirection.InOut;
break;
default:
error("Unknown key: ", defReader.key, defReader);
}
defReader.popFront();
}
}
void proccessGIR(string girFile)
{
GirPackage pack = new GirPackage("", this, srcDir);
if ( !isAbsolute(girFile) )
{
girFile = getAbsoluteGirPath(girFile);
}
pack.parseGIR(girFile);
packages[pack.name] = pack;
}
void printFreeFunctions()
{
foreach ( pack; packages )
{
foreach ( func; pack.collectedFunctions )
{
if ( func.movedTo.empty )
writefln("%s: %s", pack.name, func.name);
}
}
}
void writeFile(string fileName, string contents, bool createDirectory = false)
{
if ( createDirectory )
{
try
{
if ( !exists(fileName.dirName()) )
mkdirRecurse(fileName.dirName());
}
catch (FileException ex)
{
error("Failed to create directory: ", ex.msg);
}
}
std.file.write(fileName, contents);
if ( printFiles )
printFilePath(fileName);
}
string getAbsoluteGirPath(string girFile)
{
string[] girDirectories = getGirDirectories();
foreach(dir; girDirectories)
{
string girFilePath = buildNormalizedPath(dir, girFile);
if (exists(girFilePath) && isFile(girFilePath))
return girFilePath;
}
error("Couldn't find the gir file: ", girFile, " in any of: ", girDirectories.join(", "));
// Error shouldn't return anyways
assert(0);
}
private void printFilePath(string fileName)
{
with (PrintFileMethod) switch(printFileMethod)
{
case Absolute:
writeln(asAbsolutePath(fileName));
break;
case Relative:
writeln(asRelativePath(asAbsolutePath(fileName), cwdOrBaseDirectory));
break;
default:
writeln(fileName);
break;
}
}
private string[] getGirDirectories()
{
static string[] dirs;
if(dirs !is null)
{
return dirs;
}
if ( commandlineGirPath )
{
dirs ~= commandlineGirPath;
}
version(Windows)
{
foreach (p; splitter(environment.get("PATH"), ';'))
{
dirs ~= p.buildNormalizedPath("../share/gir-1.0");
}
}
else version(OSX)
{
string path = environment.get("GTK_BASEPATH");
if(path)
{
dirs ~= path.buildNormalizedPath("../share/gir-1.0");
}
path = environment.get("HOMEBREW_ROOT");
if(path)
{
dirs ~= path.buildNormalizedPath("share/gir-1.0");
}
}
else
{
string xdgDataDirs = environment.get("XDG_DATA_DIRS", "/usr/local/share:/usr/share");
foreach (p; splitter(xdgDataDirs, ':'))
{
dirs ~= p.buildNormalizedPath("gir-1.0");
}
}
return dirs.filter!(p=> exists(p) && isDir(p) ).array;
}
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, const DefReader defReader)
{
string[] vals = defReader.value.split();
if ( vals.length == 1 )
vals ~= "";
if ( vals.length == 2 )
aa[vals[0]] = vals[1];
else
error("Worng amount of arguments for key: ", defReader.key, defReader);
}
private void loadDependency(DefReader defReader)
{
if ( defReader.value == "end" )
return;
if ( defReader.subKey.empty )
error("No dependency specified.", defReader);
GirInclude inc = GirPackage.includes.get(defReader.subKey, GirInclude.init);
if ( defReader.value == "skip" )
inc.skip = true;
else if ( defReader.value == "start" )
{
inc.lookupFile = defReader.fileName;
inc.lookupLine = defReader.lineNumber;
inc.lookupText = defReader.readBlock();
}
else
error("Missing 'skip' or 'start' for dependency: ", defReader.subKey, defReader);
GirPackage.includes[defReader.subKey] = inc;
}
private void copyFiles(string srcDir, string destDir, string file)
{
string from = buildNormalizedPath(srcDir, file);
string to = buildNormalizedPath(destDir, file);
if ( !printFiles )
writefln("copying file [%s] to [%s]", from, to);
if ( isFile(from) )
{
if ( printFiles )
writeln(to);
copy(from, to);
return;
}
void copyDir(string from, string to)
{
if ( !exists(to) )
mkdirRecurse(to);
foreach ( entry; dirEntries(from, SpanMode.shallow) )
{
string dst = buildPath(to, entry.name.baseName);
if ( isDir(entry.name) )
{
copyDir(entry.name, dst);
}
else
{
if ( printFiles && !dst.endsWith("functions-runtime.d") && !dst.endsWith("functions-compiletime.d") )
printFilePath(dst);
copy(entry.name, dst);
}
}
}
copyDir(from, to);
if ( file == "cairo" )
{
if ( printFiles )
printFilePath(buildNormalizedPath(to, "c", "functions.d"));
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.noDeclaration = true;
pack.collectedStructs["lookup"~name] = strct;
return strct;
}
private bool checkOsVersion(string _version)
{
if ( _version.empty || !(_version[0].isAlpha() || _version[0] == '!') )
return false;
version(Windows)
{
return _version.among("Windows", "!OSX", "!linux", "!Linux", "!Posix") != 0;
}
else version(OSX)
{
return _version.among("!Windows", "OSX", "!linux", "!Linux", "Posix") != 0;
}
else version(linux)
{
return _version.among("!Windows", "!OSX", "linux", "Linux", "Posix") != 0;
}
else version(Posix)
{
return _version.among("!Windows", "!OSX", "!linux", "!Linux", "Posix") != 0;
}
else
{
return false;
}
}
}
/**
* Apply aliasses to the tokens in the string, and
* camelCase underscore separated tokens.
*/
string stringToGtkD(string str, string[string] aliases, bool caseConvert = true)
{
return stringToGtkD(str, aliases, null, caseConvert);
}
string stringToGtkD(string str, string[string] aliases, string[string] localAliases, bool caseConvert = true)
{
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, caseConvert));
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.endsWith("_t", "_t*", "_t**") )
return token;
else if ( token == "pid_t" || token == "size_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.23.2/source/gtd/GlibTypes.d 0000664 0000000 0000000 00000007074 14562767404 0017374 0 ustar 00root root 0000000 0000000 /*
* This file is part of gir-to-d.
*
* gir-to-d 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.
*
* gir-to-d 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 gir-to-d. If not, see .
*/
module gtd.GlibTypes;
enum string[string] glibTypes = [
"volatile": "",
"G_CONST_RETURN": "",
"gint": "int",
"guint": "uint",
"gboolean": "bool",
"_Bool": "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",
"greal": "real",
"goffset": "long",
"gsize": "size_t",
"gssize": "ptrdiff_t",
"gintptr": "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": "align_",
"body": "body_",
"cast": "cast_",
"continue": "continue_",
"debug": "debug_",
"default": "default_",
"delete": "delete_",
"deprecated": "deprecated_",
"export": "export_",
"foreach": "foreach_",
"function": "function_",
"Function": "Function_",
"in": "in_",
"instance": "instance_",
"interface": "interface_",
"module": "module_",
"new": "new_",
"out": "out_",
"package": "package_",
"real": "real_",
"ref": "ref_",
"scope": "scope_",
"string": "string_",
"switch": "switch_",
"this": "this_",
"union": "union_",
"version": "version_",
"byte": "byte_",
"shared": "shared_",
"GLIB_SYSDEF_POLLIN": "=1",
"GLIB_SYSDEF_POLLOUT": "=4",
"GLIB_SYSDEF_POLLPRI": "=2",
"GLIB_SYSDEF_POLLHUP": "=16",
"GLIB_SYSDEF_POLLERR": "=8",
"GLIB_SYSDEF_POLLNVAL": "=32",
];
/**
* Set some defaults for the basic libraries.
*/
enum string[][string] defaultLookupText = [
"Atk": [
"struct: Implementor",
"interface: Implementor",
"merge: ImplementorIface"
],
"cairo": [
"struct: Context",
"class: Context",
"struct: Surface",
"class: Surface",
"struct: Matrix",
"class: Matrix",
"struct: Pattern",
"class: Pattern",
"struct: Region",
"class: Region",
"struct: FontOptions",
"class: FontOption",
"struct: FontFace",
"class: FontFace",
"struct: ScaledFont",
"class: ScaledFont"
],
"Gdk": [
"struct: Atom",
"namespace:",
"struct: Monitor",
"class: MonitorG",
"struct: Rectangle",
"noCode: get_type",
"namespace:"
],
"GLib": [
"struct: Array",
"class: ArrayG",
"struct: ByteArray",
"class: ByteArray",
"struct: Error",
"class: ErrorG",
"struct: HashTable",
"class: HashTable",
"struct: List",
"class: ListG",
"struct: SList",
"class: ListSG",
"struct: MarkupParseContext",
"class: SimpleXML",
"struct: PtrArray",
"class: PtrArray",
"struct: Scanner",
"class: ScannerG",
"struct: String",
"class: StringG",
"struct: Tree",
"class: BBTree"
],
"GModule": [
"wrap: glib"
],
"Pango": [
"struct: AttrList",
"class: PgAttributeList"
],
"Gst": [
"wrap: gstreamer"
]
];
gir-to-d-0.23.2/source/gtd/IndentedStringBuilder.d 0000664 0000000 0000000 00000005520 14562767404 0021714 0 ustar 00root root 0000000 0000000 /*
* This file is part of gir-to-d.
*
* gir-to-d 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.
*
* gir-to-d 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 gir-to-d. If not, see .
*/
module gtd.IndentedStringBuilder;
import std.algorithm: canFind, count, 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;
int paramList = 0;
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 > 0 && endsWith(line, ");", ")") && count(line, '(') != count(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;
if ( paramList > 0 )
paramList--;
}
if ( line.empty )
{
return "\n";
}
else if ( startsWith(line, "&&", "||") )
{
text = tabs ~"\t"~ line ~"\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++;
}
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.23.2/source/gtd/LinkedHasMap.d 0000664 0000000 0000000 00000014635 14562767404 0017773 0 ustar 00root root 0000000 0000000 /*
* This file is part of gir-to-d.
*
* gir-to-d 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.
*
* gir-to-d 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 gir-to-d. If not, see .
*/
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.23.2/source/gtd/Log.d 0000664 0000000 0000000 00000006733 14562767404 0016214 0 ustar 00root root 0000000 0000000 /*
* This file is part of gir-to-d.
*
* gir-to-d 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.
*
* gir-to-d 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 gir-to-d. If not, see .
*/
module gtd.Log;
import core.stdc.stdlib : exit;
import std.stdio;
void warning(Args...)(Args args)
{
static if ( is(typeof(args[$-1].fileName)) && is(typeof(args[$-1].lineNumber)) )
{
stderr.writef("%s %s(%s): ", Color.blue("Warning"), args[$-1].fileName, args[$-1].lineNumber);
stderr.writeln(args[0..$-1]);
}
else
{
stderr.write(Color.blue("Warning"), ": ");
stderr.writeln(args);
}
}
void warningf(Args...)(Args args)
{
static if ( is(typeof(args[$-1].fileName)) && is(typeof(args[$-1].lineNumber)) )
{
stderr.writef("%s %s(%s): ", Color.blue("Warning"), args[$-1].fileName, args[$-1].lineNumber);
stderr.writefln(args[0..$-1]);
}
else
{
stderr.write(Color.blue("Warning"), ": ");
stderr.writefln(args);
}
}
void error(Args...)(Args args)
{
static if ( is(typeof(args[$-1].fileName)) && is(typeof(args[$-1].lineNumber)) )
{
stderr.writef("%s %s(%s): ", Color.red("Error"), args[$-1].fileName, args[$-1].lineNumber);
stderr.writeln(args[0..$-1]);
}
else
{
stderr.write(Color.red("Error"), ": ");
stderr.writeln(args);
}
exit(1);
}
void errorf(Args...)(Args args)
{
static if ( is(typeof(args[$-1].fileName)) && is(typeof(args[$-1].lineNumber)) )
{
stderr.writef("%s %s(%s): ", Color.red("Error"), args[$-1].fileName, args[$-1].lineNumber);
stderr.writefln(args[0..$-1]);
}
else
{
stderr.write(Color.red("Error"), ": ");
stderr.writefln(args);
}
exit(1);
}
struct Color
{
string esc;
string text;
string reset;
private static bool _useColor;
private static bool supportsColor;
static this()
{
version(Windows)
{
import core.sys.windows.winbase: GetStdHandle, STD_ERROR_HANDLE;
import core.sys.windows.wincon: GetConsoleMode, SetConsoleMode;
import core.sys.windows.windef: DWORD, HANDLE;
if ( !isatty(stderr.fileno()) )
return;
DWORD dwMode;
HANDLE err = GetStdHandle(STD_ERROR_HANDLE);
if ( !GetConsoleMode(err, &dwMode) )
return;
//ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
dwMode |= 0x0004;
//Try to set VT100 support on Windows 10.
if ( !SetConsoleMode(err, dwMode) )
return;
supportsColor = true;
_useColor = true;
}
else version(Posix)
{
if ( !isatty(stderr.fileno()) )
return;
supportsColor = true;
_useColor = true;
}
}
void toString(scope void delegate(const(char)[]) sink) const
{
if ( _useColor )
{
sink(esc);
sink(text);
sink(reset);
}
else
{
sink(text);
}
}
string toString() const
{
if ( _useColor )
return esc ~ text ~ reset;
else
return text;
}
void useColor(bool val)
{
if ( supportsColor )
_useColor = val;
}
static Color red(string text)
{
return Color("\033[1;31m", text, "\033[m");
}
static Color blue(string text)
{
return Color("\033[1;34m", text, "\033[m");
}
}
extern(C) private int isatty(int);
gir-to-d-0.23.2/source/gtd/WrapException.d 0000664 0000000 0000000 00000001511 14562767404 0020250 0 ustar 00root root 0000000 0000000 /*
* This file is part of gir-to-d.
*
* gir-to-d 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.
*
* gir-to-d 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 gir-to-d. If not, see .
*/
module gtd.WrapException;
class WrapException : Exception
{
this(A...)(auto ref A a)
{
import std.functional;
super(forward!a);
}
}
gir-to-d-0.23.2/source/gtd/XMLReader.d 0000664 0000000 0000000 00000023130 14562767404 0017244 0 ustar 00root root 0000000 0000000 /*
* This file is part of gir-to-d.
*
* gir-to-d 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.
*
* gir-to-d 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 gir-to-d. If not, see .
*/
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;
import gtd.WrapException;
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;
}
alias lineNumber = 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;
case "#x4":
buff.put('\004');
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 : WrapException
{
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))
{
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);
}
}