code
stringlengths 3
10M
| language
stringclasses 31
values |
|---|---|
/**
* Convert to Intermediate Representation (IR) for the back-end.
*
* Copyright: Copyright (C) 1999-2022 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/_tocsym.d, _toir.d)
* Documentation: https://dlang.org/phobos/dmd_toir.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/toir.d
*/
module dmd.toir;
import core.checkedint;
import core.stdc.stdio;
import core.stdc.string;
import core.stdc.stdlib;
import dmd.root.array;
import dmd.common.outbuffer;
import dmd.root.rmem;
import dmd.backend.cdef;
import dmd.backend.cc;
import dmd.backend.dt;
import dmd.backend.el;
import dmd.backend.global;
import dmd.backend.oper;
import dmd.backend.rtlsym;
import dmd.backend.symtab : SYMIDX;
import dmd.backend.ty;
import dmd.backend.type;
import dmd.aggregate;
import dmd.arraytypes;
import dmd.astenums;
import dmd.attrib;
import dmd.dclass;
import dmd.declaration;
import dmd.dmangle;
import dmd.dmodule;
import dmd.dstruct;
import dmd.dsymbol;
import dmd.dtemplate;
import dmd.toctype;
import dmd.e2ir;
import dmd.func;
import dmd.globals;
import dmd.glue;
import dmd.identifier;
import dmd.id;
import dmd.mtype;
import dmd.target;
import dmd.tocvdebug;
import dmd.tocsym;
alias toSymbol = dmd.tocsym.toSymbol;
alias toSymbol = dmd.glue.toSymbol;
/****************************************
* Our label symbol
*/
struct Label
{
block *lblock; // The block to which the label is defined.
}
/***********************************************************
* Collect state variables needed by the intermediate representation (IR)
*/
struct IRState
{
Module m; // module
private FuncDeclaration symbol; // function that code is being generate for
Symbol* shidden; // hidden parameter to function
Symbol* sthis; // 'this' parameter to function (member and nested)
Symbol* sclosure; // pointer to closure instance
Blockx* blx;
Dsymbols* deferToObj; // array of Dsymbol's to run toObjFile(bool multiobj) on later
elem* ehidden; // transmit hidden pointer to CallExp::toElem()
Symbol* startaddress;
Array!(elem*)* varsInScope; // variables that are in scope that will need destruction later
Label*[void*]* labels; // table of labels used/declared in function
const Param* params; // command line parameters
const Target* target; // target
bool mayThrow; // the expression being evaluated may throw
bool Cfile; // use C semantics
this(Module m, FuncDeclaration fd, Array!(elem*)* varsInScope, Dsymbols* deferToObj, Label*[void*]* labels,
const Param* params, const Target* target)
{
this.m = m;
this.symbol = fd;
this.varsInScope = varsInScope;
this.deferToObj = deferToObj;
this.labels = labels;
this.params = params;
this.target = target;
mayThrow = global.params.useExceptions
&& ClassDeclaration.throwable
&& !(fd && fd.hasNoEH);
this.Cfile = m.filetype == FileType.c;
}
FuncDeclaration getFunc()
{
return symbol;
}
/**********************
* Returns:
* true if do array bounds checking for the current function
*/
bool arrayBoundsCheck()
{
if (m.filetype == FileType.c)
return false;
bool result;
final switch (global.params.useArrayBounds)
{
case CHECKENABLE.off:
result = false;
break;
case CHECKENABLE.on:
result = true;
break;
case CHECKENABLE.safeonly:
{
result = false;
FuncDeclaration fd = getFunc();
if (fd)
{
Type t = fd.type;
if (t.ty == Tfunction && (cast(TypeFunction)t).trust == TRUST.safe)
result = true;
}
break;
}
case CHECKENABLE._default:
assert(0);
}
return result;
}
/****************************
* Returns:
* true if in a nothrow section of code
*/
bool isNothrow()
{
return !mayThrow;
}
}
extern (C++):
/*********************************************
* Produce elem which increments the usage count for a particular line.
* Sets corresponding bit in bitmap `m.covb[linnum]`.
* Used to implement -cov switch (coverage analysis).
* Params:
* irs = context
* loc = line and file of what line to show usage for
* Returns:
* elem that increments the line count
* References:
* https://dlang.org/dmd-windows.html#switch-cov
*/
extern (D) elem *incUsageElem(IRState *irs, const ref Loc loc)
{
uint linnum = loc.linnum;
Module m = cast(Module)irs.blx._module;
if (!m.cov || !linnum ||
loc.filename != m.srcfile.toChars())
return null;
//printf("cov = %p, covb = %p, linnum = %u\n", m.cov, m.covb, p, linnum);
linnum--; // from 1-based to 0-based
/* Set bit in covb[] indicating this is a valid code line number
*/
uint *p = m.covb;
if (p) // covb can be null if it has already been written out to its .obj file
{
assert(linnum < m.numlines);
p += linnum / ((*p).sizeof * 8);
*p |= 1 << (linnum & ((*p).sizeof * 8 - 1));
}
/* Generate: *(m.cov + linnum * 4) += 1
*/
elem *e;
e = el_ptr(m.cov);
e = el_bin(OPadd, TYnptr, e, el_long(TYuint, linnum * 4));
e = el_una(OPind, TYuint, e);
e = el_bin(OPaddass, TYuint, e, el_long(TYuint, 1));
return e;
}
/******************************************
* Return elem that evaluates to the static frame pointer for function fd.
* If fd is a member function, the returned expression will compute the value
* of fd's 'this' variable.
* 'fdp' is the parent of 'fd' if the frame pointer is being used to call 'fd'.
* 'origSc' is the original scope we inlined from.
* This routine is critical for implementing nested functions.
*/
elem *getEthis(const ref Loc loc, IRState *irs, Dsymbol fd, Dsymbol fdp = null, Dsymbol origSc = null)
{
elem *ethis;
FuncDeclaration thisfd = irs.getFunc();
Dsymbol ctxt0 = fdp ? fdp : fd; // follow either of these two
Dsymbol ctxt1 = origSc ? origSc.toParent2() : null; // contexts from template arguments
if (!fdp) fdp = fd.toParent2();
Dsymbol fdparent = fdp;
/* These two are compiler generated functions for the in and out contracts,
* and are called from an overriding function, not just the one they're
* nested inside, so this hack sets fdparent so it'll pass
*/
if (fdparent != thisfd && (fd.ident == Id.require || fd.ident == Id.ensure))
{
FuncDeclaration fdthis = thisfd;
for (size_t i = 0; ; )
{
if (i == fdthis.foverrides.dim)
{
if (i == 0)
break;
fdthis = fdthis.foverrides[0];
i = 0;
continue;
}
if (fdthis.foverrides[i] == fdp)
{
fdparent = thisfd;
break;
}
i++;
}
}
//printf("[%s] getEthis(thisfd = '%s', fd = '%s', fdparent = '%s')\n", loc.toChars(), thisfd.toPrettyChars(), fd.toPrettyChars(), fdparent.toPrettyChars());
if (fdparent == thisfd)
{
/* Going down one nesting level, i.e. we're calling
* a nested function from its enclosing function.
*/
if (irs.sclosure && !(fd.ident == Id.require || fd.ident == Id.ensure))
{
ethis = el_var(irs.sclosure);
}
else if (irs.sthis)
{
// We have a 'this' pointer for the current function
if (fdp != thisfd)
{
/* fdparent (== thisfd) is a derived member function,
* fdp is the overridden member function in base class, and
* fd is the nested function '__require' or '__ensure'.
* Even if there's a closure environment, we should give
* original stack data as the nested function frame.
* See also: SymbolExp.toElem() in e2ir.c (https://issues.dlang.org/show_bug.cgi?id=9383 fix)
*/
/* Address of 'sthis' gives the 'this' for the nested
* function.
*/
//printf("L%d fd = %s, fdparent = %s, fd.toParent2() = %s\n",
// __LINE__, fd.toPrettyChars(), fdparent.toPrettyChars(), fdp.toPrettyChars());
assert(fd.ident == Id.require || fd.ident == Id.ensure);
assert(thisfd.hasNestedFrameRefs());
ClassDeclaration cdp = fdp.isThis().isClassDeclaration();
ClassDeclaration cd = thisfd.isThis().isClassDeclaration();
assert(cdp && cd);
int offset;
cdp.isBaseOf(cd, &offset);
assert(offset != ClassDeclaration.OFFSET_RUNTIME);
//printf("%s to %s, offset = %d\n", cd.toChars(), cdp.toChars(), offset);
if (offset)
{
/* https://issues.dlang.org/show_bug.cgi?id=7517: If fdp is declared in interface, offset the
* 'this' pointer to get correct interface type reference.
*/
Symbol *stmp = symbol_genauto(TYnptr);
ethis = el_bin(OPadd, TYnptr, el_var(irs.sthis), el_long(TYsize_t, offset));
ethis = el_bin(OPeq, TYnptr, el_var(stmp), ethis);
ethis = el_combine(ethis, el_ptr(stmp));
//elem_print(ethis);
}
else
ethis = el_ptr(irs.sthis);
}
else if (thisfd.hasNestedFrameRefs())
{
/* Local variables are referenced, can't skip.
* Address of 'sthis' gives the 'this' for the nested
* function.
*/
ethis = el_ptr(irs.sthis);
}
else
{
/* If no variables in the current function's frame are
* referenced by nested functions, then we can 'skip'
* adding this frame into the linked list of stack
* frames.
*/
ethis = el_var(irs.sthis);
}
}
else
{
/* No 'this' pointer for current function,
*/
if (thisfd.hasNestedFrameRefs())
{
/* OPframeptr is an operator that gets the frame pointer
* for the current function, i.e. for the x86 it gets
* the value of EBP
*/
ethis = el_long(TYnptr, 0);
ethis.Eoper = OPframeptr;
}
else
{
/* Use null if no references to the current function's frame
*/
ethis = el_long(TYnptr, 0);
}
}
}
else
{
if (!irs.sthis) // if no frame pointer for this function
{
fd.error(loc, "is a nested function and cannot be accessed from `%s`", irs.getFunc().toPrettyChars());
return el_long(TYnptr, 0); // error recovery
}
/* Go up a nesting level, i.e. we need to find the 'this'
* of an enclosing function.
* Our 'enclosing function' may also be an inner class.
*/
ethis = el_var(irs.sthis);
Dsymbol s = thisfd;
while (fd != s)
{
//printf("\ts = '%s'\n", s.toChars());
thisfd = s.isFuncDeclaration();
if (thisfd)
{
/* Enclosing function is a function.
*/
// Error should have been caught by front end
assert(thisfd.isNested() || thisfd.vthis);
// pick one context
ethis = fixEthis2(ethis, thisfd, thisfd.followInstantiationContext(ctxt0, ctxt1));
}
else
{
/* Enclosed by an aggregate. That means the current
* function must be a member function of that aggregate.
*/
AggregateDeclaration ad = s.isAggregateDeclaration();
if (!ad)
{
Lnoframe:
irs.getFunc().error(loc, "cannot get frame pointer to `%s`", fd.toPrettyChars());
return el_long(TYnptr, 0); // error recovery
}
ClassDeclaration cd = ad.isClassDeclaration();
ClassDeclaration cdx = fd.isClassDeclaration();
if (cd && cdx && cdx.isBaseOf(cd, null))
break;
StructDeclaration sd = ad.isStructDeclaration();
if (fd == sd)
break;
if (!ad.isNested() || !(ad.vthis || ad.vthis2))
goto Lnoframe;
bool i = ad.followInstantiationContext(ctxt0, ctxt1);
const voffset = i ? ad.vthis2.offset : ad.vthis.offset;
ethis = el_bin(OPadd, TYnptr, ethis, el_long(TYsize_t, voffset));
ethis = el_una(OPind, TYnptr, ethis);
}
if (fdparent == s.toParentP(ctxt0, ctxt1))
break;
/* Remember that frames for functions that have no
* nested references are skipped in the linked list
* of frames.
*/
FuncDeclaration fdp2 = s.toParentP(ctxt0, ctxt1).isFuncDeclaration();
if (fdp2 && fdp2.hasNestedFrameRefs())
ethis = el_una(OPind, TYnptr, ethis);
s = s.toParentP(ctxt0, ctxt1);
assert(s);
}
}
version (none)
{
printf("ethis:\n");
elem_print(ethis);
printf("\n");
}
return ethis;
}
/************************
* Select one context pointer from a dual-context array
* Returns:
* *(ethis + offset);
*/
elem *fixEthis2(elem *ethis, FuncDeclaration fd, bool ctxt2 = false)
{
if (fd && fd.hasDualContext())
{
if (ctxt2)
ethis = el_bin(OPadd, TYnptr, ethis, el_long(TYsize_t, tysize(TYnptr)));
ethis = el_una(OPind, TYnptr, ethis);
}
return ethis;
}
/*************************
* Initialize the hidden aggregate member, vthis, with
* the context pointer.
* Returns:
* *(ey + (ethis2 ? ad.vthis2 : ad.vthis).offset) = this;
*/
elem *setEthis(const ref Loc loc, IRState *irs, elem *ey, AggregateDeclaration ad, bool setthis2 = false)
{
elem *ethis;
FuncDeclaration thisfd = irs.getFunc();
int offset = 0;
Dsymbol adp = setthis2 ? ad.toParent2(): ad.toParentLocal(); // class/func we're nested in
//printf("[%s] setEthis(ad = %s, adp = %s, thisfd = %s)\n", loc.toChars(), ad.toChars(), adp.toChars(), thisfd.toChars());
if (adp == thisfd)
{
ethis = getEthis(loc, irs, ad);
}
else if (thisfd.vthis && !thisfd.hasDualContext() &&
(adp == thisfd.toParent2() ||
(adp.isClassDeclaration() &&
adp.isClassDeclaration().isBaseOf(thisfd.toParent2().isClassDeclaration(), &offset)
)
)
)
{
/* Class we're new'ing is at the same level as thisfd
*/
assert(offset == 0); // BUG: should handle this case
ethis = el_var(irs.sthis);
}
else
{
ethis = getEthis(loc, irs, adp);
FuncDeclaration fdp = adp.isFuncDeclaration();
if (fdp && fdp.hasNestedFrameRefs())
ethis = el_una(OPaddr, TYnptr, ethis);
}
assert(!setthis2 || ad.vthis2);
const voffset = setthis2 ? ad.vthis2.offset : ad.vthis.offset;
ey = el_bin(OPadd, TYnptr, ey, el_long(TYsize_t, voffset));
ey = el_una(OPind, TYnptr, ey);
ey = el_bin(OPeq, TYnptr, ey, ethis);
return ey;
}
enum NotIntrinsic = -1;
enum OPtoPrec = OPMAX + 1; // front end only
/*******************************************
* Convert intrinsic function to operator.
* Returns:
* the operator as backend OPER,
* NotIntrinsic if not an intrinsic function,
* OPtoPrec if frontend-only intrinsic
*/
int intrinsic_op(FuncDeclaration fd)
{
int op = NotIntrinsic;
fd = fd.toAliasFunc();
if (fd.isDeprecated())
return op;
//printf("intrinsic_op(%s)\n", name);
const Identifier id3 = fd.ident;
// Look for [core|std].module.function as id3.id2.id1 ...
auto m = fd.getModule();
if (!m || !m.md)
return op;
const md = m.md;
const Identifier id2 = md.id;
if (md.packages.length == 0)
return op;
// get type of first argument
auto tf = fd.type ? fd.type.isTypeFunction() : null;
auto param1 = tf && tf.parameterList.length > 0 ? tf.parameterList[0] : null;
auto argtype1 = param1 ? param1.type : null;
const Identifier id1 = md.packages[0];
// ... except std.math package and core.stdc.stdarg.va_start.
if (md.packages.length == 2)
{
// Matches any module in std.math.*
if (md.packages[1] == Id.math && id1 == Id.std)
{
goto Lstdmath;
}
goto Lva_start;
}
if (id1 == Id.std && id2 == Id.math)
{
Lstdmath:
if (argtype1 is Type.tfloat80 || id3 == Id._sqrt)
goto Lmath;
if (id3 == Id.fabs &&
(argtype1 is Type.tfloat32 || argtype1 is Type.tfloat64))
{
op = OPabs;
}
}
else if (id1 == Id.core)
{
if (id2 == Id.math)
{
Lmath:
if (argtype1 is Type.tfloat80 || argtype1 is Type.tfloat32 || argtype1 is Type.tfloat64)
{
if (id3 == Id.cos) op = OPcos;
else if (id3 == Id.sin) op = OPsin;
else if (id3 == Id.fabs) op = OPabs;
else if (id3 == Id.rint) op = OPrint;
else if (id3 == Id._sqrt) op = OPsqrt;
else if (id3 == Id.yl2x) op = OPyl2x;
else if (id3 == Id.ldexp) op = OPscale;
else if (id3 == Id.rndtol) op = OPrndtol;
else if (id3 == Id.yl2xp1) op = OPyl2xp1;
else if (id3 == Id.toPrec) op = OPtoPrec;
}
}
else if (id2 == Id.simd)
{
if (id3 == Id.__prefetch) op = OPprefetch;
else if (id3 == Id.__simd_sto) op = OPvector;
else if (id3 == Id.__simd) op = OPvector;
else if (id3 == Id.__simd_ib) op = OPvector;
}
else if (id2 == Id.bitop)
{
if (id3 == Id.volatileLoad) op = OPind;
else if (id3 == Id.volatileStore) op = OPeq;
else if (id3 == Id.bsf) op = OPbsf;
else if (id3 == Id.bsr) op = OPbsr;
else if (id3 == Id.btc) op = OPbtc;
else if (id3 == Id.btr) op = OPbtr;
else if (id3 == Id.bts) op = OPbts;
else if (id3 == Id.inp) op = OPinp;
else if (id3 == Id.inpl) op = OPinp;
else if (id3 == Id.inpw) op = OPinp;
else if (id3 == Id.outp) op = OPoutp;
else if (id3 == Id.outpl) op = OPoutp;
else if (id3 == Id.outpw) op = OPoutp;
else if (id3 == Id.bswap) op = OPbswap;
else if (id3 == Id._popcnt) op = OPpopcnt;
}
else if (id2 == Id.volatile)
{
if (id3 == Id.volatileLoad) op = OPind;
else if (id3 == Id.volatileStore) op = OPeq;
}
}
if (!target.is64bit)
// No 64-bit bsf bsr in 32bit mode
{
if ((op == OPbsf || op == OPbsr) && argtype1 is Type.tuns64)
return NotIntrinsic;
}
return op;
Lva_start:
if (target.is64bit &&
fd.toParent().isTemplateInstance() &&
id3 == Id.va_start &&
id2 == Id.stdarg &&
md.packages[1] == Id.stdc &&
id1 == Id.core)
{
return OPva_start;
}
return op;
}
/**************************************
* Given an expression e that is an array,
* determine and set the 'length' variable.
* Input:
* lengthVar Symbol of 'length' variable
* &e expression that is the array
* t1 Type of the array
* Output:
* e is rewritten to avoid side effects
* Returns:
* expression that initializes 'length'
*/
elem *resolveLengthVar(VarDeclaration lengthVar, elem **pe, Type t1)
{
//printf("resolveLengthVar()\n");
elem *einit = null;
if (lengthVar && !(lengthVar.storage_class & STC.const_))
{
elem *elength;
Symbol *slength;
if (t1.ty == Tsarray)
{
TypeSArray tsa = cast(TypeSArray)t1;
dinteger_t length = tsa.dim.toInteger();
elength = el_long(TYsize_t, length);
goto L3;
}
else if (t1.ty == Tarray)
{
elength = *pe;
*pe = el_same(&elength);
elength = el_una(target.is64bit ? OP128_64 : OP64_32, TYsize_t, elength);
L3:
slength = toSymbol(lengthVar);
if (slength.Sclass == SCauto && slength.Ssymnum == SYMIDX.max)
symbol_add(slength);
einit = el_bin(OPeq, TYsize_t, el_var(slength), elength);
}
}
return einit;
}
/*************************************
* for a nested function 'fd' return the type of the closure
* of an outer function or aggregate. If the function is a member function
* the 'this' type is expected to be stored in 'sthis.Sthis'.
* It is always returned if it is not a void pointer.
* buildClosure() must have been called on the outer function before.
*
* Params:
* sthis = the symbol of the current 'this' derived from fd.vthis
* fd = the nested function
*/
TYPE* getParentClosureType(Symbol* sthis, FuncDeclaration fd)
{
if (sthis)
{
// only replace void*
if (sthis.Stype.Tty != TYnptr || sthis.Stype.Tnext.Tty != TYvoid)
return sthis.Stype;
}
for (Dsymbol sym = fd.toParent2(); sym; sym = sym.toParent2())
{
if (auto fn = sym.isFuncDeclaration())
if (fn.csym && fn.csym.Sscope)
return fn.csym.Sscope.Stype;
if (sym.isAggregateDeclaration())
break;
}
return sthis ? sthis.Stype : Type_toCtype(Type.tvoidptr);
}
/**************************************
* Go through the variables in function fd that are
* to be allocated in a closure, and set the .offset fields
* for those variables to their positions relative to the start
* of the closure instance.
* Also turns off nrvo for closure variables.
* Params:
* fd = function
*/
void setClosureVarOffset(FuncDeclaration fd)
{
// Nothing to do
if (!fd.needsClosure())
return;
uint offset = target.ptrsize; // leave room for previous sthis
foreach (v; fd.closureVars)
{
/* Align and allocate space for v in the closure
* just like AggregateDeclaration.addField() does.
*/
uint memsize;
uint memalignsize;
structalign_t xalign;
if (v.storage_class & STC.lazy_)
{
/* Lazy variables are really delegates,
* so give same answers that TypeDelegate would
*/
memsize = target.ptrsize * 2;
memalignsize = memsize;
xalign.setDefault();
}
else if (v.storage_class & (STC.out_ | STC.ref_))
{
// reference parameters are just pointers
memsize = target.ptrsize;
memalignsize = memsize;
xalign.setDefault();
}
else
{
memsize = cast(uint)v.type.size();
memalignsize = v.type.alignsize();
xalign = v.alignment;
}
AggregateDeclaration.alignmember(xalign, memalignsize, &offset);
v.offset = offset;
//printf("closure var %s, offset = %d\n", v.toChars(), v.offset);
offset += memsize;
/* Can't do nrvo if the variable is put in a closure, since
* what the shidden points to may no longer exist.
*/
assert(!fd.isNRVO() || fd.nrvo_var != v);
}
}
/*************************************
* Closures are implemented by taking the local variables that
* need to survive the scope of the function, and copying them
* into a gc allocated chuck of memory. That chunk, called the
* closure here, is inserted into the linked list of stack
* frames instead of the usual stack frame.
*
* buildClosure() inserts code just after the function prolog
* is complete. It allocates memory for the closure, allocates
* a local variable (sclosure) to point to it, inserts into it
* the link to the enclosing frame, and copies into it the parameters
* that are referred to in nested functions.
* In VarExp::toElem and SymOffExp::toElem, when referring to a
* variable that is in a closure, takes the offset from sclosure rather
* than from the frame pointer.
*
* getEthis() and NewExp::toElem need to use sclosure, if set, rather
* than the current frame pointer.
*/
void buildClosure(FuncDeclaration fd, IRState *irs)
{
//printf("buildClosure(fd = %s)\n", fd.toChars());
if (fd.needsClosure())
{
setClosureVarOffset(fd);
// Generate closure on the heap
// BUG: doesn't capture variadic arguments passed to this function
/* BUG: doesn't handle destructors for the local variables.
* The way to do it is to make the closure variables the fields
* of a class object:
* class Closure {
* vtbl[]
* monitor
* ptr to destructor
* sthis
* ... closure variables ...
* ~this() { call destructor }
* }
*/
//printf("FuncDeclaration.buildClosure() %s\n", fd.toChars());
/* Generate type name for closure struct */
const char *name1 = "CLOSURE.";
const char *name2 = fd.toPrettyChars();
size_t namesize = strlen(name1)+strlen(name2)+1;
char *closname = cast(char *)Mem.check(calloc(namesize, char.sizeof));
strcat(strcat(closname, name1), name2);
/* Build type for closure */
type *Closstru = type_struct_class(closname, target.ptrsize, 0, null, null, false, false, true, false);
free(closname);
auto chaintype = getParentClosureType(irs.sthis, fd);
symbol_struct_addField(Closstru.Ttag, "__chain", chaintype, 0);
Symbol *sclosure;
sclosure = symbol_name("__closptr", SCauto, type_pointer(Closstru));
sclosure.Sflags |= SFLtrue | SFLfree;
symbol_add(sclosure);
irs.sclosure = sclosure;
assert(fd.closureVars.dim);
assert(fd.closureVars[0].offset >= target.ptrsize);
foreach (v; fd.closureVars)
{
//printf("closure var %s\n", v.toChars());
// Hack for the case fail_compilation/fail10666.d,
// until proper issue 5730 fix will come.
bool isScopeDtorParam = v.edtor && (v.storage_class & STC.parameter);
if (v.needsScopeDtor() || isScopeDtorParam)
{
/* Because the value needs to survive the end of the scope!
*/
v.error("has scoped destruction, cannot build closure");
}
if (v.isargptr)
{
/* See https://issues.dlang.org/show_bug.cgi?id=2479
* This is actually a bug, but better to produce a nice
* message at compile time rather than memory corruption at runtime
*/
v.error("cannot reference variadic arguments from closure");
}
/* Set Sscope to closure */
Symbol *vsym = toSymbol(v);
assert(vsym.Sscope == null);
vsym.Sscope = sclosure;
/* Add variable as closure type member */
symbol_struct_addField(Closstru.Ttag, &vsym.Sident[0], vsym.Stype, v.offset);
//printf("closure field %s: memalignsize: %i, offset: %i\n", &vsym.Sident[0], memalignsize, v.offset);
}
// Calculate the size of the closure
VarDeclaration vlast = fd.closureVars[fd.closureVars.dim - 1];
typeof(Type.size()) lastsize;
if (vlast.storage_class & STC.lazy_)
lastsize = target.ptrsize * 2;
else if (vlast.isReference)
lastsize = target.ptrsize;
else
lastsize = vlast.type.size();
bool overflow;
const structsize = addu(vlast.offset, lastsize, overflow);
assert(!overflow && structsize <= uint.max);
//printf("structsize = %d\n", cast(uint)structsize);
Closstru.Ttag.Sstruct.Sstructsize = cast(uint)structsize;
fd.csym.Sscope = sclosure;
if (global.params.symdebug)
toDebugClosure(Closstru.Ttag);
// Allocate memory for the closure
elem *e = el_long(TYsize_t, structsize);
e = el_bin(OPcall, TYnptr, el_var(getRtlsym(RTLSYM.ALLOCMEMORY)), e);
toTraceGC(irs, e, fd.loc);
// Assign block of memory to sclosure
// sclosure = allocmemory(sz);
e = el_bin(OPeq, TYvoid, el_var(sclosure), e);
// Set the first element to sthis
// *(sclosure + 0) = sthis;
elem *ethis;
if (irs.sthis)
ethis = el_var(irs.sthis);
else
ethis = el_long(TYnptr, 0);
elem *ex = el_una(OPind, TYnptr, el_var(sclosure));
ex = el_bin(OPeq, TYnptr, ex, ethis);
e = el_combine(e, ex);
// Copy function parameters into closure
foreach (v; fd.closureVars)
{
if (!v.isParameter())
continue;
tym_t tym = totym(v.type);
const x64ref = ISX64REF(v);
if (x64ref && config.exe == EX_WIN64)
{
if (v.storage_class & STC.lazy_)
tym = TYdelegate;
}
else if (ISREF(v) && !x64ref)
tym = TYnptr; // reference parameters are just pointers
else if (v.storage_class & STC.lazy_)
tym = TYdelegate;
ex = el_bin(OPadd, TYnptr, el_var(sclosure), el_long(TYsize_t, v.offset));
ex = el_una(OPind, tym, ex);
elem *ev = el_var(toSymbol(v));
if (x64ref)
{
ev.Ety = TYnref;
ev = el_una(OPind, tym, ev);
if (tybasic(ev.Ety) == TYstruct || tybasic(ev.Ety) == TYarray)
ev.ET = Type_toCtype(v.type);
}
if (tybasic(ex.Ety) == TYstruct || tybasic(ex.Ety) == TYarray)
{
.type *t = Type_toCtype(v.type);
ex.ET = t;
ex = el_bin(OPstreq, tym, ex, ev);
ex.ET = t;
}
else
ex = el_bin(OPeq, tym, ex, ev);
e = el_combine(e, ex);
}
block_appendexp(irs.blx.curblock, e);
}
}
/*************************************
* build a debug info struct for variables captured by nested functions,
* but not in a closure.
* must be called after generating the function to fill stack offsets
* Params:
* fd = function
*/
void buildCapture(FuncDeclaration fd)
{
if (!global.params.symdebug)
return;
if (target.objectFormat() != Target.ObjectFormat.coff) // toDebugClosure only implemented for CodeView,
return; // but optlink crashes for negative field offsets
if (fd.closureVars.dim && !fd.needsClosure)
{
/* Generate type name for struct with captured variables */
const char *name1 = "CAPTURE.";
const char *name2 = fd.toPrettyChars();
size_t namesize = strlen(name1)+strlen(name2)+1;
char *capturename = cast(char *)Mem.check(calloc(namesize, char.sizeof));
strcat(strcat(capturename, name1), name2);
/* Build type for struct */
type *capturestru = type_struct_class(capturename, target.ptrsize, 0, null, null, false, false, true, false);
free(capturename);
foreach (v; fd.closureVars)
{
Symbol *vsym = toSymbol(v);
/* Add variable as capture type member */
auto soffset = vsym.Soffset;
if (fd.vthis)
soffset -= toSymbol(fd.vthis).Soffset; // see toElem.ToElemVisitor.visit(SymbolExp)
symbol_struct_addField(capturestru.Ttag, &vsym.Sident[0], vsym.Stype, cast(uint)soffset);
//printf("capture field %s: offset: %i\n", &vsym.Sident[0], v.offset);
}
// generate pseudo symbol to put into functions' Sscope
Symbol *scapture = symbol_name("__captureptr", SCalias, type_pointer(capturestru));
scapture.Sflags |= SFLtrue | SFLfree;
//symbol_add(scapture);
fd.csym.Sscope = scapture;
toDebugClosure(capturestru.Ttag);
}
}
/***************************
* Determine return style of function - whether in registers or
* through a hidden pointer to the caller's stack.
* Params:
* tf = function type to check
* needsThis = true if the function type is for a non-static member function
* Returns:
* RET.stack if return value from function is on the stack, RET.regs otherwise
*/
RET retStyle(TypeFunction tf, bool needsThis)
{
//printf("TypeFunction.retStyle() %s\n", toChars());
return target.isReturnOnStack(tf, needsThis) ? RET.stack : RET.regs;
}
|
D
|
instance DIA_DMT_1201_Dementor_EXIT(C_Info)
{
npc = DMT_1201_Dementor;
nr = 999;
condition = DIA_DMT_1201_Dementor_EXIT_Condition;
information = DIA_DMT_1201_Dementor_EXIT_Info;
permanent = TRUE;
description = Dialog_Ende;
};
func int DIA_DMT_1201_Dementor_EXIT_Condition()
{
return TRUE;
};
func void DIA_DMT_1201_Dementor_EXIT_Info()
{
B_AssignDementorTalk_Ritual_Exit();
};
instance DIA_DMT_1201_Dementor(C_Info)
{
npc = DMT_1201_Dementor;
nr = 1;
condition = DIA_DMT_1201_Dementor_Condition;
information = DIA_DMT_1201_Dementor_Info;
important = TRUE;
permanent = TRUE;
};
func int DIA_DMT_1201_Dementor_Condition()
{
if(!Npc_RefuseTalk(self))
{
return TRUE;
};
};
func void DIA_DMT_1201_Dementor_Info()
{
B_AssignDementorTalk_Ritual();
};
instance DIA_DMT_1202_Dementor_EXIT(C_Info)
{
npc = DMT_1202_Dementor;
nr = 999;
condition = DIA_DMT_1202_Dementor_EXIT_Condition;
information = DIA_DMT_1202_Dementor_EXIT_Info;
permanent = TRUE;
description = Dialog_Ende;
};
func int DIA_DMT_1202_Dementor_EXIT_Condition()
{
return TRUE;
};
func void DIA_DMT_1202_Dementor_EXIT_Info()
{
B_AssignDementorTalk_Ritual_Exit();
};
instance DIA_DMT_1202_Dementor(C_Info)
{
npc = DMT_1202_Dementor;
nr = 1;
condition = DIA_DMT_1202_Dementor_Condition;
information = DIA_DMT_1202_Dementor_Info;
important = TRUE;
permanent = TRUE;
};
func int DIA_DMT_1202_Dementor_Condition()
{
if(!Npc_RefuseTalk(self))
{
return TRUE;
};
};
func void DIA_DMT_1202_Dementor_Info()
{
B_AssignDementorTalk_Ritual();
};
instance DIA_DMT_1203_Dementor_EXIT(C_Info)
{
npc = DMT_1203_Dementor;
nr = 999;
condition = DIA_DMT_1203_Dementor_EXIT_Condition;
information = DIA_DMT_1203_Dementor_EXIT_Info;
permanent = TRUE;
description = Dialog_Ende;
};
func int DIA_DMT_1203_Dementor_EXIT_Condition()
{
return TRUE;
};
func void DIA_DMT_1203_Dementor_EXIT_Info()
{
B_AssignDementorTalk_Ritual_Exit();
};
instance DIA_DMT_1203_Dementor(C_Info)
{
npc = DMT_1203_Dementor;
nr = 1;
condition = DIA_DMT_1203_Dementor_Condition;
information = DIA_DMT_1203_Dementor_Info;
important = TRUE;
permanent = TRUE;
};
func int DIA_DMT_1203_Dementor_Condition()
{
if(!Npc_RefuseTalk(self))
{
return TRUE;
};
};
func void DIA_DMT_1203_Dementor_Info()
{
B_AssignDementorTalk_Ritual();
};
instance DIA_DMT_1204_Dementor_EXIT(C_Info)
{
npc = DMT_1204_Dementor;
nr = 999;
condition = DIA_DMT_1204_Dementor_EXIT_Condition;
information = DIA_DMT_1204_Dementor_EXIT_Info;
permanent = TRUE;
description = Dialog_Ende;
};
func int DIA_DMT_1204_Dementor_EXIT_Condition()
{
return TRUE;
};
func void DIA_DMT_1204_Dementor_EXIT_Info()
{
B_AssignDementorTalk_Ritual_Exit();
};
instance DIA_DMT_1204_Dementor(C_Info)
{
npc = DMT_1204_Dementor;
nr = 1;
condition = DIA_DMT_1204_Dementor_Condition;
information = DIA_DMT_1204_Dementor_Info;
important = TRUE;
permanent = TRUE;
};
func int DIA_DMT_1204_Dementor_Condition()
{
if(!Npc_RefuseTalk(self))
{
return TRUE;
};
};
func void DIA_DMT_1204_Dementor_Info()
{
B_AssignDementorTalk_Ritual();
};
instance DIA_DMT_1205_Dementor_EXIT(C_Info)
{
npc = DMT_1205_Dementor;
nr = 999;
condition = DIA_DMT_1205_Dementor_EXIT_Condition;
information = DIA_DMT_1205_Dementor_EXIT_Info;
permanent = TRUE;
description = Dialog_Ende;
};
func int DIA_DMT_1205_Dementor_EXIT_Condition()
{
return TRUE;
};
func void DIA_DMT_1205_Dementor_EXIT_Info()
{
B_AssignDementorTalk_Ritual_Exit();
};
instance DIA_DMT_1205_Dementor(C_Info)
{
npc = DMT_1205_Dementor;
nr = 1;
condition = DIA_DMT_1205_Dementor_Condition;
information = DIA_DMT_1205_Dementor_Info;
important = TRUE;
permanent = TRUE;
};
func int DIA_DMT_1205_Dementor_Condition()
{
if(!Npc_RefuseTalk(self))
{
return TRUE;
};
};
func void DIA_DMT_1205_Dementor_Info()
{
B_AssignDementorTalk_Ritual();
};
instance DIA_DMT_1206_Dementor_EXIT(C_Info)
{
npc = DMT_1206_Dementor;
nr = 999;
condition = DIA_DMT_1206_Dementor_EXIT_Condition;
information = DIA_DMT_1206_Dementor_EXIT_Info;
permanent = TRUE;
description = Dialog_Ende;
};
func int DIA_DMT_1206_Dementor_EXIT_Condition()
{
return TRUE;
};
func void DIA_DMT_1206_Dementor_EXIT_Info()
{
B_AssignDementorTalk_Ritual_Exit();
};
instance DIA_DMT_1206_Dementor(C_Info)
{
npc = DMT_1206_Dementor;
nr = 1;
condition = DIA_DMT_1206_Dementor_Condition;
information = DIA_DMT_1206_Dementor_Info;
important = TRUE;
permanent = TRUE;
};
func int DIA_DMT_1206_Dementor_Condition()
{
if(!Npc_RefuseTalk(self))
{
return TRUE;
};
};
func void DIA_DMT_1206_Dementor_Info()
{
B_AssignDementorTalk_Ritual();
};
instance DIA_DMT_1207_Dementor_EXIT(C_Info)
{
npc = DMT_1207_Dementor;
nr = 999;
condition = DIA_DMT_1207_Dementor_EXIT_Condition;
information = DIA_DMT_1207_Dementor_EXIT_Info;
permanent = TRUE;
description = Dialog_Ende;
};
func int DIA_DMT_1207_Dementor_EXIT_Condition()
{
return TRUE;
};
func void DIA_DMT_1207_Dementor_EXIT_Info()
{
B_AssignDementorTalk_Ritual_Exit();
};
instance DIA_DMT_1207_Dementor(C_Info)
{
npc = DMT_1207_Dementor;
nr = 1;
condition = DIA_DMT_1207_Dementor_Condition;
information = DIA_DMT_1207_Dementor_Info;
important = TRUE;
permanent = TRUE;
};
func int DIA_DMT_1207_Dementor_Condition()
{
if(!Npc_RefuseTalk(self))
{
return TRUE;
};
};
func void DIA_DMT_1207_Dementor_Info()
{
B_AssignDementorTalk_Ritual();
};
instance DIA_DMT_1208_Dementor_EXIT(C_Info)
{
npc = DMT_1208_Dementor;
nr = 999;
condition = DIA_DMT_1208_Dementor_EXIT_Condition;
information = DIA_DMT_1208_Dementor_EXIT_Info;
permanent = TRUE;
description = Dialog_Ende;
};
func int DIA_DMT_1208_Dementor_EXIT_Condition()
{
return TRUE;
};
func void DIA_DMT_1208_Dementor_EXIT_Info()
{
B_AssignDementorTalk_Ritual_Exit();
};
instance DIA_DMT_1208_Dementor(C_Info)
{
npc = DMT_1208_Dementor;
nr = 1;
condition = DIA_DMT_1208_Dementor_Condition;
information = DIA_DMT_1208_Dementor_Info;
important = TRUE;
permanent = TRUE;
};
func int DIA_DMT_1208_Dementor_Condition()
{
if(!Npc_RefuseTalk(self))
{
return TRUE;
};
};
func void DIA_DMT_1208_Dementor_Info()
{
B_AssignDementorTalk_Ritual();
};
instance DIA_DMT_1209_Dementor_EXIT(C_Info)
{
npc = DMT_1209_Dementor;
nr = 999;
condition = DIA_DMT_1209_Dementor_EXIT_Condition;
information = DIA_DMT_1209_Dementor_EXIT_Info;
permanent = TRUE;
description = Dialog_Ende;
};
func int DIA_DMT_1209_Dementor_EXIT_Condition()
{
return TRUE;
};
func void DIA_DMT_1209_Dementor_EXIT_Info()
{
B_AssignDementorTalk_Ritual_Exit();
};
instance DIA_DMT_1209_Dementor(C_Info)
{
npc = DMT_1209_Dementor;
nr = 1;
condition = DIA_DMT_1209_Dementor_Condition;
information = DIA_DMT_1209_Dementor_Info;
important = TRUE;
permanent = TRUE;
};
func int DIA_DMT_1209_Dementor_Condition()
{
if(!Npc_RefuseTalk(self))
{
return TRUE;
};
};
func void DIA_DMT_1209_Dementor_Info()
{
B_AssignDementorTalk_Ritual();
};
instance DIA_DMT_1210_Dementor_EXIT(C_Info)
{
npc = DMT_1210_Dementor;
nr = 999;
condition = DIA_DMT_1210_Dementor_EXIT_Condition;
information = DIA_DMT_1210_Dementor_EXIT_Info;
permanent = TRUE;
description = Dialog_Ende;
};
func int DIA_DMT_1210_Dementor_EXIT_Condition()
{
return TRUE;
};
func void DIA_DMT_1210_Dementor_EXIT_Info()
{
B_AssignDementorTalk_Ritual_Exit();
};
instance DIA_DMT_1210_Dementor(C_Info)
{
npc = DMT_1210_Dementor;
nr = 1;
condition = DIA_DMT_1210_Dementor_Condition;
information = DIA_DMT_1210_Dementor_Info;
important = TRUE;
permanent = TRUE;
};
func int DIA_DMT_1210_Dementor_Condition()
{
if(!Npc_RefuseTalk(self))
{
return TRUE;
};
};
func void DIA_DMT_1210_Dementor_Info()
{
B_AssignDementorTalk_Ritual();
};
instance DIA_DMT_1211_Dementor_EXIT(C_Info)
{
npc = DMT_1211_Dementor;
nr = 999;
condition = DIA_DMT_1211_Dementor_EXIT_Condition;
information = DIA_DMT_1211_Dementor_EXIT_Info;
permanent = TRUE;
description = Dialog_Ende;
};
func int DIA_DMT_1211_Dementor_EXIT_Condition()
{
return TRUE;
};
func void DIA_DMT_1211_Dementor_EXIT_Info()
{
B_AssignDementorTalk_Ritual_Exit();
};
instance DIA_DMT_1211_Dementor(C_Info)
{
npc = DMT_1211_Dementor;
nr = 1;
condition = DIA_DMT_1211_Dementor_Condition;
information = DIA_DMT_1211_Dementor_Info;
important = TRUE;
permanent = TRUE;
};
func int DIA_DMT_1211_Dementor_Condition()
{
if(!Npc_RefuseTalk(self))
{
return TRUE;
};
};
func void DIA_DMT_1211_Dementor_Info()
{
B_AssignDementorTalk_Ritual();
};
|
D
|
module proc.mod.assignMod;
import proc.mod.modification;
import proc.businessProcess;
import proc.sim.simulation;
import std.algorithm.iteration;
class AssignMod : Modification {
// part will be assigned to each of funcs
this(ulong agentID, ulong[] funcIDs) {
agentID_ = agentID;
funcIDs_ = funcIDs.dup;
}
override @property string toString() const {
return "Assign A" ~ agentID_.text ~ " to funcs: " ~ funcIDs_.text;
}
override void apply(BusinessProcess proc) {
proc(agentID_).asAgent.deps = funcIDs_;
proc.postProcess();
}
static Modification[] create(const BusinessProcess p, in Simulation defSim) {
return (new AssignModFactory(p)).findAssignments(defSim);
}
private:
ulong agentID_;
ulong[] funcIDs_;
}
import proc.sim.multiple;
import proc.sim.simulator;
import std.typecons;
import std.array;
import std.algorithm;
import std.stdio;
import std.range;
import std.conv;
import util;
private class AssignModFactory {
this(const BusinessProcess p) {
proc_ = p;
}
Modification[] findAssignments(in Simulation defSim) {
// writeln(__FUNCTION__, " (assignMod)");
Modification[] pms;
Simulation[] sims;
BusinessProcess p = proc_.clone();
Simulator sor = new Simulator(p);
ulong[ulong] durByAID;
double timeTaken;
sor.fnOnStartFunction = (ulong agentID, ulong currTime, ulong dur) {
// writeln("Start P", agentID, ", currTime=", currTime, ", dur=", dur);
durByAID[agentID] += dur;
};
foreach (ref pa; proc_.agts)
durByAID[pa.id] = 0;
timeTaken = MultiSimulator.allPathSimulate(sor, proc_, defSim, sims);
// timeTaken = generate!(() { auto sim = defSim.gdup; auto t = sor.simulate(sim); sims ~= sim; return t; })
// .takeExactly(700).mean;
// writeln("time: ", timeTaken, " -- durByAID: ", durByAID, ", ", proc_.agts.length, " agts");
auto occs = durByAID.byKeyValue().array.sort!"a.value < b.value";
//auto mn = occs[0]; //durByAID.byKeyValue().minElement!"a.value";
auto occMax = occs[$ - 1]; //durByAID.byKeyValue().maxElement!"a.value";
for (int i = 0; i < occs.length - 1; i++) {
auto mn = occs[i];
auto depsWant = (proc_(mn.key).deps ~ proc_(occMax.key).deps).dup.sort.uniq.array;
ulong[] depsCan;
// remove all funcs for which we don't have a qualification
foreach (qid; proc_(mn.key).asAgent.quals) {
if (depsWant.canFind(qid))
depsCan ~= qid;
}
if (depsCan != proc_(mn.key).deps) {
pms ~= new AssignMod(mn.key, depsCan);
// writeln("maybe ", pms[$ - 1].toString());
}
}
if (proc_(occMax.key).deps.length > 1) {
ulong[] must;
foreach (depID; proc_(occMax.key).deps) {
bool found = false;
foreach (ref res; proc_.agts)
if (res.id != occMax.key && proc_(res.id).deps.canFind(depID))
found = true;
if (!found)
must ~= depID;
}
//assert(!must.empty); // TODO must could be empty actually
if (!must.empty && must != proc_(occMax.key).deps)
pms ~= new AssignMod(occMax.key, must);
}
return pms;
}
private:
const BusinessProcess proc_;
}
|
D
|
/// rpc using a simple tcp based protocol
///
/// author: fawzi
//
// Copyright 2008-2010 the blip developer group
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
module blip.parallel.rpc.RpcStcp;
import blip.parallel.rpc.RpcBase;
import blip.parallel.rpc.RpcMixins;
import blip.io.Console;
import blip.serialization.Serialization;
import blip.container.GrowableArray;
import blip.BasicModels;
import blip.util.TangoConvert;
import blip.core.Array;
import blip.util.TangoLog;
import blip.sync.UniqueNumber;
import blip.io.IOArray;
import blip.parallel.smp.WorkManager;
import blip.io.BasicIO;
import blip.io.StreamConverters;
import blip.io.Console;
import blip.io.Socket;
import blip.io.BufferIn;
import blip.io.BasicStreams;
import blip.time.Time;
import blip.time.Clock;
import blip.sync.Atomic;
import blip.stdc.unistd;
import blip.container.HashMap;
import blip.math.random.Random;
import blip.container.Pool;
import blip.container.Cache;
import blip.util.RefCount;
import blip.core.Boxer;
import blip.stdc.string:strlen;
import blip.io.EventWatcher;
import blip.Comp;
/// represents a request to another handler
///
/// to do to support recoverable close:
/// + restart requests that will not be answered (sent to an already closed socket)
/// (this should not be too difficult, now that we use StcpRequest, but some synchronization details will)
struct StcpRequest{
Exception exception;
ParsedUrl url;
StcpConnection connection;
void delegate(Serializer)serArgs;
void delegate(Unserializer)unserRes;
TaskI toResume;
char[22] reqBuf;
PoolI!(StcpRequest*) pool;
static PoolI!(StcpRequest*) gPool;
static this(){
gPool=cachedPool(function StcpRequest*(PoolI!(StcpRequest*)p){
auto res=new StcpRequest;
res.pool=p;
version(TrackStcpRequests){
sinkTogether(sout,delegate void(CharSink s){
dumper(s)("StcpRequest@")(cast(void*)res)(" created\n");
});
}
return res;
});
}
void clear(){
exception=null;
url=ParsedUrl.init;
connection=null;
serArgs=null;
unserRes=null;
toResume=null;
}
void release0(){
if (connection!is null){
connection.rmLocalUser();
connection=null;
}
if (pool!is null){
refCount=1;
pool.giveBack(this);
version(TrackStcpRequests){
sinkTogether(sout,delegate void(CharSink s){
dumper(s)("gave StcpRequest@")(cast(void*)this)(" to pool@")(cast(void*)pool)("\n");
});
}
} else {
clear();
delete this;
version(TrackStcpRequests){
sinkTogether(sout,delegate void(CharSink s){
dumper(s)("destroyed StcpRequest@")(cast(void*)this)("\n");
});
}
}
}
mixin RefCountMixin!();
/// this is the method to call to start the request
void doRequest(){
retain();// for sendRequest
// always delay (even oneway) to catch at least immediate send erorrs, and to ensure that one can use on stack delegates/arguments in the serialization...
toResume=taskAtt.val;
toResume.delay(delegate void(){
Task("sendReq",&this.sendRequest).autorelease.submit(connection.serTask);
});
if (exception!is null){
throw exception;
}
}
/// sends the request, is called from within the serialization task of the connection
void sendRequest(){
try{
auto res=formatInt(reqBuf[],connection.nextRequestId);
url.anchor=res; // makes struct non copiable!!!
if (unserRes){
retain(); // for decodeAnswer
// register callback
connection.protocolHandler.addPendingRequest(urlDecode(url.anchor),&this.decodeAnswer);
}
char[256] buf2=void;
version(TrackRpc){
sinkTogether(connection.log,delegate void(CharSink s){
dumper(s)(taskAtt.val)(" sending request for ")(&url.urlWriter)("\n");
});
}
connection.serializer(url.pathAndRest(buf2));
serArgs(connection.serializer);
connection.outStream.flush();
} catch(Exception o){
exception=new Exception(collectAppender(delegate void(CharSink s){
dumper(s)("exception in sending request for url")(&url.urlWriter);
}),__FILE__,__LINE__,o);
}
if (unserRes is null) toResume.resubmitDelayed(toResume.delayLevel-1);
release();
}
/// decodes the answer, this is appended to the pending requests
void decodeAnswer(ParsedUrl urlAnsw,Unserializer u){
assert(unserRes!is null,"called decodeAnswer of oneway method with url "~url.url());
try{
version(TrackRpc){
sinkTogether(connection.log,delegate void(CharSink s){
dumper(s)(taskAtt.val)(" decoding answer to ")(&url.urlWriter)(" with url ")(&urlAnsw.urlWriter)("\n");
});
}
int resKind;
u(resKind);
version(TrackRpc){
sinkTogether(connection.log,delegate void(CharSink s){
dumper(s)(taskAtt.val)(" decoding answer to ")(&url.urlWriter)(" has kind ")(resKind)("\n");
});
}
switch (resKind){
case 0:
break;
case 1:
unserRes(u);
break;
case 2:{
char[] errMsg;
u(errMsg);
exception=new RpcException(errMsg~" calling "~url.url(),__FILE__,__LINE__);
}
break;
case 3:{
char[] errMsg;
u(errMsg);
exception=new RpcException(errMsg~" calling "~url.url(),__FILE__,__LINE__);
}
break;
default:
exception=new RpcException("unknown resKind "~to!(string )(resKind)~
" calling "~url.url(),__FILE__,__LINE__);
}
} catch (Exception o){
exception=new Exception("exception decoding res for url "~url.url(),__FILE__,__LINE__,o);
}
version(TrackRpc){
sinkTogether(connection.log,delegate void(CharSink s){
dumper(s)(taskAtt.val)(" finished decoding task for ")(&url.urlWriter);
if (exception!is null){
dumper(s)(" with exception ")(exception);
}
s("\n");
});
}
toResume.resubmitDelayed(toResume.delayLevel-1);
release();
}
/// creates a request and returns it
static StcpRequest*opCall(StcpConnection connection,ParsedUrl url,void delegate(Serializer)serArgs,
void delegate(Unserializer)unserRes){
auto res=gPool.getObj();
res.url=url;
res.connection=connection;
res.serArgs=serArgs;
res.unserRes=unserRes;
return res;
}
/// performs a request
static void performRequest(StcpConnection connection,ParsedUrl url,void delegate(Serializer)serArgs,
void delegate(Unserializer)unserRes)
{
auto res=StcpRequest(connection,url,serArgs,unserRes);
version(TrackStcpRequests){
sinkTogether(sout,delegate void(CharSink s){
dumper(s)(&url.urlWriter)(" uses StcpRequest@")(cast(void*)res)("\n");
});
}
res.doRequest();
if (res.exception!is null)
throw res.exception; // release? the exception might need this...
res.release();
}
}
/// represent a connection with an host
class StcpConnection{
enum Status{
Setup,
Running,
Stopping,
Stopped,
}
StcpProtocolHandler protocolHandler;
BasicSocket sock;
BufferedBinStream outStream;
BufferIn!(void) readIn;
Reader!(char) charReader;
SequentialTask serTask; /// sequential task in which sending should be performed
TaskI requestsTask; /// reference to the task that is doing the unserialization/handling requests, worth keeping?
Serializer serializer;
Unserializer unserializer;
size_t localUsers=1;
Time lastUse; // valid only if localUsers is 0
TargetHost targetHost;
Status status=Status.Setup;
size_t lastReqId;
CharSink log;
LoopHandlerI loop;
override equals_t opEquals(Object o){
return this is o;
}
override int opCmp(Object o){
size_t a=cast(size_t)cast(void*)this;
size_t b=cast(size_t)cast(void*)o;
return ((a<b)?-1:((a==b)?0:1));
}
size_t nextRequestId(){
synchronized(this){
lastReqId=protocolHandler.newRequestId.next();
return lastReqId;
}
}
final void writeExact(void[] src){
this.sock.writeExactTout(src,loop);
}
final size_t rawReadInto(void[] dest){
return this.sock.rawReadIntoTout(dest,loop);
}
final void rawReadExact(void[]dest){
readExact(&this.rawReadInto,dest);
}
this(StcpProtocolHandler protocolHandler,TargetHost targetHost,BasicSocket sock){
this.protocolHandler=protocolHandler;
this.targetHost=targetHost;
this.sock=sock;
this.loop=protocolHandler.loop;
version(StcpNoCache){}
else {
this.sock.noDelay(true); // use no delay to reduce the latency
}
//this.sock.keepalive(true);
serTask=new SequentialTask("stcpSerTask",defaultTask,true);
// should limit buffer to 1280 or 1500 or multiples of them? (jumbo frames)
outStream=new BufferedBinStream(&this.sock.desc,&this.writeExact,3000,&this.sock.flush,&this.sock.close);
readIn=new BufferIn!(void)(&this.sock.desc,&this.rawReadInto);
version(StcpTextualSerialization){
auto r=new BufferIn!(char)(&this.sock.desc,cast(size_t delegate(cstring))&this.rawReadInto);
//ReinterpretReader!(void,char) r=readIn.reinterpretReader!(char)();
charReader=r;
serializer=new JsonSerializer!(char)(&outStream.desc,outStream.charSink());
unserializer=new JsonUnserializer!(char)(charReader);
} else {
version(StcpNoCache){
serializer=new SBinSerializer(&this.writeExact);
unserializer=new SBinUnserializer(&this.rawReadExact);
} else {
serializer=new SBinSerializer(&outStream.desc,outStream.binSink());
unserializer=new SBinUnserializer(readIn);
}
}
localUsers=1;
log=protocolHandler.log;
version(TrackRpc){
sinkTogether(log,delegate void(CharSink s){
dumper(s)("created new connection StcpConnection@")(cast(void*)this)
(" in StcpProtocolHandler@")(cast(void*)protocolHandler)
(" to ")(targetHost)(" on socket ")(this.sock)("\n");
});
}
}
this(StcpProtocolHandler protocolHandler,TargetHost targetHost){
this(protocolHandler,targetHost,BasicSocket(targetHost));
}
bool tryAddLocalUser(){
synchronized(this){
if (localUsers==0) return false;
++localUsers;
return true;
}
}
// stuff to keep track of the users (and allow in the future to close a unused connection)
void addLocalUser(){
synchronized(this){
if (atomicAdd(localUsers,1)==0){
throw new Exception("localUsers was 0 in addLocalUser",__FILE__,__LINE__);
}
}
}
void rmLocalUser(){
synchronized(this){
auto oldL=atomicAdd(localUsers,-1);
if (oldL==0){
throw new Exception("localUsers was 0 in rmLocalUser",__FILE__,__LINE__);
}
if (oldL==1){
lastUse=Clock.now;
}
}
}
/// sends back a result on this connection
void sendReply(ubyte[] reqId,void delegate(Serializer) serRes){
version(TrackRpc){
sinkTogether(log,delegate void(CharSink s){
dumper(s)("sendReply #")(urlEncode2(reqId))(" working in task ")(taskAtt.val)("\n");
});
}
Task("sendReply",delegate void(){
try{
char[128] buf2;
size_t i=5;
buf2[0..i]="/req#";
auto rc=urlEncode(reqId);
buf2[i..i+rc.length]=rc;
version(TrackRpc){
sinkTogether(log,delegate void(CharSink s){
dumper(s)(taskAtt.val)(" sending reply for ")(buf2[0..i+rc.length])(" start\n");
});
}
serializer(buf2[0..i+rc.length]);
serRes(serializer);
outStream.flush();
version(TrackRpc){
sinkTogether(log,delegate void(CharSink s){
dumper(s)(taskAtt.val)(" sending reply for ")(buf2[0..i+rc.length])(" success\n");
});
}
} catch(Exception o){
sinkTogether(log,delegate void(CharSink s){
dumper(s)("exception in sendReply sending result of #")(urlEncode2(reqId))(" ")(o)("\n");
});
}
}).autorelease.executeNow(serTask);
}
// loop that handles incoming requests on this connection, this defines requestsTask
void handleRequests(){
assert(requestsTask is null);
requestsTask=taskAtt.val;
requestsTask.retain();
scope(exit){requestsTask.release(); requestsTask=null;}
try{
synchronized(this){
if (status!=Status.Setup){
throw new Exception("invalid status",__FILE__,__LINE__);
}
status=Status.Running;
}
Task("checkUrl",&this.checkUrl).autorelease.submitYield();
while(status<Status.Stopping){
processRequest();
}
synchronized(this){
status=Status.Stopped;
}
} catch (Exception e){
protocolHandler.lostConnection(this,e);
return;
}
protocolHandler.lostConnection(this,null);
}
/// ask other party for its url, and if not yet done, registers this connection as handling
/// that url (this helps to take care of different namings for the same host)
void checkUrl(){
char[128] buf=void;
auto arr=lGrowableArray!(char)(buf,0,GASharing.Local);
arr("stcp://");
ParsedUrl.dumpHost(&arr.appendArr,targetHost.host);
dumper(&arr.appendArr)(":")(targetHost.port);
if (protocolHandler.group.length!=1){
arr(protocolHandler.group);
} else if (protocolHandler.port.length>0 && protocolHandler.server !is null) {
dumper(&arr.appendArr)(".lp")(protocolHandler.port);
}
arr("/serv/publisher/handlerUrl");
char[] otherUrl;
rpcManualResCall(otherUrl,arr.data);
arr.deallocData();
auto pUrl=ParsedUrl.parseUrl(otherUrl);
if (pUrl.host!=targetHost.host || pUrl.port!=targetHost.port){
TargetHost newH;
newH.host=pUrl.host.dup;
auto l=find(pUrl.port,".");
newH.port=pUrl.port[0..l].dup;
synchronized(protocolHandler.connections){
auto oldC=newH in protocolHandler.connections;
if (oldC!is null){
if ((*oldC) is this) return;
sinkTogether(log,delegate void(CharSink s){
dumper(s)("replacing connection to ")(newH)
(" from ")(*oldC)("@")(cast(void*)*oldC)
(" to ")(this)("@")(cast(void*)this)("\n");
});
}
protocolHandler.connections[newH]=this;
}
}
}
/// handler that handles a request from connection c
void processRequest(){
char[512] buf;
char[]path=buf;
unserializer(path);
addLocalUser();
ParsedUrl url=ParsedUrl.parsePath(path);
protocolHandler.handleRequest(url,unserializer,&this.sendReply);
}
// closes the connection
void closeConnection(){
synchronized(this){
if (status==Status.Running){
status=Status.Stopping;
} else {
status=Status.Stopped;
}
}
outStream.close();
readIn.shutdownInput();
}
}
/// handles vending (and possibly also receiving the results if using one channel for both)
class StcpProtocolHandler: ProtocolHandler{
static string [] selfHostnames;
CharSink log;
RandomSync rand;
LoopHandlerI loop;
// well known ports: 0-1023 (needs root)
// registered ports: 1024-49151 (should be registred at iana)
// dynamic ports: 49152-65535 (free usage)
// now uses the dynamic ports as fallback, should use a narrower range or ports 24250-24320 that are unassigned (but should be registred...)??
ushort fallBackPortMin=49152;
ushort fallBackPortMax=65535; // this is exclusive...
static StcpProtocolHandler[string] stcpProtocolHandlers;
/// adds a hostname for this host (or an ip address), and begins to use it to build urls
static void pushSelfHostname(string hostName) {
string[] newNames= [hostName]~selfHostnames;
selfHostnames=newNames;
}
/// those that can actually handle the given protocol
static ProtocolHandler findHandlerForUrl(ParsedUrl url){
if (url.protocol.length>0 && url.protocol!="stcp"){
throw new RpcException("unexpected protocol instead of stcp in "~url.url(),
__FILE__,__LINE__);
}
string port=url.port;
string group;
auto gStart=find(port,'.');
if (gStart<port.length) {
group=port[gStart..$];
port=port[0..gStart];
} else {
group=".";
}
synchronized(StcpProtocolHandler.classinfo){
auto pHP= group in stcpProtocolHandlers;
if (pHP !is null){
return *pHP;
}
}
auto newH=new StcpProtocolHandler(group,port,serr.call);
synchronized(StcpProtocolHandler.classinfo){
auto pHP= group in stcpProtocolHandlers;
if (pHP !is null){
return *pHP;
}
stcpProtocolHandlers[group]=newH;
return newH;
}
}
HashMap!(TargetHost,StcpConnection) connections;
StcpConnection[] doubleConnections;
string group;
string port;
UniqueNumber!(size_t) newRequestId;
SocketServer server;
this(){
version(TrackRpc){
sinkTogether(sout,delegate void(CharSink s){
dumper(s)("creating StcpProtocolHandler@")(cast(void*)this)("\n");
});
}
super();
log=serr.call;
loop=noToutWatcher;
rand=new RandomSync();
connections=new HashMap!(TargetHost,StcpConnection)();
auto vendor=new DefaultVendor(this);
servPublisher.publishObject(vendor,"publisher",true,Publisher.Flags.Public);
}
this(string group,string port,void delegate(cstring) log=null){
version(TrackRpc){
sinkTogether(sout,delegate void(CharSink s){
dumper(s)("creating StcpProtocolHandler@")(cast(void*)this)(" for group '")(group)("' and port: ")(port)("\n");
});
}
super();
this.log=log;
if (log is null) this.log=serr.call;
loop=noToutWatcher;
rand=new RandomSync();
connections=new HashMap!(TargetHost,StcpConnection)();
this.group=((group.length==0)?"."[]:group);
assert(this.group[0]=='.',"group should start with .");
this.port=port;
updateUrl();
newRequestId=UniqueNumber!(size_t)(10);
auto vendor=new DefaultVendor(this);
servPublisher.publishObject(vendor,"publisher",true,Publisher.Flags.Public);
}
/// updates the url of this handler (to be called when the port changes)
void updateUrl(){
char[128] buf=void;
auto arr=lGrowableArray!(char)(buf,0,GASharing.Local);
arr("stcp://");
ParsedUrl.dumpHost(&arr.appendArr,selfHostnames[0]);
dumper(&arr.appendArr)(":")(port);
if (group.length!=1){
arr(group);
}
_handlerUrl=arr.takeData();
}
/// registers this handler in the global registry of the handlers, there should be just one handler per
/// group
void register(){
synchronized(StcpProtocolHandler.classinfo){
auto pHP= group in stcpProtocolHandlers;
if (pHP !is null && (*pHP) !is this){
log("replacing already registred protocol for group "~group~"\n");
this.newRequestId.ensure((*pHP).newRequestId.next+10_000); // try to avoid any overlap...
}
stcpProtocolHandlers[group]=this;
}
}
/// registers a local group using the listening port
void registerLocalPort(){
synchronized(StcpProtocolHandler.classinfo){
char[128] buf;
auto arr=lGrowableArray(buf,0,GASharing.Local);
dumper(&arr.appendArr)(".lp")(port);
char[] lGroup=arr.takeData();
auto pHP= lGroup in stcpProtocolHandlers;
if (pHP !is null && (*pHP) !is this){
log("replacing already registred protocol for group "~lGroup~"\n");
}
stcpProtocolHandlers[lGroup]=this;
}
}
/// checks if the given url is local
override bool localUrl(ParsedUrl pUrl){
if (pUrl.host.length==0 || find(selfHostnames,pUrl.host)<selfHostnames.length){
auto p=pUrl.port;
if (p.length==0) return true;
auto sep=find(p,'.');
string group;
if (sep<p.length)
group=p[sep..$];
else
group=".";
auto prt=p[0..sep];
synchronized(StcpProtocolHandler.classinfo){
auto ph=group in stcpProtocolHandlers;
if (ph!is null){
return (*ph).port==prt && (*ph).server !is null && (*ph).server.isStarted();
}
}
}
return false;
}
/+ /// local rpc call, oneway methods are *not* executed in background (change?)
override void doRpcCallLocal(ParsedUrl url,void delegate(Serializer) serArgs, void delegate(Unserializer) unserRes,Box addrArg){
sinkTogether(sout,delegate void(CharSink s){
dumper(s)("doRpcCallLocal with url ")(url)("\n");
});
ubyte[1024] buf1;
ubyte[512] buf2;
auto serArr=lGrowableArray(buf1,0);
auto resArr=lGrowableArray(buf2,0);
scope(exit){
resArr.deallocData;
serArr.deallocData;
}
scope ser=new SBinSerializer(&serArr.appendVoid);
serArgs(ser);
auto data=serArr.data;
auto d2=data;
void readExact(void[]d){
if (d2.length<d.length) throw new Exception("EOF while reading",__FILE__,__LINE__);
d[]=d2[0..d.length];
d2=d2[d.length..$];
}
scope unser=new SBinUnserializer(&readExact);
scope serRes=new SBinSerializer(&resArr.appendVoid); // should reuse ser
assert(0);
// the result writer should notify the reader, as they are in different tasks
void getReply(ubyte[] reqId,void delegate(Serializer) sRes){
sRes(serRes);
}
handleRequest(url,unser,&getReply);
assert(d2.length==0,"args not fully read");
d2=resArr.data;
sout("resultData=")(d2)("\n");
if (unserRes!is null){
unser.resetObjIdCounter();
int resKind;
unser(resKind);
switch (resKind){
case 0:
break;
case 1:
unserRes(unser);
break;
case 2:{
char[] errMsg;
unser(errMsg);
throw new RpcException(errMsg~" local calling "~url.url(),__FILE__,__LINE__);
}
case 3:{
char[] errMsg;
unser(errMsg);
throw new RpcException(errMsg~" local calling "~url.url(),__FILE__,__LINE__);
}
default:
throw new RpcException("unknown resKind "~to!(string )(resKind)~
" calling "~url.url(),__FILE__,__LINE__);
}
}
assert(d2.length==0,"res not fully read");
}+/
/// perform rpc call using sockets
override void doRpcCall(ParsedUrl url,void delegate(Serializer) serArgs, void delegate(Unserializer) unserRes,Box addrArg){
version(TrackRpc){
sinkTogether(sout,delegate void(CharSink s){
dumper(s)("doRpcCall(")(&url.urlWriter)(",")(serArgs)(",")(unserRes)(",__)\n"); // don't trust variant serialization...
});
}
TargetHost tHost;
tHost.host=url.host;
tHost.port=url.port[0..find(url.port,'.')];
TaskI tAtt=taskAtt.val;
auto dLevel=tAtt.delayLevel;
Exception e;
version(TrackRpc){
sinkTogether(log,delegate void(CharSink s){
dumper(s)(taskAtt.val)(" doRpcCall on remote url ")(&url.urlWriter)("\n");
});
}
StcpConnection connection;
bool startHandler=false;
synchronized(connections){
auto conn=tHost in connections;
if (conn!is null) connection= *conn;
if (connection is null || (! connection.tryAddLocalUser())){
version(TrackRpc){
if (connection !is null)
sinkTogether(log,delegate void(CharSink s){
dumper(s)(taskAtt.val)(" created double connection to ")(tHost)("\n");
});
}
connection=new StcpConnection(this,tHost);
connections[tHost.dup]=connection;
assert((tHost in connections)!is null,"host not in connections");
startHandler=true;
}
}
if (startHandler){
Task("handleReplies",&connection.handleRequests).autorelease.submit(defaultTask);
}
// connection is valid and has a LocalUser
StcpRequest.performRequest(connection,url,serArgs,unserRes);
}
void handleConnection(ref SocketServer.Handler h){
TargetHost th=h.otherHost();
auto newC=new StcpConnection(this,th,h.sock);
version(TrackRpc){
sinkTogether(log,delegate void(CharSink s){
dumper(s)(taskAtt.val)(" got connection from ")(th)("\n");
});
}
synchronized(connections){
auto dConn=th in connections;
if (dConn !is null){
sinkTogether(log,delegate void(CharSink s){
dumper(s)(taskAtt.val)(" has double connection from ")(th)("\n");
});
doubleConnections~=*dConn;
}
connections[th]=newC;
}
newC.handleRequests();
}
override void startServer(bool strict){
if (server is null){
char[] buf;
string origPort=port;
bool isBound=false;
server=new SocketServer(port,&this.handleConnection,log);
Exception bindE;
for (int i=0;i<100;++i){
try{
server.start();
isBound=true;
} catch(BIONoBindException e){
if (strict){
server=null;
throw e;
}
bindE=e;
}
if (isBound) break;
auto newP=rand.uniformR2(fallBackPortMin,fallBackPortMax);
if (buf.length==0) buf=new char[](30);
auto arr=lGrowableArray(buf,0,GASharing.Global);
writeOut(&arr.appendArr,newP);
port=cast(string)arr.takeData();
server.serviceName=port;
}
if (!isBound) {
server=null;
throw new BIONoBindException("could not bind server started with port "~origPort,__FILE__,__LINE__,bindE);
}
updateUrl();
registerLocalPort();
}
}
/// handles a non pending request, be very careful about sending back errors for this to avoid
/// infinite messaging
/// trying to skip the content of the request migth be a good idea
override void handleNonPendingRequest(ParsedUrl url,Unserializer u, SendResHandler sendRes){
Log.lookup ("blip.rpc").warn("ignoring non pending request {}",url.url());
}
override void handleRequest(ParsedUrl url,Unserializer u, SendResHandler sendRes){
version(TrackRpc){
sinkTogether(log,delegate void(CharSink s){
dumper(s)(taskAtt.val)(" handleRequest ")(&url.urlWriter)("\n");
});
}
if (url.path.length>0){
switch(url.path[0]){
case "obj":
publisher.handleRequest(url,u,sendRes);
break;
case "serv":
servPublisher.handleRequest(url,u,sendRes);
break;
case "req":
PendingRequest req;
bool error=false;
auto reqId=urlDecode(url.anchor);
synchronized(this){
auto reqPtr=reqId in pendingRequests;
if (reqPtr is null) {
error=true;
} else {
req=*reqPtr;
pendingRequests.remove(reqId);
}
}
if (!error){
req.handleRequest(url,u);
} else {
handleNonPendingRequest(url,u,sendRes);
}
break;
case "stop":
assert(0,"to do"); // should close down the connection, check for requests that were sent after the closing request id and restart them at the moment closig a connection means that it will never be reestablished.
default:
sinkTogether(log,delegate void(CharSink s){
dumper(s)("Warning unknown namespace ")(url.path[0])(" in ")(url)("\n");
});
sysError(url,"unknown namespace",sendRes,__FILE__,__LINE__);
}
} else {
sinkTogether(log,delegate void(CharSink s){
dumper(s)("Warning no valid path in url ")(url)("\n");
});
}
}
void lostConnection(StcpConnection c,Exception e){
sinkTogether(log,delegate void(CharSink s){
dumper(s)(port)(group)(" lostConnection to")(c.targetHost);
if (e!is null){
dumper(s)(" with exception:")(e);
}
s("\n");
});
}
string[] listObjects(){
string[] res;
synchronized(publisher){
res = new string[](publisher.objects.length);
size_t ii=0;
foreach(k,v;publisher.objects){
res[ii]=k;
++ii;
}
}
return res;
}
mixin(rpcMixin("","",`handlerUrl|listObjects`));
}
static this(){
char[512] buf;
if (gethostname(buf.ptr,buf.length)!=0){
serr("Warning could not establish the hostname\n");
} else {
buf[$-1]=0;
StcpProtocolHandler.selfHostnames=[buf[0..strlen(buf.ptr)].dup];
sout("selfHostnames:")(StcpProtocolHandler.selfHostnames)("\n");
}
// registers the default stcp protocol
ProtocolHandler.registerProtocolHandler("stcp",&StcpProtocolHandler.findHandlerForUrl);
if (ProtocolHandler.defaultProtocol is null){
auto rpc1=new StcpProtocolHandler("","50000");
rpc1.register();
// rpc1.startServer(false); // does not start, so that it will require an explicit start. This ensures that no program will open a listening socket without being aware
ProtocolHandler.defaultProtocol=rpc1;
}
}
|
D
|
module des.mc.calibrate.filter;
import des.mc.calibrate.util;
class FilterBuffer(T)
if( is( typeof( (T[]).init.expected ) == T ) && is( typeof( T[].init.variance(T.init) ) == T ) )
{
private:
size_t max_length;
size_t current_index = 0;
T[] data;
public:
this( size_t maxLen )
{
assert( maxLen > 0 );
max_length = maxLen;
}
@property
{
bool isFilled() const { return data.length >= max_length; }
float fillRatio() const { return data.length / cast(float)max_length; }
T[2] distributionParams() const
{
auto exp = data.expected;
auto var = data.variance(exp);
return [ exp, var ];
}
size_t maxLength() const { return max_length; }
size_t maxLength( size_t maxLen )
{
max_length = maxLen;
return max_length;
}
}
void reset()
{
data.length = 0;
current_index = 0;
}
void append( in T nval )
{
if( isFilled ) data[current_index%$] = nval;
else data ~= nval;
current_index = (current_index+1) % max_length;
}
}
|
D
|
module stm32.stm32;
import core.bitop: volatileLoad, volatileStore;
import std.meta;
import std.traits;
extern(C):
@nogc:
nothrow:
pragma(LDC_no_moduleinfo);
alias word = uint;
struct _SysTick {
word CTRL,
LOAD,
VAL;
}
struct _RCC {
word CR,
CFGR,
CIR,
APB2STR,
APB1STR,
AHBENR,
APB2ENR,
APB1ENR,
BDCR,
CSR,
AHBSTR,
CFGR2,
CFGR3;
}
struct _GPIO {
word MODER,
OTYPER,
OSPEEDR,
PUPDR,
IDR,
ODR,
BSRR,
LCKR,
AFRL,
AFRH,
BRR;
}
struct _NVIC {
word[8] ISER;
private const(word[24]) RSV1;
word[8] ISCR;
private const(word[24]) RSV2;
word[8] ISPR;
private const(word[24]) RSV3;
word[8] ICPR;
private const(word[24]) RSV4;
word[8] IABR;
private const(word[56]) RSV5;
ubyte[240] IP;
private const(word[644]) RSV6;
word STIR;
}
struct _TIM2_3_4 {
word CR1,
CR2,
SMCR,
DIER,
SR,
EGR,
CCMR1,
CCMR2,
CCER,
CNT,
PSC,
ARR;
private const(word) RSV1;
word CCR1,
CCR2,
CCR3,
CCR4;
private const(word) RSV2;
word DCR,
DMAR;
}
alias RCC_BASE = Alias!0x4002_1000;
alias RCC = Alias!(cast(_RCC*)RCC_BASE);
alias GPIOF_BASE = Alias!0x4800_1400;
alias GPIOF = Alias!(cast(_GPIO*)GPIOF_BASE);
alias SysTick_BASE = Alias!0xE000_E010;
alias SysTick = Alias!(cast(_SysTick*)SysTick_BASE);
alias NVIC_BASE = Alias!0xE000_E100;
alias NVIC = Alias!(cast(_NVIC*)NVIC_BASE);
alias TIM2_BASE = Alias!0x4000_0000;
alias TIM2 = Alias!(cast(_TIM2_3_4*)TIM2_BASE);
void st(T)(ref T reg, T val)
if( isNumeric!(T) ) {
volatileStore(®, val);
}
word ld(T)(ref T reg)
if( isNumeric!(T) ){
return volatileLoad(®);
}
ref bset(T, U)(ref T reg, U[] valarr ...)
if( isNumeric!(T) && isNumeric!(U) ){
word val;
foreach (arg; valarr) {
val |= (1 << arg);
}
volatileStore(®, volatileLoad(®) | val);
return reg;
}
ref bclr(T, U)(ref T reg, U[] valarr ...)
if( isNumeric!(T) && isNumeric!(U) ){
word val;
foreach (arg; valarr) {
val |= (1 << arg);
}
volatileStore(®, volatileLoad(®) & ~val);
return reg;
}
bool bitIsSet(T, U)(ref T reg, U pos)
if( isNumeric!(T) && isNumeric!(U) ){
return ((volatileLoad(®) & (1 << pos)) != 0);
}
void enableIRQ(int IRQn) {
NVIC.ISER[IRQn >> 5].st(1 << (IRQn & 0x1F));
}
void disableIRQ(int IRQn) {
NVIC.ISCR[IRQn >> 5].st(1 << (IRQn & 0x1F));
}
void setPriority(int IRQn, int priority) {
if( IRQn > 0 ) { // TODO: implement for IRQn < 0 */
NVIC.IP[IRQn].st((priority << 4) & 0xFF);
}
}
enum
{
/****** Cortex-M4 Processor Exceptions Numbers ****************************************************************/
NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */
HardFault_IRQn = -13, /*!< 3 Cortex-M4 Hard Fault Interrupt */
MemoryManagement_IRQn = -12, /*!< 4 Cortex-M4 Memory Management Interrupt */
BusFault_IRQn = -11, /*!< 5 Cortex-M4 Bus Fault Interrupt */
UsageFault_IRQn = -10, /*!< 6 Cortex-M4 Usage Fault Interrupt */
SVCall_IRQn = -5, /*!< 11 Cortex-M4 SV Call Interrupt */
DebugMonitor_IRQn = -4, /*!< 12 Cortex-M4 Debug Monitor Interrupt */
PendSV_IRQn = -2, /*!< 14 Cortex-M4 Pend SV Interrupt */
SysTick_IRQn = -1, /*!< 15 Cortex-M4 System Tick Interrupt */
/****** STM32 specific Interrupt Numbers **********************************************************************/
WWDG_IRQn = 0, /*!< Window WatchDog Interrupt */
PVD_IRQn = 1, /*!< PVD through EXTI Line detection Interrupt */
TAMP_STAMP_IRQn = 2, /*!< Tamper and TimeStamp interrupts through the EXTI line 19 */
RTC_WKUP_IRQn = 3, /*!< RTC Wakeup interrupt through the EXTI line 20 */
FLASH_IRQn = 4, /*!< FLASH global Interrupt */
RCC_IRQn = 5, /*!< RCC global Interrupt */
EXTI0_IRQn = 6, /*!< EXTI Line0 Interrupt */
EXTI1_IRQn = 7, /*!< EXTI Line1 Interrupt */
EXTI2_TSC_IRQn = 8, /*!< EXTI Line2 Interrupt and Touch Sense Controller Interrupt */
EXTI3_IRQn = 9, /*!< EXTI Line3 Interrupt */
EXTI4_IRQn = 10, /*!< EXTI Line4 Interrupt */
DMA1_Channel1_IRQn = 11, /*!< DMA1 Channel 1 Interrupt */
DMA1_Channel2_IRQn = 12, /*!< DMA1 Channel 2 Interrupt */
DMA1_Channel3_IRQn = 13, /*!< DMA1 Channel 3 Interrupt */
DMA1_Channel4_IRQn = 14, /*!< DMA1 Channel 4 Interrupt */
DMA1_Channel5_IRQn = 15, /*!< DMA1 Channel 5 Interrupt */
DMA1_Channel6_IRQn = 16, /*!< DMA1 Channel 6 Interrupt */
DMA1_Channel7_IRQn = 17, /*!< DMA1 Channel 7 Interrupt */
ADC1_2_IRQn = 18, /*!< ADC1 & ADC2 Interrupts */
USB_HP_CAN_TX_IRQn = 19, /*!< USB Device High Priority or CAN TX Interrupts */
USB_LP_CAN_RX0_IRQn = 20, /*!< USB Device Low Priority or CAN RX0 Interrupts */
CAN_RX1_IRQn = 21, /*!< CAN RX1 Interrupt */
CAN_SCE_IRQn = 22, /*!< CAN SCE Interrupt */
EXTI9_5_IRQn = 23, /*!< External Line[9:5] Interrupts */
TIM1_BRK_TIM15_IRQn = 24, /*!< TIM1 Break and TIM15 Interrupts */
TIM1_UP_TIM16_IRQn = 25, /*!< TIM1 Update and TIM16 Interrupts */
TIM1_TRG_COM_TIM17_IRQn = 26, /*!< TIM1 Trigger and Commutation and TIM17 Interrupt */
TIM1_CC_IRQn = 27, /*!< TIM1 Capture Compare Interrupt */
TIM2_IRQn = 28, /*!< TIM2 global Interrupt */
TIM3_IRQn = 29, /*!< TIM3 global Interrupt */
TIM4_IRQn = 30, /*!< TIM4 global Interrupt */
I2C1_EV_IRQn = 31, /*!< I2C1 Event Interrupt & EXTI Line23 Interrupt (I2C1 wakeup) */
I2C1_ER_IRQn = 32, /*!< I2C1 Error Interrupt */
I2C2_EV_IRQn = 33, /*!< I2C2 Event Interrupt & EXTI Line24 Interrupt (I2C2 wakeup) */
I2C2_ER_IRQn = 34, /*!< I2C2 Error Interrupt */
SPI1_IRQn = 35, /*!< SPI1 global Interrupt */
SPI2_IRQn = 36, /*!< SPI2 global Interrupt */
USART1_IRQn = 37, /*!< USART1 global Interrupt & EXTI Line25 Interrupt (USART1 wakeup) */
USART2_IRQn = 38, /*!< USART2 global Interrupt & EXTI Line26 Interrupt (USART2 wakeup) */
USART3_IRQn = 39, /*!< USART3 global Interrupt & EXTI Line28 Interrupt (USART3 wakeup) */
EXTI15_10_IRQn = 40, /*!< External Line[15:10] Interrupts */
RTC_Alarm_IRQn = 41, /*!< RTC Alarm (A and B) through EXTI Line 17 Interrupt */
USBWakeUp_IRQn = 42, /*!< USB Wakeup Interrupt */
TIM8_BRK_IRQn = 43, /*!< TIM8 Break Interrupt */
TIM8_UP_IRQn = 44, /*!< TIM8 Update Interrupt */
TIM8_TRG_COM_IRQn = 45, /*!< TIM8 Trigger and Commutation Interrupt */
TIM8_CC_IRQn = 46, /*!< TIM8 Capture Compare Interrupt */
ADC3_IRQn = 47, /*!< ADC3 global Interrupt */
SPI3_IRQn = 51, /*!< SPI3 global Interrupt */
UART4_IRQn = 52, /*!< UART4 global Interrupt & EXTI Line34 Interrupt (UART4 wakeup) */
UART5_IRQn = 53, /*!< UART5 global Interrupt & EXTI Line35 Interrupt (UART5 wakeup) */
TIM6_DAC_IRQn = 54, /*!< TIM6 global and DAC underrun error Interrupt */
TIM7_IRQn = 55, /*!< TIM7 global Interrupt */
DMA2_Channel1_IRQn = 56, /*!< DMA2 Channel 1 global Interrupt */
DMA2_Channel2_IRQn = 57, /*!< DMA2 Channel 2 global Interrupt */
DMA2_Channel3_IRQn = 58, /*!< DMA2 Channel 3 global Interrupt */
DMA2_Channel4_IRQn = 59, /*!< DMA2 Channel 4 global Interrupt */
DMA2_Channel5_IRQn = 60, /*!< DMA2 Channel 5 global Interrupt */
ADC4_IRQn = 61, /*!< ADC4 global Interrupt */
COMP1_2_3_IRQn = 64, /*!< COMP1, COMP2 and COMP3 global Interrupt via EXTI Line21, 22 and 29*/
COMP4_5_6_IRQn = 65, /*!< COMP4, COMP5 and COMP6 global Interrupt via EXTI Line30, 31 and 32*/
COMP7_IRQn = 66, /*!< COMP7 global Interrupt via EXTI Line33 */
USB_HP_IRQn = 74, /*!< USB High Priority global Interrupt */
USB_LP_IRQn = 75, /*!< USB Low Priority global Interrupt */
USBWakeUp_RMP_IRQn = 76, /*!< USB Wakeup Interrupt remap */
FPU_IRQn = 81, /*!< Floating point Interrupt */
};
|
D
|
/*
* This file is part of gtkD.
*
* gtkD is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* gtkD is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with gtkD; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// generated automatically - do not change
// find conversion definition on APILookup.txt
// implement new conversion functionalities on the wrap.utils pakage
/*
* Conversion parameters:
* inFile = GstObject.html
* outPack = gstreamer
* outFile = ObjectGst
* strct = GstObject
* realStrct=
* ctorStrct=
* clss = ObjectGst
* interf =
* class Code: Yes
* interface Code: No
* template for:
* extend =
* implements:
* prefixes:
* - gst_object_
* - gst_
* omit structs:
* omit prefixes:
* omit code:
* - gst_object_save_thyself
* - gst_object_restore_thyself
* - gst_class_signal_emit_by_name
* - gst_class_signal_connect
* - gst_object_ref
* omit signals:
* imports:
* - gtkD.glib.Str
* - gtkD.gobject.ObjectG
* - gtkD.glib.ErrorG
* - gtkD.glib.ListG
* structWrap:
* - GError* -> ErrorG
* - GList* -> ListG
* - GObject* -> ObjectG
* - GstObject* -> ObjectGst
* module aliases:
* local aliases:
* overrides:
*/
module gtkD.gstreamer.ObjectGst;
public import gtkD.gstreamerc.gstreamertypes;
private import gtkD.gstreamerc.gstreamer;
private import gtkD.glib.ConstructionException;
private import gtkD.gobject.Signals;
public import gtkD.gtkc.gdktypes;
private import gtkD.glib.Str;
private import gtkD.gobject.ObjectG;
private import gtkD.glib.ErrorG;
private import gtkD.glib.ListG;
private import gtkD.gobject.ObjectG;
/**
* Description
* GstObject provides a root for the object hierarchy tree filed in by the
* GStreamer library. It is currently a thin wrapper on top of
* GObject. It is an abstract class that is not very usable on its own.
* GstObject gives us basic refcounting, parenting functionality and locking.
* Most of the function are just extended for special GStreamer needs and can be
* found under the same name in the base class of GstObject which is GObject
* (e.g. g_object_ref() becomes gst_object_ref()).
* The most interesting difference between GstObject and GObject is the
* "floating" reference count. A GObject is created with a reference count of
* 1, owned by the creator of the GObject. (The owner of a reference is the
* code section that has the right to call gst_object_unref() in order to
* remove that reference.) A GstObject is created with a reference count of 1
* also, but it isn't owned by anyone; Instead, the initial reference count
* of a GstObject is "floating". The floating reference can be removed by
* anyone at any time, by calling gst_object_sink(). gst_object_sink() does
* nothing if an object is already sunk (has no floating reference).
* When you add a GstElement to its parent container, the parent container will
* do this:
* gst_object_ref (GST_OBJECT (child_element));
* gst_object_sink (GST_OBJECT (child_element));
* This means that the container now owns a reference to the child element
* (since it called gst_object_ref()), and the child element has no floating
* reference.
* The purpose of the floating reference is to keep the child element alive
* until you add it to a parent container, which then manages the lifetime of
* the object itself:
* element = gst_element_factory_make (factoryname, name);
* // element has one floating reference to keep it alive
* gst_bin_add (GST_BIN (bin), element);
* // element has one non-floating reference owned by the container
* Another effect of this is, that calling gst_object_unref() on a bin object,
* will also destoy all the GstElement objects in it. The same is true for
* calling gst_bin_remove().
* Special care has to be taken for all methods that gst_object_sink() an object
* since if the caller of those functions had a floating reference to the object,
* the object reference is now invalid.
* In contrast to GObject instances, GstObject adds a name property. The functions
* gst_object_set_name() and gst_object_get_name() are used to set/get the name
* of the object.
* Last reviewed on 2005-11-09 (0.9.4)
*/
public class ObjectGst : ObjectG
{
/** the main Gtk struct */
protected GstObject* gstObject;
public GstObject* getObjectGstStruct()
{
return gstObject;
}
/** the main Gtk struct as a void* */
protected override void* getStruct()
{
return cast(void*)gstObject;
}
/**
* Sets our main struct and passes it to the parent class
*/
public this (GstObject* gstObject)
{
if(gstObject is null)
{
this = null;
return;
}
//Check if there already is a D object for this gtk struct
void* ptr = getDObject(cast(GObject*)gstObject);
if( ptr !is null )
{
this = cast(ObjectGst)ptr;
return;
}
super(cast(GObject*)gstObject);
this.gstObject = gstObject;
}
/**
* Increments the refence count on object. This function
* does not take the lock on object because it relies on
* atomic refcounting.
* This object returns the input parameter to ease writing
* constructs like :
* result = gst_object_ref (object->parent);
* Returns:
* A pointer to object
*/
public void* reference()
{
// gpointer gst_object_ref (gpointer object);
return gst_object_ref( gstObject );
}
/*public static void* ref(void* object)
{
// gpointer gst_object_ref (gpointer object);
return gst_object_ref(object);
}*/
/**
*/
int[char[]] connectedSignals;
void delegate(ObjectG, GParamSpec*, ObjectGst)[] onDeepNotifyListeners;
/**
* The deep notify signal is used to be notified of property changes. It is
* typically attached to the toplevel bin to receive notifications from all
* the elements contained in that bin.
*/
void addOnDeepNotify(void delegate(ObjectG, GParamSpec*, ObjectGst) dlg, ConnectFlags connectFlags=cast(ConnectFlags)0)
{
if ( !("deep-notify" in connectedSignals) )
{
Signals.connectData(
getStruct(),
"deep-notify",
cast(GCallback)&callBackDeepNotify,
cast(void*)this,
null,
connectFlags);
connectedSignals["deep-notify"] = 1;
}
onDeepNotifyListeners ~= dlg;
}
extern(C) static void callBackDeepNotify(GstObject* gstobjectStruct, GObject* propObject, GParamSpec* prop, ObjectGst objectGst)
{
foreach ( void delegate(ObjectG, GParamSpec*, ObjectGst) dlg ; objectGst.onDeepNotifyListeners )
{
dlg(new ObjectG(propObject), prop, objectGst);
}
}
void delegate(gpointer, ObjectGst)[] onObjectSavedListeners;
/**
* Trigered whenever a new object is saved to XML. You can connect to this
* signal to insert custom XML tags into the core XML.
*/
void addOnObjectSaved(void delegate(gpointer, ObjectGst) dlg, ConnectFlags connectFlags=cast(ConnectFlags)0)
{
if ( !("object-saved" in connectedSignals) )
{
Signals.connectData(
getStruct(),
"object-saved",
cast(GCallback)&callBackObjectSaved,
cast(void*)this,
null,
connectFlags);
connectedSignals["object-saved"] = 1;
}
onObjectSavedListeners ~= dlg;
}
extern(C) static void callBackObjectSaved(GstObject* gstobjectStruct, gpointer xmlNode, ObjectGst objectGst)
{
foreach ( void delegate(gpointer, ObjectGst) dlg ; objectGst.onObjectSavedListeners )
{
dlg(xmlNode, objectGst);
}
}
void delegate(ObjectG, ObjectGst)[] onParentSetListeners;
/**
* Emitted when the parent of an object is set.
*/
void addOnParentSet(void delegate(ObjectG, ObjectGst) dlg, ConnectFlags connectFlags=cast(ConnectFlags)0)
{
if ( !("parent-set" in connectedSignals) )
{
Signals.connectData(
getStruct(),
"parent-set",
cast(GCallback)&callBackParentSet,
cast(void*)this,
null,
connectFlags);
connectedSignals["parent-set"] = 1;
}
onParentSetListeners ~= dlg;
}
extern(C) static void callBackParentSet(GstObject* gstobjectStruct, GObject* parent, ObjectGst objectGst)
{
foreach ( void delegate(ObjectG, ObjectGst) dlg ; objectGst.onParentSetListeners )
{
dlg(new ObjectG(parent), objectGst);
}
}
void delegate(ObjectG, ObjectGst)[] onParentUnsetListeners;
/**
* Emitted when the parent of an object is unset.
*/
void addOnParentUnset(void delegate(ObjectG, ObjectGst) dlg, ConnectFlags connectFlags=cast(ConnectFlags)0)
{
if ( !("parent-unset" in connectedSignals) )
{
Signals.connectData(
getStruct(),
"parent-unset",
cast(GCallback)&callBackParentUnset,
cast(void*)this,
null,
connectFlags);
connectedSignals["parent-unset"] = 1;
}
onParentUnsetListeners ~= dlg;
}
extern(C) static void callBackParentUnset(GstObject* gstobjectStruct, GObject* parent, ObjectGst objectGst)
{
foreach ( void delegate(ObjectG, ObjectGst) dlg ; objectGst.onParentUnsetListeners )
{
dlg(new ObjectG(parent), objectGst);
}
}
/**
* Sets the name of object, or gives object a guaranteed unique
* name (if name is NULL).
* This function makes a copy of the provided name, so the caller
* retains ownership of the name it sent.
* Params:
* name = new name of object
* Returns: TRUE if the name could be set. Since Objects that havea parent cannot be renamed, this function returns FALSE in thosecases.MT safe. This function grabs and releases object's LOCK.
*/
public int setName(string name)
{
// gboolean gst_object_set_name (GstObject *object, const gchar *name);
return gst_object_set_name(gstObject, Str.toStringz(name));
}
/**
* Returns a copy of the name of object.
* Caller should g_free() the return value after usage.
* For a nameless object, this returns NULL, which you can safely g_free()
* as well.
* Returns: the name of object. g_free() after usage.MT safe. This function grabs and releases object's LOCK.
*/
public string getName()
{
// gchar* gst_object_get_name (GstObject *object);
return Str.toString(gst_object_get_name(gstObject));
}
/**
* Sets the parent of object to parent. The object's reference count will
* be incremented, and any floating reference will be removed (see gst_object_sink()).
* This function causes the parent-set signal to be emitted when the parent
* was successfully set.
* Params:
* parent = new parent of object
* Returns: TRUE if parent could be set or FALSE when objectalready had a parent or object and parent are the same.MT safe. Grabs and releases object's LOCK.
*/
public int setParent(ObjectGst parent)
{
// gboolean gst_object_set_parent (GstObject *object, GstObject *parent);
return gst_object_set_parent(gstObject, (parent is null) ? null : parent.getObjectGstStruct());
}
/**
* Returns the parent of object. This function increases the refcount
* of the parent object so you should gst_object_unref() it after usage.
* Returns: parent of object, this can be NULL if object has no parent. unref after usage.MT safe. Grabs and releases object's LOCK.
*/
public ObjectGst getParent()
{
// GstObject* gst_object_get_parent (GstObject *object);
auto p = gst_object_get_parent(gstObject);
if(p is null)
{
return null;
}
return new ObjectGst(cast(GstObject*) p);
}
/**
* Clear the parent of object, removing the associated reference.
* This function decreases the refcount of object.
* MT safe. Grabs and releases object's lock.
*/
public void unparent()
{
// void gst_object_unparent (GstObject *object);
gst_object_unparent(gstObject);
}
/**
* Returns a copy of the name prefix of object.
* Caller should g_free() the return value after usage.
* For a prefixless object, this returns NULL, which you can safely g_free()
* as well.
* Returns: the name prefix of object. g_free() after usage.MT safe. This function grabs and releases object's LOCK.
*/
public string getNamePrefix()
{
// gchar* gst_object_get_name_prefix (GstObject *object);
return Str.toString(gst_object_get_name_prefix(gstObject));
}
/**
* Sets the name prefix of object to name_prefix.
* This function makes a copy of the provided name prefix, so the caller
* retains ownership of the name prefix it sent.
* MT safe. This function grabs and releases object's LOCK.
* Params:
* namePrefix = new name prefix of object
*/
public void setNamePrefix(string namePrefix)
{
// void gst_object_set_name_prefix (GstObject *object, const gchar *name_prefix);
gst_object_set_name_prefix(gstObject, Str.toStringz(namePrefix));
}
/**
* A default deep_notify signal callback for an object. The user data
* should contain a pointer to an array of strings that should be excluded
* from the notify. The default handler will print the new value of the property
* using g_print.
* MT safe. This function grabs and releases object's LOCK for getting its
* path string.
* Params:
* object = the GObject that signalled the notify.
* orig = a GstObject that initiated the notify.
* pspec = a GParamSpec of the property.
* excludedProps = a set of user-specified properties to exclude or
* NULL to show all changes.
*/
public static void defaultDeepNotify(ObjectG object, ObjectGst orig, GParamSpec* pspec, char** excludedProps)
{
// void gst_object_default_deep_notify (GObject *object, GstObject *orig, GParamSpec *pspec, gchar **excluded_props);
gst_object_default_deep_notify((object is null) ? null : object.getObjectGStruct(), (orig is null) ? null : orig.getObjectGstStruct(), pspec, excludedProps);
}
/**
* A default error function.
* The default handler will simply print the error string using g_print.
* Params:
* error = the GError.
* dbug = an additional debug information string, or NULL.
*/
public void defaultError(ErrorG error, string dbug)
{
// void gst_object_default_error (GstObject *source, GError *error, gchar *debug);
gst_object_default_error(gstObject, (error is null) ? null : error.getErrorGStruct(), Str.toStringz(dbug));
}
/**
* Checks to see if there is any object named name in list. This function
* does not do any locking of any kind. You might want to protect the
* provided list with the lock of the owner of the list. This function
* will lock each GstObject in the list to compare the name, so be
* carefull when passing a list with a locked object.
* Params:
* list = a list of GstObject to check through
* name = the name to search for
* Returns: TRUE if a GstObject named name does not appear in list, FALSE if it does.MT safe. Grabs and releases the LOCK of each object in the list.
*/
public static int checkUniqueness(ListG list, string name)
{
// gboolean gst_object_check_uniqueness (GList *list, const gchar *name);
return gst_object_check_uniqueness((list is null) ? null : list.getListGStruct(), Str.toStringz(name));
}
/**
* Check if object has an ancestor ancestor somewhere up in
* the hierarchy.
* Params:
* ancestor = a GstObject to check as ancestor
* Returns: TRUE if ancestor is an ancestor of object.MT safe. Grabs and releases object's locks.
*/
public int hasAncestor(ObjectGst ancestor)
{
// gboolean gst_object_has_ancestor (GstObject *object, GstObject *ancestor);
return gst_object_has_ancestor(gstObject, (ancestor is null) ? null : ancestor.getObjectGstStruct());
}
/**
* Decrements the refence count on object. If reference count hits
* zero, destroy object. This function does not take the lock
* on object as it relies on atomic refcounting.
* The unref method should never be called with the LOCK held since
* this might deadlock the dispose function.
* Params:
* object = a GstObject to unreference
*/
public static void unref(void* object)
{
// void gst_object_unref (gpointer object);
gst_object_unref(object);
}
/**
* If object was floating, the GST_OBJECT_FLOATING flag is removed
* and object is unreffed. When object was not floating,
* this function does nothing.
* Any newly created object has a refcount of 1 and is floating.
* This function should be used when creating a new object to
* symbolically 'take ownership' of object. This done by first doing a
* gst_object_ref() to keep a reference to object and then gst_object_sink()
* to remove and unref any floating references to object.
* Use gst_object_set_parent() to have this done for you.
* MT safe. This function grabs and releases object lock.
* Params:
* object = a GstObject to sink
*/
public static void sink(void* object)
{
// void gst_object_sink (gpointer object);
gst_object_sink(object);
}
/**
* Unrefs the GstObject pointed to by oldobj, refs newobj and
* puts newobj in *oldobj. Be carefull when calling this
* function, it does not take any locks. You might want to lock
* the object owning oldobj pointer before calling this
* function.
* Make sure not to LOCK oldobj because it might be unreffed
* which could cause a deadlock when it is disposed.
* Params:
* oldobj = pointer to a place of a GstObject to replace
* newobj = a new GstObject
*/
public static void replace(GstObject** oldobj, ObjectGst newobj)
{
// void gst_object_replace (GstObject **oldobj, GstObject *newobj);
gst_object_replace(oldobj, (newobj is null) ? null : newobj.getObjectGstStruct());
}
/**
* Generates a string describing the path of object in
* the object hierarchy. Only useful (or used) for debugging.
* Returns: a string describing the path of object. You must g_free() the string after usage.MT safe. Grabs and releases the GstObject's LOCK for all objects in the hierarchy.
*/
public string getPathString()
{
// gchar* gst_object_get_path_string (GstObject *object);
return Str.toString(gst_object_get_path_string(gstObject));
}
}
|
D
|
module dcv.imgproc.imgmanip;
/**
* Image manipulation module.
*
* v0.1 norm:
* resize (done, not tested)
* scale (done, not tested)
* transform!affine,perspective
* remap (pixel-wise displacement)
* split (split multichannel image to single channels)
* merge (merge multiple channels to one image)
* channelChain (chain mono images into multi-channel)
*/
public import dcv.imgproc.interpolate;
private import std.exception : enforce;
private import std.experimental.ndslice;
private import std.traits;
private import std.algorithm : each;
private import std.range : iota;
private import std.parallelism : parallel;
/**
* Resize array using custom interpolation function.
*
* Primarilly implemented as image resize.
* 1D, 2D and 3D arrays are supported, where 3D array is
* treated as channeled image - each channel is interpolated
* as isolated 2D array (matrix).
*
* Interpolation function is given as a template parameter.
* Default interpolation function is linear. Custom interpolation
* function can be implemented in the 3rd party code, by following
* interpolation function rules in dcv.imgproc.interpolation.
*
* params:
* slice = Slice to an input array.
* newsize = tuple that defines new shape. New dimension has to be
* the same as input slice in the 1D and 2D resize, where in the
* 3D resize newsize has to be 2D.
*/
Slice!(N, V*) resize(alias interp = linear, V, size_t N, Size...)
(Slice!(N, V*) slice, Size newsize)
if (allSameType!Size && allSatisfy!(isIntegral, Size))
{
static if (N == 1) {
static assert(newsize.length == 1,
"Invalid new-size setup - dimension does not match with input slice.");
return resizeImpl_1!interp(slice, newsize[0]);
} else static if (N == 2) {
static assert(newsize.length == 2,
"Invalid new-size setup - dimension does not match with input slice.");
return resizeImpl_2!interp(slice, newsize[0], newsize[1]);
} else static if (N == 3) {
static assert(newsize.length == 2,
"Invalid new-size setup - 3D resize is performed as 2D."); // TODO: find better way to say this...
return resizeImpl_3!interp(slice, newsize[0], newsize[1]);
} else {
import std.conv : to;
static assert(0, "Resize is not supported for slice with " ~ N.to!string ~ " dimensions.");
}
}
/**
* Scale array size using custom interpolation function.
*
* Implemented as convenience function which calls resize
* using scaled shape of the input slice as:
*
* ```
* scaled = resize(input, input.shape*scale)
* ```
*/
Slice!(N, V*) scale(alias interp = linear, V, size_t N, Scale...)
(Slice!(N, V*) slice, Scale scale)
if (allSameType!Scale && allSatisfy!(isFloatingPoint, Scale))
{
foreach(v;scale)
assert(v > 0., "Invalid scale values (v > 0.0)");
static if (N == 1) {
static assert(scale.length == 1,
"Invalid scale setup - dimension does not match with input slice.");
auto newsize = slice.length*scale[0];
enforce (newsize > 0, "Scaling value invalid - after scaling array size is zero.");
return resizeImpl_1!interp(slice, newsize);
} else static if (N == 2) {
static assert(scale.length == 2,
"Invalid scale setup - dimension does not match with input slice.");
auto newsize = [slice.length!0*scale[0], slice.length!1*scale[1]];
enforce (newsize[0] > 0 && newsize[1] > 0, "Scaling value invalid - after scaling array size is zero.");
return resizeImpl_2!interp(slice, newsize[0], newsize[1]);
} else static if (N == 3) {
static assert(scale.length == 2,
"Invalid scale setup - 3D scale is performed as 2D."); // TODO: find better way to say this...
auto newsize = [slice.length!0*scale[0], slice.length!1*scale[1]];
enforce (newsize[0] > 0 && newsize[1] > 0, "Scaling value invalid - after scaling array size is zero.");
return resizeImpl_3!interp(slice, newsize[0], newsize[1]);
} else {
import std.conv : to;
static assert(0, "Resize is not supported for slice with " ~ N.to!string ~ " dimensions.");
}
}
unittest {
// TODO: design the test
}
private:
// 1d resize implementation
Slice!(1, V*) resizeImpl_1(alias interp, V)(Slice!(1, V*) slice, ulong newsize) {
static assert(__traits(compiles, interp(slice, newsize)),
"Interpolation function is not supported for given slice.");
enforce(!slice.empty && newsize > 0);
auto retval = new V[newsize];
auto resizeRatio = cast(float)(newsize - 1) / cast(float)(slice.length - 1);
foreach(i; iota(newsize).parallel) {
retval[i] = interp(slice, cast(float)i/resizeRatio);
}
return retval.sliced(newsize);
}
// 1d resize implementation
Slice!(2, V*) resizeImpl_2(alias interp, V)(Slice!(2, V*) slice, ulong width, ulong height) {
static assert(__traits(compiles, interp(slice, width, height)),
"Interpolation function is not supported for given slice.");
enforce(!slice.empty && width > 0 && height > 0);
auto retval = new V[width*height].sliced(height, width);
auto rows = slice.length!0;
auto cols = slice.length!1;
auto r_v = cast(float)(height - 1) / cast(float)(rows - 1); // horizontaresize ratio
auto r_h = cast(float)(width - 1) / cast(float)(cols - 1);
foreach(i; iota(height).parallel) {
auto row = retval[i, 0..width];
foreach(j; iota(width)) {
row[j] = interp(slice, cast(float)i/r_v, cast(float)j/r_h);
}
}
return retval;
}
// 1d resize implementation
Slice!(3, V*) resizeImpl_3(alias interp, V)(Slice!(3, V*) slice, ulong width, ulong height) {
/*
static assert(__traits(compiles, interp(slice, width, height)),
"Interpolation function is not supported for given slice.");
*/
enforce(!slice.empty && width > 0 && height > 0);
auto rows = slice.length!0;
auto cols = slice.length!1;
auto channels = slice.length!2;
auto retval = new V[width*height*channels].sliced(height, width, channels);
auto r_v = cast(float)(height - 1) / cast(float)(rows - 1); // horizontaresize ratio
auto r_h = cast(float)(width - 1) / cast(float)(cols - 1);
foreach(c; iota(channels)) {
auto sl_ch = slice[0..rows, 0..cols, c];
auto ret_ch = retval[0..height, 0..width, c];
foreach(i; iota(height).parallel) {
auto row = ret_ch[i, 0..width];
foreach(j; iota(width)) {
row[j] = interp(sl_ch, cast(float)i/r_v, cast(float)j/r_h);
}
}
}
return retval;
}
|
D
|
/Users/apple-1/Downloads/Demos-master/AdaptiveUITextView/Build/Intermediates/AdaptiveUITextView.build/Debug-iphonesimulator/AdaptiveUITextView.build/Objects-normal/x86_64/AppDelegate.o : /Users/apple-1/Downloads/Demos-master/AdaptiveUITextView/AdaptiveUITextView/ViewController.swift /Users/apple-1/Downloads/Demos-master/AdaptiveUITextView/AdaptiveUITextView/AppDelegate.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule
/Users/apple-1/Downloads/Demos-master/AdaptiveUITextView/Build/Intermediates/AdaptiveUITextView.build/Debug-iphonesimulator/AdaptiveUITextView.build/Objects-normal/x86_64/AppDelegate~partial.swiftmodule : /Users/apple-1/Downloads/Demos-master/AdaptiveUITextView/AdaptiveUITextView/ViewController.swift /Users/apple-1/Downloads/Demos-master/AdaptiveUITextView/AdaptiveUITextView/AppDelegate.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule
/Users/apple-1/Downloads/Demos-master/AdaptiveUITextView/Build/Intermediates/AdaptiveUITextView.build/Debug-iphonesimulator/AdaptiveUITextView.build/Objects-normal/x86_64/AppDelegate~partial.swiftdoc : /Users/apple-1/Downloads/Demos-master/AdaptiveUITextView/AdaptiveUITextView/ViewController.swift /Users/apple-1/Downloads/Demos-master/AdaptiveUITextView/AdaptiveUITextView/AppDelegate.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule
|
D
|
module mach.sdl.input.event.mixins;
/// This module defines mixin templates used by the various event types.
private:
//
public:
template EventMixinAttribute(T){
import derelict.sdl2.types;
static if(is(T == SDL_CommonEvent)) enum EventMixinAttribute = `common`;
else static if(is(T == SDL_WindowEvent)) enum EventMixinAttribute = `window`;
else static if(is(T == SDL_KeyboardEvent)) enum EventMixinAttribute = `key`;
else static if(is(T == SDL_TextEditingEvent)) enum EventMixinAttribute = `edit`;
else static if(is(T == SDL_TextInputEvent)) enum EventMixinAttribute = `text`;
else static if(is(T == SDL_MouseMotionEvent)) enum EventMixinAttribute = `motion`;
else static if(is(T == SDL_MouseButtonEvent)) enum EventMixinAttribute = `button`;
else static if(is(T == SDL_MouseWheelEvent)) enum EventMixinAttribute = `wheel`;
else static if(is(T == SDL_JoyAxisEvent)) enum EventMixinAttribute = `jaxis`;
else static if(is(T == SDL_JoyBallEvent)) enum EventMixinAttribute = `jball`;
else static if(is(T == SDL_JoyHatEvent)) enum EventMixinAttribute = `jhat`;
else static if(is(T == SDL_JoyButtonEvent)) enum EventMixinAttribute = `jbutton`;
else static if(is(T == SDL_JoyDeviceEvent)) enum EventMixinAttribute = `jdevice`;
else static if(is(T == SDL_ControllerAxisEvent)) enum EventMixinAttribute = `caxis`;
else static if(is(T == SDL_ControllerButtonEvent)) enum EventMixinAttribute = `cbutton`;
else static if(is(T == SDL_ControllerDeviceEvent)) enum EventMixinAttribute = `cdevice`;
else static if(is(T == SDL_AudioDeviceEvent)) enum EventMixinAttribute = `adevice`;
else static if(is(T == SDL_QuitEvent)) enum EventMixinAttribute = `quit`;
else static if(is(T == SDL_UserEvent)) enum EventMixinAttribute = `user`;
else static if(is(T == SDL_SysWMEvent)) enum EventMixinAttribute = `syswm`;
else static if(is(T == SDL_TouchFingerEvent)) enum EventMixinAttribute = `tfinger`;
else static if(is(T == SDL_MultiGestureEvent)) enum EventMixinAttribute = `mgesture`;
else static if(is(T == SDL_DollarGestureEvent)) enum EventMixinAttribute = `dgesture`;
else static if(is(T == SDL_DropEvent)) enum EventMixinAttribute = `drop`;
else static assert(false, "Unrecognized SDL_Event type.");
}
template EventMixin(T){
mixin EventMixin!(T, EventMixinAttribute!T);
}
template EventMixin(T, string attribute){
SDL_Event* event;
@property auto eventdata() const{
mixin(`return cast(T) this.event.` ~ attribute ~ `;`);
}
}
/// For events including the focused window.
template WindowEventMixin(){
import mach.sdl.window : Window;
/// Get the ID of the window for which this event was generated.
@property Window.ID windowid() const{
return cast(Window.ID) this.eventdata.windowID;
}
/// Set the ID of the window for which this event was generated.
@property void windowid(Window.ID windowid){
this.eventdata.windowID = windowid;
}
/// Get the window object for which this event was generated.
@property Window window(){
return Window.byid(this.windowid);
}
/// Set the window for which this event was generated.
@property void window(Window window){
this.windowid = window.id;
}
}
/// For events including the state of a button.
template ButtonStateEventMixin(){
import mach.sdl.input.common : ButtonState;
/// Get whether the button was pressed or released.
@property ButtonState state() const{
return cast(ButtonState) this.eventdata.state;
}
/// Set whether the button was pressed or released.
@property void state(ButtonState state){
this.eventdata.state = cast(ubyte) state;
}
/// Get whether the button was pressed.
@property bool pressed(){
return this.state is ButtonState.Pressed;
}
/// Get whether the button was released.
@property bool released(){
return this.state is ButtonState.Released;
}
}
/// For events including both the state of a button and a single identifier
/// representing the button that was pressed or released.
template ButtonEventMixin(ButtonType){
mixin ButtonStateEventMixin;
alias Button = ButtonType;
/// Get the button associated with the event.
@property Button button() const{
return cast(Button) this.eventdata.button;
}
/// Set the button associated with the event.
@property void button(Button button) const{
this.eventdata.button = cast(ubyte) button;
}
}
/// For events including a mouse ID.
template MouseEventMixin(){
import mach.sdl.input.mouse : Mouse;
/// Indicate the window with mouse focus, if any.
mixin WindowEventMixin;
/// Get ID of the device which generated this event.
@property Mouse.ID mouseid() const{
return cast(Mouse.ID) this.eventdata.which;
}
/// Set ID of the device generating this event.
@property void mouseid(Mouse.ID mouseid){
this.eventdata.which = mouseid;
}
/// Determine whether the event was generated by a touch input device rather
/// than by an actual mouse.
@property bool istouch() const{
return this.mouseid == Mouse.TouchID;
}
}
/// For events including x, y position data.
template PositionEventMixin(string xattr = `x`, string yattr = `y`){
/// Get the x position associated with the event.
@property auto x() const{
mixin(`return this.eventdata.` ~ xattr ~ `;`);
}
/// Set the x position associated with the event.
@property void x(typeof(this.x()) x){
mixin(`this.eventdata.` ~ xattr ~ ` = x;`);
}
/// Get the y position associated with the event.
@property auto y() const{
mixin(`return this.eventdata.` ~ yattr ~ `;`);
}
/// Set the y position associated with the event.
@property void y(typeof(this.y()) y){
mixin(`this.eventdata.` ~ yattr ~ ` = y;`);
}
}
/// For events including change in x, y data.
template RelativePositionEventMixin(string xattr = `dx`, string yattr = `dy`){
/// Get the change in x associated with the event.
@property auto dx() const{
mixin(`return this.eventdata.` ~ xattr ~ `;`);
}
/// Set the change in x associated with the event.
@property void dx(typeof(this.dx()) dx){
mixin(`this.eventdata.` ~ xattr ~ ` = dx;`);
}
/// Get the change in y associated with the event.
@property auto dy() const{
mixin(`return this.eventdata.` ~ yattr ~ `;`);
}
/// Set the change in y associated with the event.
@property void dy(typeof(this.dy()) dy){
mixin(`this.eventdata.` ~ yattr ~ ` = dy;`);
}
}
/// For events including text data.
template TextEventMixin(){
import std.string : fromStringz;
/// All text events also include window data.
mixin WindowEventMixin;
/// The size limit of event text.
static enum TextSize = typeof(this.eventdata).text.length;
/// Get the text associated with the event.
@property string text() const{
return cast(string) fromStringz(this.eventdata.text.ptr);
}
/// Set the text associated with the event.
@property void text(string text) in{assert(text.length < TextSize);} body{
for(size_t i = 0; i <= text.length; i++){
this.eventdata.text[i] = cast(char) (text.ptr)[i];
}
}
}
/// For events including joystick data.
template JoyEventMixin(){
import mach.sdl.input.joystick : Joystick;
/// Get ID of the joystick which generated the event.
@property Joystick.ID joystickid() const{
return cast(Joystick.ID) this.eventdata.which;
}
/// Set ID of the joystick which generated the event.
@property void joystickid(Joystick.ID joystickid){
this.eventdata.which = joystickid;
}
/// Get a Joystick object representing the device which generated the event.
@property Joystick joystick(){
return Joystick.byid(this.joystickid);
}
/// Set the Joystick object which generated the event.
@property void joystick(Joystick joystick){
this.joystickid = joystick.id;
}
}
/// For events including controller data.
template ControllerEventMixin(){
import mach.sdl.input.controller : Controller;
/// All events with controller data also include joystick data.
mixin JoyEventMixin;
/// Get a Controller object for the device which generated the event.
@property Controller controller(){
return Controller.byid(this.joystickid);
}
/// Set the Controller which generated the event.
@property void controller(Controller controller){
this.joystickid = controller.id;
}
}
/// For events including joystick or controller axis data.
template JoyAxisEventMixin(AxisType){
import mach.sdl.input.joystick : Joystick;
alias Axis = AxisType;
/// Get the identifier for the axis associated with the event.
@property Axis axis() const{
return cast(Axis) this.eventdata.axis;
}
/// Set the identifier for the axis associated with the event.
@property void axis(Axis axis){
this.eventdata.axis = cast(ubyte) axis;
}
/// Get the position on the axis, represented by a signed short.
@property short positionraw() const{
return this.eventdata.value;
}
/// Set the position on the axis, represented by a signed short.
@property void positionraw(short value){
this.eventdata.value = value;
}
/// Get the position on the axis, normalized to a floating point value
/// from -1.0 to 1.0.
@property real position() const{
return Joystick.normalizeaxis(this.positionraw);
}
/// Set the position on the axis, normalized to a floating point value
/// from -1.0 to 1.0.
@property void position(real value){
this.positionraw = Joystick.denormalizeaxis(value);
}
}
/// For events including touch data.
template TouchEventMixin(){
alias TouchID = SDL_TouchID;
/// Get ID of the touch device which generated the event.
@property TouchID touchid() const{
return this.eventdata.touchId;
}
/// Set ID of the touch device which generated the event.
@property void touchid(TouchID touchid){
this.eventdata.touchId = touchid;
}
}
/// For events including gesture data.
template GestureEventMixin(){
/// All events with gesture data also include touch and position data.
mixin TouchEventMixin;
mixin PositionEventMixin!(`x`, `y`);
/// Get the number of fingers used to express the gesture.
@property auto fingers() const{
return this.eventdata.numFingers;
}
/// Set the number of fingers used to express the gesture.
@property void fingers(typeof(this.fingers()) count){
this.eventdata.numFingers = count;
}
}
|
D
|
/* crypto/evp/evp.h */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
module deimos.openssl.evp;
import deimos.openssl._d_util;
import deimos.openssl.x509; // Needed for X509_ATTRIBUTE.
//#ifdef OPENSSL_ALGORITHM_DEFINES
public import deimos.openssl.opensslconf;
//#else
//# define OPENSSL_ALGORITHM_DEFINES
//public import deimos.openssl.opensslconf;
//# undef OPENSSL_ALGORITHM_DEFINES
//#endif
public import deimos.openssl.ossl_typ;
public import deimos.openssl.symhacks;
version(OPENSSL_NO_BIO) {} else {
public import deimos.openssl.bio;
}
/*
enum EVP_RC2_KEY_SIZE = 16;
enum EVP_RC4_KEY_SIZE = 16;
enum EVP_BLOWFISH_KEY_SIZE = 16;
enum EVP_CAST5_KEY_SIZE = 16;
enum EVP_RC5_32_12_16_KEY_SIZE = 16;
*/
enum EVP_MAX_MD_SIZE = 64; /* longest known is SHA512 */
enum EVP_MAX_KEY_LENGTH = 64;
enum EVP_MAX_IV_LENGTH = 16;
enum EVP_MAX_BLOCK_LENGTH = 32;
enum PKCS5_SALT_LEN = 8;
/* Default PKCS#5 iteration count */
enum PKCS5_DEFAULT_ITER = 2048;
public import deimos.openssl.objects;
enum EVP_PK_RSA = 0x0001;
enum EVP_PK_DSA = 0x0002;
enum EVP_PK_DH = 0x0004;
enum EVP_PK_EC = 0x0008;
enum EVP_PKT_SIGN = 0x0010;
enum EVP_PKT_ENC = 0x0020;
enum EVP_PKT_EXCH = 0x0040;
enum EVP_PKS_RSA = 0x0100;
enum EVP_PKS_DSA = 0x0200;
enum EVP_PKS_EC = 0x0400;
enum EVP_PKT_EXP = 0x1000; /* <= 512 bit key */
alias NID_undef EVP_PKEY_NONE;
alias NID_rsaEncryption EVP_PKEY_RSA;
alias NID_rsa EVP_PKEY_RSA2;
alias NID_dsa EVP_PKEY_DSA;
alias NID_dsa_2 EVP_PKEY_DSA1;
alias NID_dsaWithSHA EVP_PKEY_DSA2;
alias NID_dsaWithSHA1 EVP_PKEY_DSA3;
alias NID_dsaWithSHA1_2 EVP_PKEY_DSA4;
alias NID_dhKeyAgreement EVP_PKEY_DH;
alias NID_X9_62_id_ecPublicKey EVP_PKEY_EC;
alias NID_hmac EVP_PKEY_HMAC;
alias NID_cmac EVP_PKEY_CMAC;
extern (C):
nothrow:
/* Type needs to be a bit field
* Sub-type needs to be for variations on the method, as in_, can it do
* arbitrary encryption.... */
struct evp_pkey_st
{
int type;
int save_type;
int references;
const(EVP_PKEY_ASN1_METHOD)* ameth;
ENGINE* engine;
union pkey_ {
char* ptr;
version(OPENSSL_NO_RSA) {} else {
rsa_st* rsa; /* RSA */
}
version(OPENSSL_NO_DSA) {} else {
dsa_st* dsa; /* DSA */
}
version(OPENSSL_NO_DH) {} else {
dh_st* dh; /* DH */
}
version(OPENSSL_NO_EC) {} else {
ec_key_st* ec; /* ECC */
}
}
pkey_ pkey;
int save_parameters;
STACK_OF!(X509_ATTRIBUTE) *attributes; /* [ 0 ] */
} /* EVP_PKEY */;
enum EVP_PKEY_MO_SIGN = 0x0001;
enum EVP_PKEY_MO_VERIFY = 0x0002;
enum EVP_PKEY_MO_ENCRYPT = 0x0004;
enum EVP_PKEY_MO_DECRYPT = 0x0008;
// #ifndef EVP_MD
struct env_md_st
{
int type;
int pkey_type;
int md_size;
c_ulong flags;
ExternC!(int function(EVP_MD_CTX* ctx)) init_;
ExternC!(int function(EVP_MD_CTX* ctx,const(void)* data,size_t count)) update;
ExternC!(int function(EVP_MD_CTX* ctx,ubyte* md)) final_;
ExternC!(int function(EVP_MD_CTX* to,const(EVP_MD_CTX)* from)) copy;
ExternC!(int function(EVP_MD_CTX* ctx)) cleanup;
/* FIXME: prototype these some day */
ExternC!(int function(int type, const(ubyte)* m, uint m_length,
ubyte* sigret, uint* siglen, void* key)) sign;
ExternC!(int function(int type, const(ubyte)* m, uint m_length,
const(ubyte)* sigbuf, uint siglen,
void* key)) verify;
int[5] required_pkey_type; /*EVP_PKEY_xxx */
int block_size;
int ctx_size; /* how big does the ctx->md_data need to be */
/* control function */
ExternC!(int function(EVP_MD_CTX* ctx, int cmd, int p1, void* p2)) md_ctrl;
} /* EVP_MD */;
alias typeof(*(ExternC!(int function(int type,const(ubyte)* m,
uint m_length,ubyte* sigret,
uint* siglen, void* key))).init) evp_sign_method;
alias typeof(*(ExternC!(int function(int type,const(ubyte)* m,
uint m_length,const(ubyte)* sigbuf,
uint siglen, void* key))).init) evp_verify_method;
enum EVP_MD_FLAG_ONESHOT = 0x0001; /* digest can only handle a single
* block */
enum EVP_MD_FLAG_PKEY_DIGEST = 0x0002; /* digest is a "clone" digest used
* which is a copy of an existing
* one for a specific public key type.
* EVP_dss1() etc */
/* Digest uses EVP_PKEY_METHOD for signing instead of MD specific signing */
enum EVP_MD_FLAG_PKEY_METHOD_SIGNATURE = 0x0004;
/* DigestAlgorithmIdentifier flags... */
enum EVP_MD_FLAG_DIGALGID_MASK = 0x0018;
/* NULL or absent parameter accepted. Use NULL */
enum EVP_MD_FLAG_DIGALGID_NULL = 0x0000;
/* NULL or absent parameter accepted. Use NULL for PKCS#1 otherwise absent */
enum EVP_MD_FLAG_DIGALGID_ABSENT = 0x0008;
/* Custom handling via ctrl */
enum EVP_MD_FLAG_DIGALGID_CUSTOM = 0x0018;
enum EVP_MD_FLAG_FIPS = 0x0400; /* Note if suitable for use in FIPS mode */
/* Digest ctrls */
enum EVP_MD_CTRL_DIGALGID = 0x1;
enum EVP_MD_CTRL_MICALG = 0x2;
/* Minimum Algorithm specific ctrl value */
enum EVP_MD_CTRL_ALG_CTRL = 0x1000;
enum EVP_PKEY_NULL_method = "null,null,{0,0,0,0}";
version (OPENSSL_NO_DSA) {
alias EVP_PKEY_NULL_method EVP_PKEY_DSA_method;
} else {
enum EVP_PKEY_DSA_method = "cast(evp_sign_method*)&DSA_sign," ~
"cast(evp_verify_method*)&DSA_verify,{EVP_PKEY_DSA,EVP_PKEY_DSA2," ~
"EVP_PKEY_DSA3, EVP_PKEY_DSA4,0}";
}
version(OPENSSL_NO_ECDSA) {
alias EVP_PKEY_NULL_method EVP_PKEY_ECDSA_method;
} else {
enum EVP_PKEY_ECDSA_method = "cast(evp_sign_method*)&ECDSA_sign," ~
"cast(evp_verify_method*)&ECDSA_verify,{EVP_PKEY_EC,0,0,0}";
}
version (OPENSSL_NO_RSA) {
alias EVP_PKEY_NULL_method EVP_PKEY_RSA_method;
alias EVP_PKEY_NULL_method EVP_PKEY_RSA_ASN1_OCTET_STRING_method;
} else {
enum EVP_PKEY_RSA_method = "cast(evp_sign_method*)&RSA_sign," ~
"cast(evp_verify_method*)RSA_verify,{EVP_PKEY_RSA,EVP_PKEY_RSA2,0,0}";
enum EVP_PKEY_RSA_ASN1_OCTET_STRING_method =
"cast(evp_sign_method*)&RSA_sign_ASN1_OCTET_STRING," ~
"cast(evp_verify_method*)RSA_verify_ASN1_OCTET_STRING," ~
"{EVP_PKEY_RSA,EVP_PKEY_RSA2,0,0}";
}
// #endif /* !EVP_MD */
struct env_md_ctx_st
{
const(EVP_MD)* digest;
ENGINE* engine; /* functional reference if 'digest' is ENGINE-provided */
c_ulong flags;
void* md_data;
/* Public key context for sign/verify */
EVP_PKEY_CTX* pctx;
/* Update function: usually copied from EVP_MD */
ExternC!(int function(EVP_MD_CTX* ctx,const(void)* data,size_t count)) update;
} /* EVP_MD_CTX */;
/* values for EVP_MD_CTX flags */
enum EVP_MD_CTX_FLAG_ONESHOT = 0x0001; /* digest update will be called
* once only */
enum EVP_MD_CTX_FLAG_CLEANED = 0x0002; /* context has already been
* cleaned */
enum EVP_MD_CTX_FLAG_REUSE = 0x0004; /* Don't free up ctx->md_data
* in EVP_MD_CTX_cleanup */
/* FIPS and pad options are ignored in 1.0.0, definitions are here
* so we don't accidentally reuse the values for other purposes.
*/
enum EVP_MD_CTX_FLAG_NON_FIPS_ALLOW = 0x0008; /* Allow use of non FIPS digest
* in FIPS mode */
/* The following PAD options are also currently ignored in 1.0.0, digest
* parameters are handled through EVP_DigestSign*() and EVP_DigestVerify*()
* instead.
*/
enum EVP_MD_CTX_FLAG_PAD_MASK = 0xF0; /* RSA mode to use */
enum EVP_MD_CTX_FLAG_PAD_PKCS1 = 0x00; /* PKCS#1 v1.5 mode */
enum EVP_MD_CTX_FLAG_PAD_X931 = 0x10; /* X9.31 mode */
enum EVP_MD_CTX_FLAG_PAD_PSS = 0x20; /* PSS mode */
enum EVP_MD_CTX_FLAG_NO_INIT = 0x0100; /* Don't initialize md_data */
struct evp_cipher_st
{
int nid;
int block_size;
int key_len; /* Default value for variable length ciphers */
int iv_len;
c_ulong flags; /* Various flags */
ExternC!(int function(EVP_CIPHER_CTX* ctx, const(ubyte)* key,
const(ubyte)* iv, int enc)) init_; /* init key */
ExternC!(int function(EVP_CIPHER_CTX* ctx, ubyte* out_,
const(ubyte)* in_, size_t inl)) do_cipher;/* encrypt/decrypt data */
ExternC!(int function(EVP_CIPHER_CTX*)) cleanup; /* cleanup ctx */
int ctx_size; /* how big ctx->cipher_data needs to be */
ExternC!(int function(EVP_CIPHER_CTX*, ASN1_TYPE*)) set_asn1_parameters; /* Populate a ASN1_TYPE with parameters */
ExternC!(int function(EVP_CIPHER_CTX*, ASN1_TYPE*)) get_asn1_parameters; /* Get parameters from a ASN1_TYPE */
ExternC!(int function(EVP_CIPHER_CTX*, int type, int arg, void* ptr)) ctrl; /* Miscellaneous operations */
void* app_data; /* Application data */
} /* EVP_CIPHER */;
/* Values for cipher flags */
/* Modes for ciphers */
enum EVP_CIPH_STREAM_CIPHER = 0x0;
enum EVP_CIPH_ECB_MODE = 0x1;
enum EVP_CIPH_CBC_MODE = 0x2;
enum EVP_CIPH_CFB_MODE = 0x3;
enum EVP_CIPH_OFB_MODE = 0x4;
enum EVP_CIPH_CTR_MODE = 0x5;
enum EVP_CIPH_GCM_MODE = 0x6;
enum EVP_CIPH_CCM_MODE = 0x7;
enum EVP_CIPH_XTS_MODE = 0x10001;
enum EVP_CIPH_MODE = 0xF0007;
/* Set if variable length cipher */
enum EVP_CIPH_VARIABLE_LENGTH = 0x8;
/* Set if the iv handling should be done by the cipher itself */
enum EVP_CIPH_CUSTOM_IV = 0x10;
/* Set if the cipher's init() function should be called if key is NULL */
enum EVP_CIPH_ALWAYS_CALL_INIT = 0x20;
/* Call ctrl() to init cipher parameters */
enum EVP_CIPH_CTRL_INIT = 0x40;
/* Don't use standard key length function */
enum EVP_CIPH_CUSTOM_KEY_LENGTH = 0x80;
/* Don't use standard block padding */
enum EVP_CIPH_NO_PADDING = 0x100;
/* cipher handles random key generation */
enum EVP_CIPH_RAND_KEY = 0x200;
/* cipher has its own additional copying logic */
enum EVP_CIPH_CUSTOM_COPY = 0x400;
/* Allow use default ASN1 get/set iv */
enum EVP_CIPH_FLAG_DEFAULT_ASN1 = 0x1000;
/* Buffer length in bits not bytes: CFB1 mode only */
enum EVP_CIPH_FLAG_LENGTH_BITS = 0x2000;
/* Note if suitable for use in FIPS mode */
enum EVP_CIPH_FLAG_FIPS = 0x4000;
/* Allow non FIPS cipher in FIPS mode */
enum EVP_CIPH_FLAG_NON_FIPS_ALLOW = 0x8000;
/* Cipher handles any and all padding logic as well
* as finalisation.
*/
enum EVP_CIPH_FLAG_CUSTOM_CIPHER = 0x100000;
enum EVP_CIPH_FLAG_AEAD_CIPHER = 0x200000;
/* ctrl() values */
enum EVP_CTRL_INIT = 0x0;
enum EVP_CTRL_SET_KEY_LENGTH = 0x1;
enum EVP_CTRL_GET_RC2_KEY_BITS = 0x2;
enum EVP_CTRL_SET_RC2_KEY_BITS = 0x3;
enum EVP_CTRL_GET_RC5_ROUNDS = 0x4;
enum EVP_CTRL_SET_RC5_ROUNDS = 0x5;
enum EVP_CTRL_RAND_KEY = 0x6;
enum EVP_CTRL_PBE_PRF_NID = 0x7;
enum EVP_CTRL_COPY = 0x8;
enum EVP_CTRL_GCM_SET_IVLEN = 0x9;
enum EVP_CTRL_GCM_GET_TAG = 0x10;
enum EVP_CTRL_GCM_SET_TAG = 0x11;
enum EVP_CTRL_GCM_SET_IV_FIXED = 0x12;
enum EVP_CTRL_GCM_IV_GEN = 0x13;
alias EVP_CTRL_CCM_SET_IVLEN = EVP_CTRL_GCM_SET_IVLEN;
alias EVP_CTRL_CCM_GET_TAG = EVP_CTRL_GCM_GET_TAG;
alias EVP_CTRL_CCM_SET_TAG = EVP_CTRL_GCM_SET_TAG;
enum EVP_CTRL_CCM_SET_L = 0x14;
enum EVP_CTRL_CCM_SET_MSGLEN = 0x15;
/* AEAD cipher deduces payload length and returns number of bytes
* required to store MAC and eventual padding. Subsequent call to
* EVP_Cipher even appends/verifies MAC.
*/
enum EVP_CTRL_AEAD_TLS1_AAD = 0x16;
/* Used by composite AEAD ciphers, no-op in GCM, CCM... */
enum EVP_CTRL_AEAD_SET_MAC_KEY = 0x17;
/* Set the GCM invocation field, decrypt only */
enum EVP_CTRL_GCM_SET_IV_INV = 0x18;
/* GCM TLS constants */
/* Length of fixed part of IV derived from PRF */
enum EVP_GCM_TLS_FIXED_IV_LEN = 4;
/* Length of explicit part of IV part of TLS records */
enum EVP_GCM_TLS_EXPLICIT_IV_LEN = 8;
/* Length of tag for TLS */
enum EVP_GCM_TLS_TAG_LEN = 16;
struct evp_cipher_info_st {
const(EVP_CIPHER)* cipher;
ubyte[EVP_MAX_IV_LENGTH] iv;
}
alias evp_cipher_info_st EVP_CIPHER_INFO;
struct evp_cipher_ctx_st
{
const(EVP_CIPHER)* cipher;
ENGINE* engine; /* functional reference if 'cipher' is ENGINE-provided */
int encrypt; /* encrypt or decrypt */
int buf_len; /* number we have left */
ubyte[EVP_MAX_IV_LENGTH] oiv; /* original iv */
ubyte[EVP_MAX_IV_LENGTH] iv; /* working iv */
ubyte[EVP_MAX_BLOCK_LENGTH] buf;/* saved partial block */
int num; /* used by cfb/ofb mode */
void* app_data; /* application stuff */
int key_len; /* May change for variable length cipher */
c_ulong flags; /* Various flags */
void* cipher_data; /* per EVP data */
int final_used;
int block_mask;
ubyte[EVP_MAX_BLOCK_LENGTH] final_;/* possible final block */
} /* EVP_CIPHER_CTX */;
struct evp_Encode_Ctx_st {
int num; /* number saved in a partial encode/decode */
int length; /* The length is either the output line length
* (in input bytes) or the shortest input line
* length that is ok. Once decoding begins,
* the length is adjusted up each time a longer
* line is decoded */
ubyte[80] enc_data; /* data to encode */
int line_num; /* number read on current line */
int expect_nl;
}
alias evp_Encode_Ctx_st EVP_ENCODE_CTX;
/* Password based encryption function */
alias typeof(*(ExternC!(int function(EVP_CIPHER_CTX* ctx, const(char)* pass, int passlen,
ASN1_TYPE* param, const(EVP_CIPHER)* cipher,
const(EVP_MD)* md, int en_de))).init) EVP_PBE_KEYGEN;
version(OPENSSL_NO_RSA) {} else {
auto EVP_PKEY_assign_RSA()(EVP_PKEY* pkey, RSA* key) {
return EVP_PKEY_assign(pkey,EVP_PKEY_RSA,cast(void*)key);
}
}
version(OPENSSL_NO_DSA) {} else {
auto EVP_PKEY_assign_RSA()(EVP_PKEY* pkey, DSA* key) {
return EVP_PKEY_assign(pkey,EVP_PKEY_DSA,cast(void*)key);
}
}
version(OPENSSL_NO_DH) {} else {
auto EVP_PKEY_assign_DH()(EVP_PKEY* pkey, DH* key) {
return EVP_PKEY_assign(pkey,EVP_PKEY_DH,cast(void*)key);
}
}
version(OPENSSL_NO_EC) {} else {
auto EVP_PKEY_assign_EC_KEY()(EVP_PKEY* pkey, EC_KEY* key) {
return EVP_PKEY_assign(pkey,EVP_PKEY_EC,cast(void*)key);
}
}
/* Add some extra combinations */
auto EVP_get_digestbynid()(int a) { return EVP_get_digestbyname(OBJ_nid2sn(a)); }
auto EVP_get_digestbyobj()(const(ASN1_OBJECT)* a) { return EVP_get_digestbynid(OBJ_obj2nid(a)); }
auto EVP_get_cipherbynid()(int a) { return EVP_get_cipherbyname(OBJ_nid2sn(a)); }
auto EVP_get_cipherbyobj()(const(ASN1_OBJECT)* a) { return EVP_get_cipherbynid(OBJ_obj2nid(a)); }
int EVP_MD_type(const(EVP_MD)* md);
alias EVP_MD_type EVP_MD_nid;
auto EVP_MD_name()(const(EVP_MD)* e) { return OBJ_nid2sn(EVP_MD_nid(e)); }
int EVP_MD_pkey_type(const(EVP_MD)* md);
int EVP_MD_size(const(EVP_MD)* md);
int EVP_MD_block_size(const(EVP_MD)* md);
c_ulong EVP_MD_flags(const(EVP_MD)* md);
const(EVP_MD)* EVP_MD_CTX_md(const(EVP_MD_CTX)* ctx);
auto EVP_MD_CTX_size()(const(EVP_MD_CTX)* e) { return EVP_MD_size(EVP_MD_CTX_md(e)); }
auto EVP_MD_CTX_block_size()(const(EVP_MD_CTX)* e) { return EVP_MD_block_size(EVP_MD_CTX_md(e)); }
auto EVP_MD_CTX_type()(const(EVP_MD_CTX)* e) { return EVP_MD_type(EVP_MD_CTX_md(e)); }
int EVP_CIPHER_nid(const(EVP_CIPHER)* cipher);
auto EVP_CIPHER_name()(const(EVP_CIPHER)* e){ return OBJ_nid2sn(EVP_CIPHER_nid(e)); }
int EVP_CIPHER_block_size(const(EVP_CIPHER)* cipher);
int EVP_CIPHER_key_length(const(EVP_CIPHER)* cipher);
int EVP_CIPHER_iv_length(const(EVP_CIPHER)* cipher);
c_ulong EVP_CIPHER_flags(const(EVP_CIPHER)* cipher);
auto EVP_CIPHER_mode()(const(EVP_CIPHER)* e) { return (EVP_CIPHER_flags(e) & EVP_CIPH_MODE); }
const(EVP_CIPHER)* EVP_CIPHER_CTX_cipher(const(EVP_CIPHER_CTX)* ctx);
int EVP_CIPHER_CTX_nid(const(EVP_CIPHER_CTX)* ctx);
int EVP_CIPHER_CTX_block_size(const(EVP_CIPHER_CTX)* ctx);
int EVP_CIPHER_CTX_key_length(const(EVP_CIPHER_CTX)* ctx);
int EVP_CIPHER_CTX_iv_length(const(EVP_CIPHER_CTX)* ctx);
int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX* out_, const(EVP_CIPHER_CTX)* in_);
void* EVP_CIPHER_CTX_get_app_data(const(EVP_CIPHER_CTX)* ctx);
void EVP_CIPHER_CTX_set_app_data(EVP_CIPHER_CTX* ctx, void* data);
auto EVP_CIPHER_CTX_type()(const(EVP_CIPHER_CTX)* c) { return EVP_CIPHER_type(EVP_CIPHER_CTX_cipher(c)); }
c_ulong EVP_CIPHER_CTX_flags(const(EVP_CIPHER_CTX)* ctx);
auto EVP_CIPHER_CTX_mode()(const(EVP_CIPHER_CTX)* e) { return (EVP_CIPHER_CTX_flags(e) & EVP_CIPH_MODE); }
auto EVP_ENCODE_LENGTH(T)(T l) { return (((l+2)/3*4)+(l/48+1)*2+80); }
auto EVP_DECODE_LENGTH(T)(T l) { return ((l+3)/4*3+80); }
alias EVP_DigestInit_ex EVP_SignInit_ex;
alias EVP_DigestInit EVP_SignInit;
alias EVP_DigestUpdate EVP_SignUpdate;
alias EVP_DigestInit_ex EVP_VerifyInit_ex;
alias EVP_DigestInit EVP_VerifyInit;
alias EVP_DigestUpdate EVP_VerifyUpdate;
alias EVP_DecryptUpdate EVP_OpenUpdate;
alias EVP_EncryptUpdate EVP_SealUpdate;
alias EVP_DigestUpdate EVP_DigestSignUpdate;
alias EVP_DigestUpdate EVP_DigestVerifyUpdate;
void BIO_set_md()(BIO* b,const(EVP_MD)* md) { return BIO_ctrl(b,BIO_C_SET_MD,0,md); }
auto BIO_get_md()(BIO* b,EVP_MD** mdp) { return BIO_ctrl(b,BIO_C_GET_MD,0,mdp); }
auto BIO_get_md_ctx()(BIO* b,EVP_MD_CTX** mdcp) { return BIO_ctrl(b,BIO_C_GET_MD_CTX,0,mdcp); }
auto BIO_set_md_ctx()(BIO* b,EVP_MD_CTX** mdcp) { return BIO_ctrl(b,BIO_C_SET_MD_CTX,0,mdcp); }
auto BIO_get_cipher_status()(BIO* b) { return BIO_ctrl(b,BIO_C_GET_CIPHER_STATUS,0,null); }
auto BIO_get_cipher_ctx()(BIO* b,EVP_CIPHER_CTX** c_pp) { return BIO_ctrl(b,BIO_C_GET_CIPHER_CTX,0,c_pp); }
int EVP_Cipher(EVP_CIPHER_CTX* c,
ubyte* out_,
const(ubyte)* in_,
uint inl);
auto EVP_add_cipher_alias()(const(char)* n,const(char)* alias_) {
return OBJ_NAME_add(alias_,OBJ_NAME_TYPE_CIPHER_METH|OBJ_NAME_ALIAS,(n));
}
auto EVP_add_digest_alias()(const(char)* n,const(char)* alias_) {
return OBJ_NAME_add(alias_,OBJ_NAME_TYPE_MD_METH|OBJ_NAME_ALIAS,(n));
}
auto EVP_delete_cipher_alias()(const(char)* alias_) {
return OBJ_NAME_remove(alias_,OBJ_NAME_TYPE_CIPHER_METH|OBJ_NAME_ALIAS);
}
auto EVP_delete_digest_alias()(const(char)* alias_) {
return OBJ_NAME_remove(alias_,OBJ_NAME_TYPE_MD_METH|OBJ_NAME_ALIAS);
}
void EVP_MD_CTX_init(EVP_MD_CTX* ctx);
int EVP_MD_CTX_cleanup(EVP_MD_CTX* ctx);
EVP_MD_CTX* EVP_MD_CTX_create();
void EVP_MD_CTX_destroy(EVP_MD_CTX* ctx);
int EVP_MD_CTX_copy_ex(EVP_MD_CTX* out_,const(EVP_MD_CTX)* in_);
void EVP_MD_CTX_set_flags(EVP_MD_CTX* ctx, int flags);
void EVP_MD_CTX_clear_flags(EVP_MD_CTX* ctx, int flags);
int EVP_MD_CTX_test_flags(const(EVP_MD_CTX)* ctx,int flags);
int EVP_DigestInit_ex(EVP_MD_CTX* ctx, const(EVP_MD)* type, ENGINE* impl);
int EVP_DigestUpdate(EVP_MD_CTX* ctx,const(void)* d,
size_t cnt);
int EVP_DigestFinal_ex(EVP_MD_CTX* ctx,ubyte* md,uint* s);
int EVP_Digest(const(void)* data, size_t count,
ubyte* md, uint* size, const(EVP_MD)* type, ENGINE* impl);
int EVP_MD_CTX_copy(EVP_MD_CTX* out_,const(EVP_MD_CTX)* in_);
int EVP_DigestInit(EVP_MD_CTX* ctx, const(EVP_MD)* type);
int EVP_DigestFinal(EVP_MD_CTX* ctx,ubyte* md,uint* s);
int EVP_read_pw_string(char* buf,int length,const(char)* prompt,int verify);
int EVP_read_pw_string_min(char* buf,int minlen,int maxlen,const(char)* prompt,int verify);
void EVP_set_pw_prompt(const(char)* prompt);
char* EVP_get_pw_prompt();
int EVP_BytesToKey(const(EVP_CIPHER)* type,const(EVP_MD)* md,
const(ubyte)* salt, const(ubyte)* data,
int datal, int count, ubyte* key,ubyte* iv);
void EVP_CIPHER_CTX_set_flags(EVP_CIPHER_CTX* ctx, int flags);
void EVP_CIPHER_CTX_clear_flags(EVP_CIPHER_CTX* ctx, int flags);
int EVP_CIPHER_CTX_test_flags(const(EVP_CIPHER_CTX)* ctx,int flags);
int EVP_EncryptInit(EVP_CIPHER_CTX* ctx,const(EVP_CIPHER)* cipher,
const(ubyte)* key, const(ubyte)* iv);
int EVP_EncryptInit_ex(EVP_CIPHER_CTX* ctx,const(EVP_CIPHER)* cipher, ENGINE* impl,
const(ubyte)* key, const(ubyte)* iv);
int EVP_EncryptUpdate(EVP_CIPHER_CTX* ctx, ubyte* out_,
int* outl, const(ubyte)* in_, int inl);
int EVP_EncryptFinal_ex(EVP_CIPHER_CTX* ctx, ubyte* out_, int* outl);
int EVP_EncryptFinal(EVP_CIPHER_CTX* ctx, ubyte* out_, int* outl);
int EVP_DecryptInit(EVP_CIPHER_CTX* ctx,const(EVP_CIPHER)* cipher,
const(ubyte)* key, const(ubyte)* iv);
int EVP_DecryptInit_ex(EVP_CIPHER_CTX* ctx,const(EVP_CIPHER)* cipher, ENGINE* impl,
const(ubyte)* key, const(ubyte)* iv);
int EVP_DecryptUpdate(EVP_CIPHER_CTX* ctx, ubyte* out_,
int* outl, const(ubyte)* in_, int inl);
int EVP_DecryptFinal(EVP_CIPHER_CTX* ctx, ubyte* outm, int* outl);
int EVP_DecryptFinal_ex(EVP_CIPHER_CTX* ctx, ubyte* outm, int* outl);
int EVP_CipherInit(EVP_CIPHER_CTX* ctx,const(EVP_CIPHER)* cipher,
const(ubyte)* key,const(ubyte)* iv,
int enc);
int EVP_CipherInit_ex(EVP_CIPHER_CTX* ctx,const(EVP_CIPHER)* cipher, ENGINE* impl,
const(ubyte)* key,const(ubyte)* iv,
int enc);
int EVP_CipherUpdate(EVP_CIPHER_CTX* ctx, ubyte* out_,
int* outl, const(ubyte)* in_, int inl);
int EVP_CipherFinal(EVP_CIPHER_CTX* ctx, ubyte* outm, int* outl);
int EVP_CipherFinal_ex(EVP_CIPHER_CTX* ctx, ubyte* outm, int* outl);
int EVP_SignFinal(EVP_MD_CTX* ctx,ubyte* md,uint* s,
EVP_PKEY* pkey);
int EVP_VerifyFinal(EVP_MD_CTX* ctx,const(ubyte)* sigbuf,
uint siglen,EVP_PKEY* pkey);
int EVP_DigestSignInit(EVP_MD_CTX* ctx, EVP_PKEY_CTX** pctx,
const(EVP_MD)* type, ENGINE* e, EVP_PKEY* pkey);
int EVP_DigestSignFinal(EVP_MD_CTX* ctx,
ubyte* sigret, size_t* siglen);
int EVP_DigestVerifyInit(EVP_MD_CTX* ctx, EVP_PKEY_CTX** pctx,
const(EVP_MD)* type, ENGINE* e, EVP_PKEY* pkey);
int EVP_DigestVerifyFinal(EVP_MD_CTX* ctx,
ubyte* sig, size_t siglen);
int EVP_OpenInit(EVP_CIPHER_CTX* ctx,const(EVP_CIPHER)* type,
const(ubyte)* ek, int ekl, const(ubyte)* iv,
EVP_PKEY* priv);
int EVP_OpenFinal(EVP_CIPHER_CTX* ctx, ubyte* out_, int* outl);
int EVP_SealInit(EVP_CIPHER_CTX* ctx, const(EVP_CIPHER)* type,
ubyte** ek, int* ekl, ubyte* iv,
EVP_PKEY** pubk, int npubk);
int EVP_SealFinal(EVP_CIPHER_CTX* ctx,ubyte* out_,int* outl);
void EVP_EncodeInit(EVP_ENCODE_CTX* ctx);
void EVP_EncodeUpdate(EVP_ENCODE_CTX* ctx,ubyte* out_,int* outl,
const(ubyte)* in_,int inl);
void EVP_EncodeFinal(EVP_ENCODE_CTX* ctx,ubyte* out_,int* outl);
int EVP_EncodeBlock(ubyte* t, const(ubyte)* f, int n);
void EVP_DecodeInit(EVP_ENCODE_CTX* ctx);
int EVP_DecodeUpdate(EVP_ENCODE_CTX* ctx,ubyte* out_,int* outl,
const(ubyte)* in_, int inl);
int EVP_DecodeFinal(EVP_ENCODE_CTX* ctx, ubyte* out_, int* outl);
int EVP_DecodeBlock(ubyte* t, const(ubyte)* f, int n);
// Corresponding to the OpenSSL 1.1.0b
void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX* a); // alias EVP_CIPHER_CTX_reset
int EVP_CIPHER_CTX_reset(EVP_CIPHER_CTX* a);
EVP_CIPHER_CTX* EVP_CIPHER_CTX_new();
void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX* a);
int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX* x, int keylen);
int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX* c, int pad);
int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX* ctx, int type, int arg, void* ptr);
int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX* ctx, ubyte* key);
version(OPENSSL_NO_BIO) {} else {
BIO_METHOD* BIO_f_md();
BIO_METHOD* BIO_f_base64();
BIO_METHOD* BIO_f_cipher();
BIO_METHOD* BIO_f_reliable();
void BIO_set_cipher(BIO* b,const(EVP_CIPHER)* c,const(ubyte)* k,
const(ubyte)* i, int enc);
}
const(EVP_MD)* EVP_md_null();
version(OPENSSL_NO_MD2) {} else {
const(EVP_MD)* EVP_md2();
}
version(OPENSSL_NO_MD4) {} else {
const(EVP_MD)* EVP_md4();
}
version(OPENSSL_NO_MD5) {} else {
const(EVP_MD)* EVP_md5();
}
version(OPENSSL_NO_SHA) {} else {
const(EVP_MD)* EVP_sha();
const(EVP_MD)* EVP_sha1();
const(EVP_MD)* EVP_dss();
const(EVP_MD)* EVP_dss1();
const(EVP_MD)* EVP_ecdsa();
}
version(OPENSSL_NO_SHA256) {} else {
const(EVP_MD)* EVP_sha224();
const(EVP_MD)* EVP_sha256();
}
version(OPENSSL_NO_SHA512) {} else {
const(EVP_MD)* EVP_sha384();
const(EVP_MD)* EVP_sha512();
}
version(OPENSSL_NO_MDC2) {} else {
const(EVP_MD)* EVP_mdc2();
}
version(OPENSSL_NO_RIPEMD) {} else {
const(EVP_MD)* EVP_ripemd160();
}
version(OPENSSL_NO_WHIRLPOOL) {} else {
const(EVP_MD)* EVP_whirlpool();
}
const(EVP_CIPHER)* EVP_enc_null(); /* does nothing :-) */
version (OPENSSL_NO_DES) {} else {
const(EVP_CIPHER)* EVP_des_ecb();
const(EVP_CIPHER)* EVP_des_ede();
const(EVP_CIPHER)* EVP_des_ede3();
const(EVP_CIPHER)* EVP_des_ede_ecb();
const(EVP_CIPHER)* EVP_des_ede3_ecb();
const(EVP_CIPHER)* EVP_des_cfb64();
alias EVP_des_cfb64 EVP_des_cfb;
const(EVP_CIPHER)* EVP_des_cfb1();
const(EVP_CIPHER)* EVP_des_cfb8();
const(EVP_CIPHER)* EVP_des_ede_cfb64();
alias EVP_des_ede_cfb64 EVP_des_ede_cfb;
version (none) {
const(EVP_CIPHER)* EVP_des_ede_cfb1();
const(EVP_CIPHER)* EVP_des_ede_cfb8();
}
const(EVP_CIPHER)* EVP_des_ede3_cfb64();
alias EVP_des_ede3_cfb64 EVP_des_ede3_cfb;
const(EVP_CIPHER)* EVP_des_ede3_cfb1();
const(EVP_CIPHER)* EVP_des_ede3_cfb8();
const(EVP_CIPHER)* EVP_des_ofb();
const(EVP_CIPHER)* EVP_des_ede_ofb();
const(EVP_CIPHER)* EVP_des_ede3_ofb();
const(EVP_CIPHER)* EVP_des_cbc();
const(EVP_CIPHER)* EVP_des_ede_cbc();
const(EVP_CIPHER)* EVP_des_ede3_cbc();
const(EVP_CIPHER)* EVP_desx_cbc();
/* This should now be supported through the dev_crypto ENGINE. But also, why are
* rc4 and md5 declarations made here inside a "NO_DES" precompiler branch? */
//#if 0
//# ifdef OPENSSL_OPENBSD_DEV_CRYPTO
//const(EVP_CIPHER)* EVP_dev_crypto_des_ede3_cbc();
//const(EVP_CIPHER)* EVP_dev_crypto_rc4();
//const(EVP_MD)* EVP_dev_crypto_md5();
//# endif
//#endif
}
version(OPENSSL_NO_RC4) {} else {
const(EVP_CIPHER)* EVP_rc4();
const(EVP_CIPHER)* EVP_rc4_40();
version(OPENSSL_NO_MD5) {} else {
const(EVP_CIPHER)* EVP_rc4_hmac_md5();
}
}
version(OPENSSL_NO_IDEA) {} else {
const(EVP_CIPHER)* EVP_idea_ecb();
const(EVP_CIPHER)* EVP_idea_cfb64();
alias EVP_idea_cfb64 EVP_idea_cfb;
const(EVP_CIPHER)* EVP_idea_ofb();
const(EVP_CIPHER)* EVP_idea_cbc();
}
version(OPENSSL_NO_RC2) {} else {
const(EVP_CIPHER)* EVP_rc2_ecb();
const(EVP_CIPHER)* EVP_rc2_cbc();
const(EVP_CIPHER)* EVP_rc2_40_cbc();
const(EVP_CIPHER)* EVP_rc2_64_cbc();
const(EVP_CIPHER)* EVP_rc2_cfb64();
alias EVP_rc2_cfb64 EVP_rc2_cfb;
const(EVP_CIPHER)* EVP_rc2_ofb();
}
version(OPENSSL_NO_BF) {} else {
const(EVP_CIPHER)* EVP_bf_ecb();
const(EVP_CIPHER)* EVP_bf_cbc();
const(EVP_CIPHER)* EVP_bf_cfb64();
alias EVP_bf_cfb64 EVP_bf_cfb;
const(EVP_CIPHER)* EVP_bf_ofb();
}
version(OPENSSL_NO_CAST) {} else {
const(EVP_CIPHER)* EVP_cast5_ecb();
const(EVP_CIPHER)* EVP_cast5_cbc();
const(EVP_CIPHER)* EVP_cast5_cfb64();
alias EVP_cast5_cfb64 EVP_cast5_cfb;
const(EVP_CIPHER)* EVP_cast5_ofb();
}
version(OPENSSL_NO_RC5) {} else {
const(EVP_CIPHER)* EVP_rc5_32_12_16_cbc();
const(EVP_CIPHER)* EVP_rc5_32_12_16_ecb();
const(EVP_CIPHER)* EVP_rc5_32_12_16_cfb64();
alias EVP_rc5_32_12_16_cfb64 EVP_rc5_32_12_16_cfb;
const(EVP_CIPHER)* EVP_rc5_32_12_16_ofb();
}
version(OPENSSL_NO_AES) {} else {
const(EVP_CIPHER)* EVP_aes_128_ecb();
const(EVP_CIPHER)* EVP_aes_128_cbc();
const(EVP_CIPHER)* EVP_aes_128_cfb1();
const(EVP_CIPHER)* EVP_aes_128_cfb8();
const(EVP_CIPHER)* EVP_aes_128_cfb128();
alias EVP_aes_128_cfb128 EVP_aes_128_cfb;
const(EVP_CIPHER)* EVP_aes_128_ofb();
const(EVP_CIPHER)* EVP_aes_128_ctr();
const(EVP_CIPHER)* EVP_aes_128_ccm();
const(EVP_CIPHER)* EVP_aes_128_gcm();
const(EVP_CIPHER)* EVP_aes_128_xts();
const(EVP_CIPHER)* EVP_aes_192_ecb();
const(EVP_CIPHER)* EVP_aes_192_cbc();
const(EVP_CIPHER)* EVP_aes_192_cfb1();
const(EVP_CIPHER)* EVP_aes_192_cfb8();
const(EVP_CIPHER)* EVP_aes_192_cfb128();
alias EVP_aes_192_cfb128 EVP_aes_192_cfb;
const(EVP_CIPHER)* EVP_aes_192_ofb();
const(EVP_CIPHER)* EVP_aes_192_ctr();
const(EVP_CIPHER)* EVP_aes_192_ccm();
const(EVP_CIPHER)* EVP_aes_192_gcm();
const(EVP_CIPHER)* EVP_aes_256_ecb();
const(EVP_CIPHER)* EVP_aes_256_cbc();
const(EVP_CIPHER)* EVP_aes_256_cfb1();
const(EVP_CIPHER)* EVP_aes_256_cfb8();
const(EVP_CIPHER)* EVP_aes_256_cfb128();
alias EVP_aes_256_cfb128 EVP_aes_256_cfb;
const(EVP_CIPHER)* EVP_aes_256_ofb();
const(EVP_CIPHER)* EVP_aes_256_ctr();
const(EVP_CIPHER)* EVP_aes_256_ccm();
const(EVP_CIPHER)* EVP_aes_256_gcm();
const(EVP_CIPHER)* EVP_aes_256_xts();
version(OPENSSL_NO_SHA) {} else version(OPENSSL_NO_SHA1) {} else {
const(EVP_CIPHER)* EVP_aes_128_cbc_hmac_sha1();
const(EVP_CIPHER)* EVP_aes_256_cbc_hmac_sha1();
}
}
version(OPENSSL_NO_CAMELLIA) {} else {
const(EVP_CIPHER)* EVP_camellia_128_ecb();
const(EVP_CIPHER)* EVP_camellia_128_cbc();
const(EVP_CIPHER)* EVP_camellia_128_cfb1();
const(EVP_CIPHER)* EVP_camellia_128_cfb8();
const(EVP_CIPHER)* EVP_camellia_128_cfb128();
alias EVP_camellia_128_cfb128 EVP_camellia_128_cfb;
const(EVP_CIPHER)* EVP_camellia_128_ofb();
const(EVP_CIPHER)* EVP_camellia_192_ecb();
const(EVP_CIPHER)* EVP_camellia_192_cbc();
const(EVP_CIPHER)* EVP_camellia_192_cfb1();
const(EVP_CIPHER)* EVP_camellia_192_cfb8();
const(EVP_CIPHER)* EVP_camellia_192_cfb128();
alias EVP_camellia_192_cfb128 EVP_camellia_192_cfb;
const(EVP_CIPHER)* EVP_camellia_192_ofb();
const(EVP_CIPHER)* EVP_camellia_256_ecb();
const(EVP_CIPHER)* EVP_camellia_256_cbc();
const(EVP_CIPHER)* EVP_camellia_256_cfb1();
const(EVP_CIPHER)* EVP_camellia_256_cfb8();
const(EVP_CIPHER)* EVP_camellia_256_cfb128();
alias EVP_camellia_256_cfb128 EVP_camellia_256_cfb;
const(EVP_CIPHER)* EVP_camellia_256_ofb();
}
version(OPENSSL_NO_SEED) {} else {
const(EVP_CIPHER)* EVP_seed_ecb();
const(EVP_CIPHER)* EVP_seed_cbc();
const(EVP_CIPHER)* EVP_seed_cfb128();
alias EVP_seed_cfb128 EVP_seed_cfb;
const(EVP_CIPHER)* EVP_seed_ofb();
}
void OPENSSL_add_all_algorithms_noconf();
void OPENSSL_add_all_algorithms_conf();
version (OPENSSL_LOAD_CONF) {
alias OPENSSL_add_all_algorithms_conf OpenSSL_add_all_algorithms;
} else {
alias OPENSSL_add_all_algorithms_noconf OpenSSL_add_all_algorithms;
}
void OpenSSL_add_all_ciphers();
void OpenSSL_add_all_digests();
alias OpenSSL_add_all_algorithms SSLeay_add_all_algorithms;
alias OpenSSL_add_all_ciphers SSLeay_add_all_ciphers;
alias OpenSSL_add_all_digests SSLeay_add_all_digests;
int EVP_add_cipher(const(EVP_CIPHER)* cipher);
int EVP_add_digest(const(EVP_MD)* digest);
const(EVP_CIPHER)* EVP_get_cipherbyname(const(char)* name);
const(EVP_MD)* EVP_get_digestbyname(const(char)* name);
void EVP_cleanup();
void EVP_CIPHER_do_all(ExternC!(void function(const(EVP_CIPHER)* ciph,
const(char)* from, const(char)* to, void* x)) fn, void* arg);
void EVP_CIPHER_do_all_sorted(ExternC!(void function(const(EVP_CIPHER)* ciph,
const(char)* from, const(char)* to, void* x)) fn, void* arg);
void EVP_MD_do_all(ExternC!(void function(const(EVP_MD)* ciph,
const(char)* from, const(char)* to, void* x)) fn, void* arg);
void EVP_MD_do_all_sorted(ExternC!(void function(const(EVP_MD)* ciph,
const(char)* from, const(char)* to, void* x)) fn, void* arg);
int EVP_PKEY_decrypt_old(ubyte* dec_key,
const(ubyte)* enc_key,int enc_key_len,
EVP_PKEY* private_key);
int EVP_PKEY_encrypt_old(ubyte* enc_key,
const(ubyte)* key,int key_len,
EVP_PKEY* pub_key);
int EVP_PKEY_type(int type);
int EVP_PKEY_id(const(EVP_PKEY)* pkey);
int EVP_PKEY_base_id(const(EVP_PKEY)* pkey);
int EVP_PKEY_bits(EVP_PKEY* pkey);
int EVP_PKEY_size(EVP_PKEY* pkey);
int EVP_PKEY_set_type(EVP_PKEY* pkey,int type);
int EVP_PKEY_set_type_str(EVP_PKEY* pkey, const(char)* str, int len);
int EVP_PKEY_assign(EVP_PKEY* pkey,int type,void* key);
void* EVP_PKEY_get0(EVP_PKEY* pkey);
version(OPENSSL_NO_RSA) {} else {
import deimos.openssl.rsa; /*struct rsa_st;*/
int EVP_PKEY_set1_RSA(EVP_PKEY* pkey,rsa_st* key);
rsa_st* EVP_PKEY_get1_RSA(EVP_PKEY* pkey);
}
version(OPENSSL_NO_DSA) {} else {
import deimos.openssl.dsa; /*struct dsa_st;*/
int EVP_PKEY_set1_DSA(EVP_PKEY* pkey,dsa_st* key);
dsa_st* EVP_PKEY_get1_DSA(EVP_PKEY* pkey);
}
version(OPENSSL_NO_DH) {} else {
import deimos.openssl.dh; /*struct dh_st;*/
int EVP_PKEY_set1_DH(EVP_PKEY* pkey,dh_st* key);
dh_st* EVP_PKEY_get1_DH(EVP_PKEY* pkey);
}
version(OPENSSL_NO_EC) {} else {
struct ec_key_st;
int EVP_PKEY_set1_EC_KEY(EVP_PKEY* pkey,ec_key_st* key);
ec_key_st* EVP_PKEY_get1_EC_KEY(EVP_PKEY* pkey);
}
EVP_PKEY* EVP_PKEY_new();
void EVP_PKEY_free(EVP_PKEY* pkey);
EVP_PKEY* d2i_PublicKey(int type,EVP_PKEY** a, const(ubyte)** pp,
c_long length);
int i2d_PublicKey(EVP_PKEY* a, ubyte** pp);
EVP_PKEY* d2i_PrivateKey(int type,EVP_PKEY** a, const(ubyte)** pp,
c_long length);
EVP_PKEY* d2i_AutoPrivateKey(EVP_PKEY** a, const(ubyte)** pp,
c_long length);
int i2d_PrivateKey(EVP_PKEY* a, ubyte** pp);
int EVP_PKEY_copy_parameters(EVP_PKEY* to, const(EVP_PKEY)* from);
int EVP_PKEY_missing_parameters(const(EVP_PKEY)* pkey);
int EVP_PKEY_save_parameters(EVP_PKEY* pkey,int mode);
int EVP_PKEY_cmp_parameters(const(EVP_PKEY)* a, const(EVP_PKEY)* b);
int EVP_PKEY_cmp(const(EVP_PKEY)* a, const(EVP_PKEY)* b);
int EVP_PKEY_print_public(BIO* out_, const(EVP_PKEY)* pkey,
int indent, ASN1_PCTX* pctx);
int EVP_PKEY_print_private(BIO* out_, const(EVP_PKEY)* pkey,
int indent, ASN1_PCTX* pctx);
int EVP_PKEY_print_params(BIO* out_, const(EVP_PKEY)* pkey,
int indent, ASN1_PCTX* pctx);
int EVP_PKEY_get_default_digest_nid(EVP_PKEY* pkey, int* pnid);
int EVP_CIPHER_type(const(EVP_CIPHER)* ctx);
/* calls methods */
int EVP_CIPHER_param_to_asn1(EVP_CIPHER_CTX* c, ASN1_TYPE* type);
int EVP_CIPHER_asn1_to_param(EVP_CIPHER_CTX* c, ASN1_TYPE* type);
/* These are used by EVP_CIPHER methods */
int EVP_CIPHER_set_asn1_iv(EVP_CIPHER_CTX* c,ASN1_TYPE* type);
int EVP_CIPHER_get_asn1_iv(EVP_CIPHER_CTX* c,ASN1_TYPE* type);
/* PKCS5 password based encryption */
int PKCS5_PBE_keyivgen(EVP_CIPHER_CTX* ctx, const(char)* pass, int passlen,
ASN1_TYPE* param, const(EVP_CIPHER)* cipher, const(EVP_MD)* md,
int en_de);
int PKCS5_PBKDF2_HMAC_SHA1(const(char)* pass, int passlen,
const(ubyte)* salt, int saltlen, int iter,
int keylen, ubyte* out_);
int PKCS5_PBKDF2_HMAC(const(char)* pass, int passlen,
const(ubyte)* salt, int saltlen, int iter,
const(EVP_MD)* digest,
int keylen, ubyte* out_);
int PKCS5_v2_PBE_keyivgen(EVP_CIPHER_CTX* ctx, const(char)* pass, int passlen,
ASN1_TYPE* param, const(EVP_CIPHER)* cipher, const(EVP_MD)* md,
int en_de);
void PKCS5_PBE_add();
int EVP_PBE_CipherInit (ASN1_OBJECT* pbe_obj, const(char)* pass, int passlen,
ASN1_TYPE* param, EVP_CIPHER_CTX* ctx, int en_de);
/* PBE type */
/* Can appear as the outermost AlgorithmIdentifier */
enum EVP_PBE_TYPE_OUTER = 0x0;
/* Is an PRF type OID */
enum EVP_PBE_TYPE_PRF = 0x1;
int EVP_PBE_alg_add_type(int pbe_type, int pbe_nid, int cipher_nid, int md_nid,
EVP_PBE_KEYGEN* keygen);
int EVP_PBE_alg_add(int nid, const(EVP_CIPHER)* cipher, const(EVP_MD)* md,
EVP_PBE_KEYGEN* keygen);
int EVP_PBE_find(int type, int pbe_nid,
int* pcnid, int* pmnid, EVP_PBE_KEYGEN** pkeygen);
void EVP_PBE_cleanup();
enum ASN1_PKEY_ALIAS = 0x1;
enum ASN1_PKEY_DYNAMIC = 0x2;
enum ASN1_PKEY_SIGPARAM_NULL = 0x4;
enum ASN1_PKEY_CTRL_PKCS7_SIGN = 0x1;
enum ASN1_PKEY_CTRL_PKCS7_ENCRYPT = 0x2;
enum ASN1_PKEY_CTRL_DEFAULT_MD_NID = 0x3;
enum ASN1_PKEY_CTRL_CMS_SIGN = 0x5;
enum ASN1_PKEY_CTRL_CMS_ENVELOPE = 0x7;
int EVP_PKEY_asn1_get_count();
const(EVP_PKEY_ASN1_METHOD)* EVP_PKEY_asn1_get0(int idx);
const(EVP_PKEY_ASN1_METHOD)* EVP_PKEY_asn1_find(ENGINE** pe, int type);
const(EVP_PKEY_ASN1_METHOD)* EVP_PKEY_asn1_find_str(ENGINE** pe,
const(char)* str, int len);
int EVP_PKEY_asn1_add0(const(EVP_PKEY_ASN1_METHOD)* ameth);
int EVP_PKEY_asn1_add_alias(int to, int from);
int EVP_PKEY_asn1_get0_info(int* ppkey_id, int* pkey_base_id, int* ppkey_flags,
const(char)** pinfo, const(char)** ppem_str,
const(EVP_PKEY_ASN1_METHOD)* ameth);
const(EVP_PKEY_ASN1_METHOD)* EVP_PKEY_get0_asn1(EVP_PKEY* pkey);
EVP_PKEY_ASN1_METHOD* EVP_PKEY_asn1_new(int id, int flags,
const(char)* pem_str, const(char)* info);
void EVP_PKEY_asn1_copy(EVP_PKEY_ASN1_METHOD* dst,
const(EVP_PKEY_ASN1_METHOD)* src);
void EVP_PKEY_asn1_free(EVP_PKEY_ASN1_METHOD* ameth);
void EVP_PKEY_asn1_set_public(EVP_PKEY_ASN1_METHOD* ameth,
ExternC!(int function(EVP_PKEY* pk, X509_PUBKEY* pub)) pub_decode,
ExternC!(int function(X509_PUBKEY* pub, const(EVP_PKEY)* pk)) pub_encode,
ExternC!(int function(const(EVP_PKEY)* a, const(EVP_PKEY)* b)) pub_cmp,
ExternC!(int function(BIO* out_, const(EVP_PKEY)* pkey, int indent,
ASN1_PCTX* pctx)) pub_print,
ExternC!(int function(const(EVP_PKEY)* pk)) pkey_size,
ExternC!(int function(const(EVP_PKEY)* pk)) pkey_bits);
void EVP_PKEY_asn1_set_private(EVP_PKEY_ASN1_METHOD* ameth,
ExternC!(int function(EVP_PKEY* pk, PKCS8_PRIV_KEY_INFO* p8inf)) priv_decode,
ExternC!(int function(PKCS8_PRIV_KEY_INFO* p8, const(EVP_PKEY)* pk)) priv_encode,
ExternC!(int function(BIO* out_, const(EVP_PKEY)* pkey, int indent,
ASN1_PCTX* pctx)) priv_print);
void EVP_PKEY_asn1_set_param(EVP_PKEY_ASN1_METHOD* ameth,
ExternC!(int function(EVP_PKEY* pkey,
const(ubyte)** pder, int derlen)) param_decode,
ExternC!(int function(const(EVP_PKEY)* pkey, ubyte** pder)) param_encode,
ExternC!(int function(const(EVP_PKEY)* pk)) param_missing,
ExternC!(int function(EVP_PKEY* to, const(EVP_PKEY)* from)) param_copy,
ExternC!(int function(const(EVP_PKEY)* a, const(EVP_PKEY)* b)) param_cmp,
ExternC!(int function(BIO* out_, const(EVP_PKEY)* pkey, int indent,
ASN1_PCTX* pctx)) param_print);
void EVP_PKEY_asn1_set_free(EVP_PKEY_ASN1_METHOD* ameth,
ExternC!(void function(EVP_PKEY* pkey)) pkey_free);
void EVP_PKEY_asn1_set_ctrl(EVP_PKEY_ASN1_METHOD* ameth,
ExternC!(int function(EVP_PKEY* pkey, int op,
c_long arg1, void* arg2)) pkey_ctrl);
enum EVP_PKEY_OP_UNDEFINED = 0;
enum EVP_PKEY_OP_PARAMGEN = (1<<1);
enum EVP_PKEY_OP_KEYGEN = (1<<2);
enum EVP_PKEY_OP_SIGN = (1<<3);
enum EVP_PKEY_OP_VERIFY = (1<<4);
enum EVP_PKEY_OP_VERIFYRECOVER = (1<<5);
enum EVP_PKEY_OP_SIGNCTX = (1<<6);
enum EVP_PKEY_OP_VERIFYCTX = (1<<7);
enum EVP_PKEY_OP_ENCRYPT = (1<<8);
enum EVP_PKEY_OP_DECRYPT = (1<<9);
enum EVP_PKEY_OP_DERIVE = (1<<10);
enum EVP_PKEY_OP_TYPE_SIG =
(EVP_PKEY_OP_SIGN | EVP_PKEY_OP_VERIFY | EVP_PKEY_OP_VERIFYRECOVER
| EVP_PKEY_OP_SIGNCTX | EVP_PKEY_OP_VERIFYCTX);
enum EVP_PKEY_OP_TYPE_CRYPT =
(EVP_PKEY_OP_ENCRYPT | EVP_PKEY_OP_DECRYPT);
/+ BUG in original headers: EVP_PKEY_OP_SIG, EVP_PKEY_OP_CRYPT are not defined.
enum EVP_PKEY_OP_TYPE_NOGEN =
(EVP_PKEY_OP_SIG | EVP_PKEY_OP_CRYPT | EVP_PKEY_OP_DERIVE);
+/
enum EVP_PKEY_OP_TYPE_GEN =
(EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN);
auto EVP_PKEY_CTX_set_signature_md()(EVP_PKEY_CTX* ctx, void* md) {
return EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_TYPE_SIG,
EVP_PKEY_CTRL_MD, 0, md);
}
enum EVP_PKEY_CTRL_MD = 1;
enum EVP_PKEY_CTRL_PEER_KEY = 2;
enum EVP_PKEY_CTRL_PKCS7_ENCRYPT = 3;
enum EVP_PKEY_CTRL_PKCS7_DECRYPT = 4;
enum EVP_PKEY_CTRL_PKCS7_SIGN = 5;
enum EVP_PKEY_CTRL_SET_MAC_KEY = 6;
enum EVP_PKEY_CTRL_DIGESTINIT = 7;
/* Used by GOST key encryption in TLS */
enum EVP_PKEY_CTRL_SET_IV = 8;
enum EVP_PKEY_CTRL_CMS_ENCRYPT = 9;
enum EVP_PKEY_CTRL_CMS_DECRYPT = 10;
enum EVP_PKEY_CTRL_CMS_SIGN = 11;
enum EVP_PKEY_CTRL_CIPHER = 12;
enum EVP_PKEY_ALG_CTRL = 0x1000;
enum EVP_PKEY_FLAG_AUTOARGLEN = 2;
/* Method handles all operations: don't assume any digest related
* defaults.
*/
enum EVP_PKEY_FLAG_SIGCTX_CUSTOM = 4;
const(EVP_PKEY_METHOD)* EVP_PKEY_meth_find(int type);
EVP_PKEY_METHOD* EVP_PKEY_meth_new(int id, int flags);
void EVP_PKEY_meth_get0_info(int* ppkey_id, int* pflags,
const(EVP_PKEY_METHOD)* meth);
void EVP_PKEY_meth_copy(EVP_PKEY_METHOD* dst, const(EVP_PKEY_METHOD)* src);
void EVP_PKEY_meth_free(EVP_PKEY_METHOD* pmeth);
int EVP_PKEY_meth_add0(const(EVP_PKEY_METHOD)* pmeth);
EVP_PKEY_CTX* EVP_PKEY_CTX_new(EVP_PKEY* pkey, ENGINE* e);
EVP_PKEY_CTX* EVP_PKEY_CTX_new_id(int id, ENGINE* e);
EVP_PKEY_CTX* EVP_PKEY_CTX_dup(EVP_PKEY_CTX* ctx);
void EVP_PKEY_CTX_free(EVP_PKEY_CTX* ctx);
int EVP_PKEY_CTX_ctrl(EVP_PKEY_CTX* ctx, int keytype, int optype,
int cmd, int p1, void* p2);
int EVP_PKEY_CTX_ctrl_str(EVP_PKEY_CTX* ctx, const(char)* type,
const(char)* value);
int EVP_PKEY_CTX_get_operation(EVP_PKEY_CTX* ctx);
void EVP_PKEY_CTX_set0_keygen_info(EVP_PKEY_CTX* ctx, int* dat, int datlen);
EVP_PKEY* EVP_PKEY_new_mac_key(int type, ENGINE* e,
const(ubyte)* key, int keylen);
void EVP_PKEY_CTX_set_data(EVP_PKEY_CTX* ctx, void* data);
void* EVP_PKEY_CTX_get_data(EVP_PKEY_CTX* ctx);
EVP_PKEY* EVP_PKEY_CTX_get0_pkey(EVP_PKEY_CTX* ctx);
EVP_PKEY* EVP_PKEY_CTX_get0_peerkey(EVP_PKEY_CTX* ctx);
void EVP_PKEY_CTX_set_app_data(EVP_PKEY_CTX* ctx, void* data);
void* EVP_PKEY_CTX_get_app_data(EVP_PKEY_CTX* ctx);
int EVP_PKEY_sign_init(EVP_PKEY_CTX* ctx);
int EVP_PKEY_sign(EVP_PKEY_CTX* ctx,
ubyte* sig, size_t* siglen,
const(ubyte)* tbs, size_t tbslen);
int EVP_PKEY_verify_init(EVP_PKEY_CTX* ctx);
int EVP_PKEY_verify(EVP_PKEY_CTX* ctx,
const(ubyte)* sig, size_t siglen,
const(ubyte)* tbs, size_t tbslen);
int EVP_PKEY_verify_recover_init(EVP_PKEY_CTX* ctx);
int EVP_PKEY_verify_recover(EVP_PKEY_CTX* ctx,
ubyte* rout, size_t* routlen,
const(ubyte)* sig, size_t siglen);
int EVP_PKEY_encrypt_init(EVP_PKEY_CTX* ctx);
int EVP_PKEY_encrypt(EVP_PKEY_CTX* ctx,
ubyte* out_, size_t* outlen,
const(ubyte)* in_, size_t inlen);
int EVP_PKEY_decrypt_init(EVP_PKEY_CTX* ctx);
int EVP_PKEY_decrypt(EVP_PKEY_CTX* ctx,
ubyte* out_, size_t* outlen,
const(ubyte)* in_, size_t inlen);
int EVP_PKEY_derive_init(EVP_PKEY_CTX* ctx);
int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX* ctx, EVP_PKEY* peer);
int EVP_PKEY_derive(EVP_PKEY_CTX* ctx, ubyte* key, size_t* keylen);
alias typeof(*(ExternC!(int function(EVP_PKEY_CTX* ctx))).init) EVP_PKEY_gen_cb;
int EVP_PKEY_paramgen_init(EVP_PKEY_CTX* ctx);
int EVP_PKEY_paramgen(EVP_PKEY_CTX* ctx, EVP_PKEY** ppkey);
int EVP_PKEY_keygen_init(EVP_PKEY_CTX* ctx);
int EVP_PKEY_keygen(EVP_PKEY_CTX* ctx, EVP_PKEY** ppkey);
void EVP_PKEY_CTX_set_cb(EVP_PKEY_CTX* ctx, EVP_PKEY_gen_cb* cb);
EVP_PKEY_gen_cb* EVP_PKEY_CTX_get_cb(EVP_PKEY_CTX* ctx);
int EVP_PKEY_CTX_get_keygen_info(EVP_PKEY_CTX* ctx, int idx);
void EVP_PKEY_meth_set_init(EVP_PKEY_METHOD* pmeth,
ExternC!(int function(EVP_PKEY_CTX* ctx)) init);
void EVP_PKEY_meth_set_copy(EVP_PKEY_METHOD* pmeth,
ExternC!(int function(EVP_PKEY_CTX* dst, EVP_PKEY_CTX* src)) copy);
void EVP_PKEY_meth_set_cleanup(EVP_PKEY_METHOD* pmeth,
ExternC!(void function(EVP_PKEY_CTX* ctx)) cleanup);
void EVP_PKEY_meth_set_paramgen(EVP_PKEY_METHOD* pmeth,
ExternC!(int function(EVP_PKEY_CTX* ctx)) paramgen_init,
ExternC!(int function(EVP_PKEY_CTX* ctx, EVP_PKEY* pkey)) paramgen);
void EVP_PKEY_meth_set_keygen(EVP_PKEY_METHOD* pmeth,
ExternC!(int function(EVP_PKEY_CTX* ctx)) keygen_init,
ExternC!(int function(EVP_PKEY_CTX* ctx, EVP_PKEY* pkey)) keygen);
void EVP_PKEY_meth_set_sign(EVP_PKEY_METHOD* pmeth,
ExternC!(int function(EVP_PKEY_CTX* ctx)) sign_init,
ExternC!(int function(EVP_PKEY_CTX* ctx, ubyte* sig, size_t* siglen,
const(ubyte)* tbs, size_t tbslen)) sign);
void EVP_PKEY_meth_set_verify(EVP_PKEY_METHOD* pmeth,
ExternC!(int function(EVP_PKEY_CTX* ctx)) verify_init,
ExternC!(int function(EVP_PKEY_CTX* ctx, const(ubyte)* sig, size_t siglen,
const(ubyte)* tbs, size_t tbslen)) verify);
void EVP_PKEY_meth_set_verify_recover(EVP_PKEY_METHOD* pmeth,
ExternC!(int function(EVP_PKEY_CTX* ctx)) verify_recover_init,
ExternC!(int function(EVP_PKEY_CTX* ctx,
ubyte* sig, size_t* siglen,
const(ubyte)* tbs, size_t tbslen)) verify_recover);
void EVP_PKEY_meth_set_signctx(EVP_PKEY_METHOD* pmeth,
ExternC!(int function(EVP_PKEY_CTX* ctx, EVP_MD_CTX* mctx)) signctx_init,
ExternC!(int function(EVP_PKEY_CTX* ctx, ubyte* sig, size_t* siglen,
EVP_MD_CTX* mctx)) signctx);
void EVP_PKEY_meth_set_verifyctx(EVP_PKEY_METHOD* pmeth,
ExternC!(int function(EVP_PKEY_CTX* ctx, EVP_MD_CTX* mctx)) verifyctx_init,
ExternC!(int function(EVP_PKEY_CTX* ctx, const(ubyte)* sig,int siglen,
EVP_MD_CTX* mctx)) verifyctx);
void EVP_PKEY_meth_set_encrypt(EVP_PKEY_METHOD* pmeth,
ExternC!(int function(EVP_PKEY_CTX* ctx)) encrypt_init,
ExternC!(int function(EVP_PKEY_CTX* ctx, ubyte* out_, size_t* outlen,
const(ubyte)* in_, size_t inlen)) encryptfn);
void EVP_PKEY_meth_set_decrypt(EVP_PKEY_METHOD* pmeth,
ExternC!(int function(EVP_PKEY_CTX* ctx)) decrypt_init,
ExternC!(int function(EVP_PKEY_CTX* ctx, ubyte* out_, size_t* outlen,
const(ubyte)* in_, size_t inlen)) decrypt);
void EVP_PKEY_meth_set_derive(EVP_PKEY_METHOD* pmeth,
ExternC!(int function(EVP_PKEY_CTX* ctx)) derive_init,
ExternC!(int function(EVP_PKEY_CTX* ctx, ubyte* key, size_t* keylen)) derive);
void EVP_PKEY_meth_set_ctrl(EVP_PKEY_METHOD* pmeth,
ExternC!(int function(EVP_PKEY_CTX* ctx, int type, int p1, void* p2)) ctrl,
ExternC!(int function(EVP_PKEY_CTX* ctx,
const(char)* type, const(char)* value)) ctrl_str);
void EVP_add_alg_module();
/* BEGIN ERROR CODES */
/* The following lines are auto generated by the script mkerr.pl. Any changes
* made after this point may be overwritten when the script is next run.
*/
void ERR_load_EVP_strings();
/* Error codes for the EVP functions. */
/* Function codes. */
enum EVP_F_AESNI_INIT_KEY = 165;
enum EVP_F_AESNI_XTS_CIPHER = 176;
enum EVP_F_AES_INIT_KEY = 133;
enum EVP_F_AES_XTS = 172;
enum EVP_F_AES_XTS_CIPHER = 175;
enum EVP_F_ALG_MODULE_INIT = 177;
enum EVP_F_CAMELLIA_INIT_KEY = 159;
enum EVP_F_CMAC_INIT = 173;
enum EVP_F_D2I_PKEY = 100;
enum EVP_F_DO_SIGVER_INIT = 161;
enum EVP_F_DSAPKEY2PKCS8 = 134;
enum EVP_F_DSA_PKEY2PKCS8 = 135;
enum EVP_F_ECDSA_PKEY2PKCS8 = 129;
enum EVP_F_ECKEY_PKEY2PKCS8 = 132;
enum EVP_F_EVP_CIPHERINIT_EX = 123;
enum EVP_F_EVP_CIPHER_CTX_COPY = 163;
enum EVP_F_EVP_CIPHER_CTX_CTRL = 124;
enum EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH = 122;
enum EVP_F_EVP_DECRYPTFINAL_EX = 101;
enum EVP_F_EVP_DIGESTINIT_EX = 128;
enum EVP_F_EVP_ENCRYPTFINAL_EX = 127;
enum EVP_F_EVP_MD_CTX_COPY_EX = 110;
enum EVP_F_EVP_MD_SIZE = 162;
enum EVP_F_EVP_OPENINIT = 102;
enum EVP_F_EVP_PBE_ALG_ADD = 115;
enum EVP_F_EVP_PBE_ALG_ADD_TYPE = 160;
enum EVP_F_EVP_PBE_CIPHERINIT = 116;
enum EVP_F_EVP_PKCS82PKEY = 111;
enum EVP_F_EVP_PKCS82PKEY_BROKEN = 136;
enum EVP_F_EVP_PKEY2PKCS8_BROKEN = 113;
enum EVP_F_EVP_PKEY_COPY_PARAMETERS = 103;
enum EVP_F_EVP_PKEY_CTX_CTRL = 137;
enum EVP_F_EVP_PKEY_CTX_CTRL_STR = 150;
enum EVP_F_EVP_PKEY_CTX_DUP = 156;
enum EVP_F_EVP_PKEY_DECRYPT = 104;
enum EVP_F_EVP_PKEY_DECRYPT_INIT = 138;
enum EVP_F_EVP_PKEY_DECRYPT_OLD = 151;
enum EVP_F_EVP_PKEY_DERIVE = 153;
enum EVP_F_EVP_PKEY_DERIVE_INIT = 154;
enum EVP_F_EVP_PKEY_DERIVE_SET_PEER = 155;
enum EVP_F_EVP_PKEY_ENCRYPT = 105;
enum EVP_F_EVP_PKEY_ENCRYPT_INIT = 139;
enum EVP_F_EVP_PKEY_ENCRYPT_OLD = 152;
enum EVP_F_EVP_PKEY_GET1_DH = 119;
enum EVP_F_EVP_PKEY_GET1_DSA = 120;
enum EVP_F_EVP_PKEY_GET1_ECDSA = 130;
enum EVP_F_EVP_PKEY_GET1_EC_KEY = 131;
enum EVP_F_EVP_PKEY_GET1_RSA = 121;
enum EVP_F_EVP_PKEY_KEYGEN = 146;
enum EVP_F_EVP_PKEY_KEYGEN_INIT = 147;
enum EVP_F_EVP_PKEY_NEW = 106;
enum EVP_F_EVP_PKEY_PARAMGEN = 148;
enum EVP_F_EVP_PKEY_PARAMGEN_INIT = 149;
enum EVP_F_EVP_PKEY_SIGN = 140;
enum EVP_F_EVP_PKEY_SIGN_INIT = 141;
enum EVP_F_EVP_PKEY_VERIFY = 142;
enum EVP_F_EVP_PKEY_VERIFY_INIT = 143;
enum EVP_F_EVP_PKEY_VERIFY_RECOVER = 144;
enum EVP_F_EVP_PKEY_VERIFY_RECOVER_INIT = 145;
enum EVP_F_EVP_RIJNDAEL = 126;
enum EVP_F_EVP_SIGNFINAL = 107;
enum EVP_F_EVP_VERIFYFINAL = 108;
enum EVP_F_FIPS_CIPHERINIT = 166;
enum EVP_F_FIPS_CIPHER_CTX_COPY = 170;
enum EVP_F_FIPS_CIPHER_CTX_CTRL = 167;
enum EVP_F_FIPS_CIPHER_CTX_SET_KEY_LENGTH = 171;
enum EVP_F_FIPS_DIGESTINIT = 168;
enum EVP_F_FIPS_MD_CTX_COPY = 169;
enum EVP_F_HMAC_INIT_EX = 174;
enum EVP_F_INT_CTX_NEW = 157;
enum EVP_F_PKCS5_PBE_KEYIVGEN = 117;
enum EVP_F_PKCS5_V2_PBE_KEYIVGEN = 118;
enum EVP_F_PKCS5_V2_PBKDF2_KEYIVGEN = 164;
enum EVP_F_PKCS8_SET_BROKEN = 112;
enum EVP_F_PKEY_SET_TYPE = 158;
enum EVP_F_RC2_MAGIC_TO_METH = 109;
enum EVP_F_RC5_CTRL = 125;
/* Reason codes. */
enum EVP_R_AES_IV_SETUP_FAILED = 162;
enum EVP_R_AES_KEY_SETUP_FAILED = 143;
enum EVP_R_ASN1_LIB = 140;
enum EVP_R_BAD_BLOCK_LENGTH = 136;
enum EVP_R_BAD_DECRYPT = 100;
enum EVP_R_BAD_KEY_LENGTH = 137;
enum EVP_R_BN_DECODE_ERROR = 112;
enum EVP_R_BN_PUBKEY_ERROR = 113;
enum EVP_R_BUFFER_TOO_SMALL = 155;
enum EVP_R_CAMELLIA_KEY_SETUP_FAILED = 157;
enum EVP_R_CIPHER_PARAMETER_ERROR = 122;
enum EVP_R_COMMAND_NOT_SUPPORTED = 147;
enum EVP_R_CTRL_NOT_IMPLEMENTED = 132;
enum EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED = 133;
enum EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH = 138;
enum EVP_R_DECODE_ERROR = 114;
enum EVP_R_DIFFERENT_KEY_TYPES = 101;
enum EVP_R_DIFFERENT_PARAMETERS = 153;
enum EVP_R_DISABLED_FOR_FIPS = 163;
enum EVP_R_ENCODE_ERROR = 115;
enum EVP_R_ERROR_LOADING_SECTION = 165;
enum EVP_R_ERROR_SETTING_FIPS_MODE = 166;
enum EVP_R_EVP_PBE_CIPHERINIT_ERROR = 119;
enum EVP_R_EXPECTING_AN_RSA_KEY = 127;
enum EVP_R_EXPECTING_A_DH_KEY = 128;
enum EVP_R_EXPECTING_A_DSA_KEY = 129;
enum EVP_R_EXPECTING_A_ECDSA_KEY = 141;
enum EVP_R_EXPECTING_A_EC_KEY = 142;
enum EVP_R_FIPS_MODE_NOT_SUPPORTED = 167;
enum EVP_R_INITIALIZATION_ERROR = 134;
enum EVP_R_INPUT_NOT_INITIALIZED = 111;
enum EVP_R_INVALID_DIGEST = 152;
enum EVP_R_INVALID_FIPS_MODE = 168;
enum EVP_R_INVALID_KEY_LENGTH = 130;
enum EVP_R_INVALID_OPERATION = 148;
enum EVP_R_IV_TOO_LARGE = 102;
enum EVP_R_KEYGEN_FAILURE = 120;
enum EVP_R_MESSAGE_DIGEST_IS_NULL = 159;
enum EVP_R_METHOD_NOT_SUPPORTED = 144;
enum EVP_R_MISSING_PARAMETERS = 103;
enum EVP_R_NO_CIPHER_SET = 131;
enum EVP_R_NO_DEFAULT_DIGEST = 158;
enum EVP_R_NO_DIGEST_SET = 139;
enum EVP_R_NO_DSA_PARAMETERS = 116;
enum EVP_R_NO_KEY_SET = 154;
enum EVP_R_NO_OPERATION_SET = 149;
enum EVP_R_NO_SIGN_FUNCTION_CONFIGURED = 104;
enum EVP_R_NO_VERIFY_FUNCTION_CONFIGURED = 105;
enum EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE = 150;
enum EVP_R_OPERATON_NOT_INITIALIZED = 151;
enum EVP_R_PKCS8_UNKNOWN_BROKEN_TYPE = 117;
enum EVP_R_PRIVATE_KEY_DECODE_ERROR = 145;
enum EVP_R_PRIVATE_KEY_ENCODE_ERROR = 146;
enum EVP_R_PUBLIC_KEY_NOT_RSA = 106;
enum EVP_R_TOO_LARGE = 164;
enum EVP_R_UNKNOWN_CIPHER = 160;
enum EVP_R_UNKNOWN_DIGEST = 161;
enum EVP_R_UNKNOWN_OPTION = 169;
enum EVP_R_UNKNOWN_PBE_ALGORITHM = 121;
enum EVP_R_UNSUPORTED_NUMBER_OF_ROUNDS = 135;
enum EVP_R_UNSUPPORTED_ALGORITHM = 156;
enum EVP_R_UNSUPPORTED_CIPHER = 107;
enum EVP_R_UNSUPPORTED_KEYLENGTH = 123;
enum EVP_R_UNSUPPORTED_KEY_DERIVATION_FUNCTION = 124;
enum EVP_R_UNSUPPORTED_KEY_SIZE = 108;
enum EVP_R_UNSUPPORTED_PRF = 125;
enum EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM = 118;
enum EVP_R_UNSUPPORTED_SALT_TYPE = 126;
enum EVP_R_WRONG_FINAL_BLOCK_LENGTH = 109;
enum EVP_R_WRONG_PUBLIC_KEY_TYPE = 110;
|
D
|
module polyplex.core.input;
public import polyplex.core.input.keyboard;
public import polyplex.core.input.mouse;
public import polyplex.core.input.controller;
public import polyplex.core.input.touch;
import derelict.sdl2.sdl;
import std.stdio;
enum InputType {
Controller,
Touch,
Keyboard,
Mouse
}
public class Input {
private static InputHandler handler;
public static void Init() {
handler = new InputHandler();
}
public static bool IsKeyDown(KeyCode kc) { return handler.IsKeyDown(kc);}
public static bool IsKeyDown(ModKey mk) { return handler.IsKeyDown(mk); }
public static bool IsKeyUp(KeyCode kc) { return handler.IsKeyUp(kc); }
public static bool IsKeyUp(ModKey mk) { return handler.IsKeyUp(mk); }
public static KeyState GetState(KeyCode kc) { return handler.GetState(kc); }
public static KeyState GetState(ModKey mk) { return handler.GetState(mk); }
public static void Update(SDL_Event ev) {
handler.Update(ev);
}
public static void Refresh() {
handler.Refresh();
}
}
public class InputHandler {
private Controller controller;
private Keyboard keyboard;
private Mouse mouse;
private Touch touch;
this() {
controller = new Controller();
keyboard = new Keyboard();
mouse = new Mouse();
touch = new Touch();
}
public bool IsKeyDown(KeyCode kc) { return keyboard.IsKeyDown(kc);}
public bool IsKeyDown(ModKey mk) { return keyboard.IsKeyDown(mk); }
public bool IsKeyUp(KeyCode kc) { return keyboard.IsKeyUp(kc); }
public bool IsKeyUp(ModKey mk) { return keyboard.IsKeyUp(mk); }
public KeyState GetState(KeyCode kc) { return keyboard.GetState(kc); }
public KeyState GetState(ModKey mk) { return keyboard.GetState(mk); }
public void Update(SDL_Event ev) {
if (ev.type == SDL_KEYUP || ev.type == SDL_KEYDOWN) {
keyboard.Update(ev);
}
mouse.Update();
touch.Update();
controller.Update();
}
public void Refresh() {
keyboard.Refresh();
mouse.Refresh();
touch.Refresh();
controller.Refresh();
}
}
|
D
|
/**
* International System of Units (SI) units and prefixes for use with
* $(D std.units).
*
* The definitions have been taken from the NIST Special Publication 330,
* $(WEB http://physics.nist.gov/Pubs/SP330/sp330.pdf, The International
* System of Units), 2008 edition.
*
* Todo: $(UL
* $(LI Do something about the derived unit types being expanded in the
* generated documentation.)
* )
*
* License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
* Authors: $(WEB klickverbot.at, David Nadlinger)
*/
module experimental.units.si;
import experimental.units;
/**
* The full $(XREF units, PrefixSystem) of SI prefixes.
*
* For each prefix, a helper template like $(D kilo!()) for prefixing units
* is provided (see $(XREF units, prefixTemplate)).
*/
alias SiPrefixSystem = PrefixSystem!(10, {
return [Prefix(-24, "yocto", "y"),
Prefix(-21, "zepto", "z"),
Prefix(-18, "atto", "a"),
Prefix(-15, "femto", "f"),
Prefix(-12, "pico", "p"),
Prefix(-9, "nano", "n"),
Prefix(-6, "micro", "µ"),
Prefix(-3, "milli", "m"),
Prefix(-2, "centi", "c"),
Prefix(-1, "deci", "d"),
Prefix(1, "deka", "da"),
Prefix(2, "hecto", "h"),
Prefix(3, "kilo", "k"),
Prefix(6, "mega", "M"),
Prefix(9, "giga", "G"),
Prefix(12, "tera", "T"),
Prefix(15, "peta", "P"),
Prefix(18, "exa", "E"),
Prefix(21, "zetta", "Z"),
Prefix(24, "yotta", "Y")];
});
// TODO Add binary byte units
mixin DefinePrefixSystem!(SiPrefixSystem);
/**
* SI base units.
*/
alias Ampere = BaseUnit!("Ampere", "A");
alias Candela = BaseUnit!("candela", "cd");
alias Gram = BaseUnit!("gram", "g");
alias Kelvin = BaseUnit!("Kelvin", "K");
alias Metre = BaseUnit!("metre", "m");
alias Mole = BaseUnit!("mole", "mol");
alias Second = BaseUnit!("second", "s");
alias Radian = BaseUnit!("radian", "rad");
alias Steradian = BaseUnit!("steradian", "sr");
enum ampere = Ampere.init;
enum candela = Candela.init; /// ditto
enum gram = Gram.init; /// ditto
enum kilogram = kilo!gram; /// ditto
enum kelvin = Kelvin.init; /// ditto
enum metre = Metre.init; /// ditto
alias meter = metre; /// ditto
enum mole = Mole.init; /// ditto
enum second = Second.init; /// ditto
/**
* SI supplementary units for angles.
*/
enum radian = Radian.init;
enum steradian = Steradian.init; /// ditto
import std.math : PI;
enum PI_OVER_180 = PI/180;
enum _180_OVER_PI = 180/PI;
/**
* SI scaled units for angles.
*/
// enum degree = PI_OVER_180 * radian; // TODO Use own convertible type:
enum degree = scale!(radian, PI/180, "degree");
// TODO Celsius: Use AffineUnit
// TODO Fahrenheit: Add and use LinearUnit
auto cos(Q)(Q angle)
if (Q.init.isConvertibleTo!radian) // TODO Fix and use ConvertibleTo?
{
import std.math : cos;
return cos(angle.convert!radian.toValue);
}
auto sin(Q)(Q angle)
if (Q.init.isConvertibleTo!radian)
{
import std.math : sin;
return sin(angle.convert!radian.toValue);
}
auto tan(Q)(Q angle)
if (Q.init.isConvertibleTo!radian)
{
import std.math : tan;
return tan(angle.convert!radian.toValue);
}
auto expi(Q)(Q angle)
if (Q.init.isConvertibleTo!radian)
{
import std.math : expi;
return expi(angle.convert!radian.toValue);
}
///
@safe pure nothrow @nogc unittest
{
import std.math : isClose;
assert(0.0*radian < 1.0*radian);
// TODO fix Quantitiy.opCmp to allow: assert(0.0*radian < 1.0*degree);
assert(isClose(cos(0.0*radian), 1));
assert(isClose(cos(PI*radian), -1));
assert(isClose(cos(2*PI*radian), 1));
enum d = (180*degree);
// pragma(msg, d.stringof ~ " : " ~ typeof(d).stringof);
enum r = d.convert!radian;
// pragma(msg, r.stringof ~ " : " ~ typeof(r).stringof);
// TODO enable when cast in ScaledUnit.{to|from}Base have been removed:
// TODO assert(isClose(cos(180*degree), -1));
assert(isClose(sin(0.0*radian), 0));
assert(isClose(sin(PI*radian), 0));
assert(isClose(sin(2*PI*radian), 0));
// TODO enable when cast in ScaledUnit.{to|from}Base have been removed:
// TODO assert(isClose(sin(360*degree), 0));
assert(isClose(sin(PI*radian), 0));
// assert(isClose(expi(0.0*radian)!0.toValue, 0));
}
/**
* SI derived units.
*/
enum hertz = dimensionless / second;
enum newton = kilogram * metre / pow!2(second); /// ditto
enum pascal = newton / pow!2(metre); /// ditto
enum joule = newton * metre; /// ditto
enum watt = joule / second; /// ditto
enum coulomb = ampere * second; /// ditto
enum volt = watt / ampere; /// ditto
enum farad = coulomb / volt; /// ditto
enum ohm = volt / ampere; /// ditto
enum siemens = ampere / volt; /// ditto
enum weber = volt * second; /// ditto
enum tesla = weber / pow!2(metre); /// ditto
enum henry = weber / ampere; /// ditto
enum lumen = candela * steradian; /// ditto
enum lux = lumen / pow!2(metre); /// ditto
enum becquerel = dimensionless / second; /// ditto
enum gray = joule / kilogram; /// ditto
enum sievert = joule / kilogram; /// ditto
enum katal = mole / second; /// ditto
///
@safe pure nothrow @nogc unittest
{
auto work(Quantity!newton force, Quantity!metre displacement)
{
return force * displacement;
}
Quantity!(mole, V) idealGasAmount(V)(Quantity!(pascal, V) pressure,
Quantity!(pow!3(meter), V) volume, Quantity!(kelvin, V) temperature)
{
enum R = 8.314471 * joule / (kelvin * mole);
return (pressure * volume) / (temperature * R);
}
enum forcef = 1.0f * newton;
enum force = 1.0 * newton;
// compare quantities with different value types
assert(forcef == force);
static assert(forcef == force);
enum displacement = 1.0 * metre;
enum Quantity!joule e = work(force, displacement);
static assert(e == 1.0 * joule);
enum T = (273. + 37.) * kelvin;
enum p = 1.01325e5 * pascal;
enum r = 0.5e-6 * meter;
enum V = (4.0 / 3.0) * 3.141592 * r.pow!3;
enum n = idealGasAmount!double(p, V, T); // Need to explicitly specify double due to @@BUG5801@@.
// TODO is this needed: static assert(n == 0xb.dd95ef4ddcb82f7p-59 * mole);
static assert((2 * kilogram).convert!gram == 2000 * gram);
static assert((2000 * gram).convert!kilogram == 2 * kilogram);
static assert((1000 * newton).convert!(milli!newton) == 1000000 * milli!newton);
static assert((2000000 * gram * meter / second.pow!2).convert!(kilo!newton) == 2 * kilo!newton);
static assert((1234.0 * micro!newton / milli!metre.pow!2).convert!pascal == 1234.0 * pascal);
}
|
D
|
/*=============================================================================
spiritd - Copyright (c) 2009 s.d.hammett
a D2 parser library ported from boost::spirit
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
module spiritd.ver.escapeCharv2;
import spiritd.utility.escapeCharCommon;
|
D
|
// Compiler implementation of the D programming language
// Copyright (c) 1999-2016 by Digital Mars
// All Rights Reserved
// written by Walter Bright
// http://www.digitalmars.com
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
module ddmd.dscope;
import core.stdc.stdio;
import core.stdc.string;
import ddmd.aggregate;
import ddmd.attrib;
import ddmd.dclass;
import ddmd.declaration;
import ddmd.dmodule;
import ddmd.doc;
import ddmd.dsymbol;
import ddmd.dtemplate;
import ddmd.errors;
import ddmd.func;
import ddmd.globals;
import ddmd.id;
import ddmd.identifier;
import ddmd.root.outbuffer;
import ddmd.root.rmem;
import ddmd.root.speller;
import ddmd.statement;
//version=LOGSEARCH;
extern (C++) bool mergeFieldInit(Loc loc, ref uint fieldInit, uint fi, bool mustInit)
{
if (fi != fieldInit)
{
// Have any branches returned?
bool aRet = (fi & CSXreturn) != 0;
bool bRet = (fieldInit & CSXreturn) != 0;
// Have any branches halted?
bool aHalt = (fi & CSXhalt) != 0;
bool bHalt = (fieldInit & CSXhalt) != 0;
bool ok;
if (aHalt && bHalt)
{
ok = true;
fieldInit = CSXhalt;
}
else if (!aHalt && aRet)
{
ok = !mustInit || (fi & CSXthis_ctor);
fieldInit = fieldInit;
}
else if (!bHalt && bRet)
{
ok = !mustInit || (fieldInit & CSXthis_ctor);
fieldInit = fi;
}
else if (aHalt)
{
ok = !mustInit || (fieldInit & CSXthis_ctor);
fieldInit = fieldInit;
}
else if (bHalt)
{
ok = !mustInit || (fi & CSXthis_ctor);
fieldInit = fi;
}
else
{
ok = !mustInit || !((fieldInit ^ fi) & CSXthis_ctor);
fieldInit |= fi;
}
return ok;
}
return true;
}
enum CSXthis_ctor = 0x01; // called this()
enum CSXsuper_ctor = 0x02; // called super()
enum CSXthis = 0x04; // referenced this
enum CSXsuper = 0x08; // referenced super
enum CSXlabel = 0x10; // seen a label
enum CSXreturn = 0x20; // seen a return statement
enum CSXany_ctor = 0x40; // either this() or super() was called
enum CSXhalt = 0x80; // assert(0)
// Flags that would not be inherited beyond scope nesting
enum SCOPEctor = 0x0001; // constructor type
enum SCOPEnoaccesscheck = 0x0002; // don't do access checks
enum SCOPEcondition = 0x0004; // inside static if/assert condition
enum SCOPEdebug = 0x0008; // inside debug conditional
// Flags that would be inherited beyond scope nesting
enum SCOPEconstraint = 0x0010; // inside template constraint
enum SCOPEinvariant = 0x0020; // inside invariant code
enum SCOPErequire = 0x0040; // inside in contract code
enum SCOPEensure = 0x0060; // inside out contract code
enum SCOPEcontract = 0x0060; // [mask] we're inside contract code
enum SCOPEctfe = 0x0080; // inside a ctfe-only expression
enum SCOPEcompile = 0x0100; // inside __traits(compile)
enum SCOPEfree = 0x8000; // is on free list
enum SCOPEfullinst = 0x10000; // fully instantiate templates
struct Scope
{
Scope* enclosing; // enclosing Scope
Module _module; // Root module
ScopeDsymbol scopesym; // current symbol
ScopeDsymbol sds; // if in static if, and declaring new symbols,
// sds gets the addMember()
FuncDeclaration func; // function we are in
Dsymbol parent; // parent to use
LabelStatement slabel; // enclosing labelled statement
SwitchStatement sw; // enclosing switch statement
TryFinallyStatement tf; // enclosing try finally statement
OnScopeStatement os; // enclosing scope(xxx) statement
Statement sbreak; // enclosing statement that supports "break"
Statement scontinue; // enclosing statement that supports "continue"
ForeachStatement fes; // if nested function for ForeachStatement, this is it
Scope* callsc; // used for __FUNCTION__, __PRETTY_FUNCTION__ and __MODULE__
int inunion; // we're processing members of a union
int nofree; // set if shouldn't free it
int noctor; // set if constructor calls aren't allowed
int intypeof; // in typeof(exp)
VarDeclaration lastVar; // Previous symbol used to prevent goto-skips-init
/* If minst && !tinst, it's in definitely non-speculative scope (eg. module member scope).
* If !minst && !tinst, it's in definitely speculative scope (eg. template constraint).
* If minst && tinst, it's in instantiated code scope without speculation.
* If !minst && tinst, it's in instantiated code scope with speculation.
*/
Module minst; // root module where the instantiated templates should belong to
TemplateInstance tinst; // enclosing template instance
// primitive flow analysis for constructors
uint callSuper;
// primitive flow analysis for field initializations
uint* fieldinit;
size_t fieldinit_dim;
// alignment for struct members
structalign_t structalign = STRUCTALIGN_DEFAULT;
// linkage for external functions
LINK linkage = LINKd;
// inlining strategy for functions
PINLINE inlining = PINLINEdefault;
// protection for class members
Prot protection = Prot(PROTpublic);
int explicitProtection; // set if in an explicit protection attribute
StorageClass stc; // storage class
DeprecatedDeclaration depdecl; // customized deprecation message
uint flags;
// user defined attributes
UserAttributeDeclaration userAttribDecl;
DocComment* lastdc; // documentation comment for last symbol at this scope
uint[void*] anchorCounts; // lookup duplicate anchor name count
Identifier prevAnchor; // qualified symbol name of last doc anchor
extern (C++) static __gshared Scope* freelist;
extern (C++) static Scope* alloc()
{
if (freelist)
{
Scope* s = freelist;
freelist = s.enclosing;
//printf("freelist %p\n", s);
assert(s.flags & SCOPEfree);
s.flags &= ~SCOPEfree;
return s;
}
return new Scope();
}
extern (C++) static Scope* createGlobal(Module _module)
{
Scope* sc = Scope.alloc();
*sc = Scope.init;
sc._module = _module;
sc.minst = _module;
sc.scopesym = new ScopeDsymbol();
sc.scopesym.symtab = new DsymbolTable();
// Add top level package as member of this global scope
Dsymbol m = _module;
while (m.parent)
m = m.parent;
m.addMember(null, sc.scopesym);
m.parent = null; // got changed by addMember()
// Create the module scope underneath the global scope
sc = sc.push(_module);
sc.parent = _module;
return sc;
}
extern (C++) Scope* copy()
{
Scope* sc = Scope.alloc();
*sc = this;
/* Bugzilla 11777: The copied scope should not inherit fieldinit.
*/
sc.fieldinit = null;
return sc;
}
extern (C++) Scope* push()
{
Scope* s = copy();
//printf("Scope::push(this = %p) new = %p\n", this, s);
assert(!(flags & SCOPEfree));
s.scopesym = null;
s.sds = null;
s.enclosing = &this;
debug
{
if (enclosing)
assert(!(enclosing.flags & SCOPEfree));
if (s == enclosing)
{
printf("this = %p, enclosing = %p, enclosing->enclosing = %p\n", s, &this, enclosing);
}
assert(s != enclosing);
}
s.slabel = null;
s.nofree = 0;
s.fieldinit = saveFieldInit();
s.flags = (flags & (SCOPEcontract | SCOPEdebug | SCOPEctfe | SCOPEcompile | SCOPEconstraint));
s.lastdc = null;
assert(&this != s);
return s;
}
extern (C++) Scope* push(ScopeDsymbol ss)
{
//printf("Scope::push(%s)\n", ss->toChars());
Scope* s = push();
s.scopesym = ss;
return s;
}
extern (C++) Scope* pop()
{
//printf("Scope::pop() %p nofree = %d\n", this, nofree);
Scope* enc = enclosing;
if (enclosing)
{
enclosing.callSuper |= callSuper;
if (fieldinit)
{
if (enclosing.fieldinit)
{
assert(fieldinit != enclosing.fieldinit);
foreach (i; 0 .. fieldinit_dim)
enclosing.fieldinit[i] |= fieldinit[i];
}
freeFieldinit();
}
}
if (!nofree)
{
enclosing = freelist;
freelist = &this;
flags |= SCOPEfree;
}
return enc;
}
void allocFieldinit(size_t dim)
{
fieldinit = cast(typeof(fieldinit))mem.xcalloc(typeof(*fieldinit).sizeof, dim);
fieldinit_dim = dim;
}
void freeFieldinit()
{
if (fieldinit)
mem.xfree(fieldinit);
fieldinit = null;
fieldinit_dim = 0;
}
extern (C++) Scope* startCTFE()
{
Scope* sc = this.push();
sc.flags = this.flags | SCOPEctfe;
version (none)
{
/* TODO: Currently this is not possible, because we need to
* unspeculative some types and symbols if they are necessary for the
* final executable. Consider:
*
* struct S(T) {
* string toString() const { return "instantiated"; }
* }
* enum x = S!int();
* void main() {
* // To call x.toString in runtime, compiler should unspeculative S!int.
* assert(x.toString() == "instantiated");
* }
*/
// If a template is instantiated from CT evaluated expression,
// compiler can elide its code generation.
sc.tinst = null;
sc.minst = null;
}
return sc;
}
extern (C++) Scope* endCTFE()
{
assert(flags & SCOPEctfe);
return pop();
}
extern (C++) void mergeCallSuper(Loc loc, uint cs)
{
// This does a primitive flow analysis to support the restrictions
// regarding when and how constructors can appear.
// It merges the results of two paths.
// The two paths are callSuper and cs; the result is merged into callSuper.
if (cs != callSuper)
{
// Have ALL branches called a constructor?
int aAll = (cs & (CSXthis_ctor | CSXsuper_ctor)) != 0;
int bAll = (callSuper & (CSXthis_ctor | CSXsuper_ctor)) != 0;
// Have ANY branches called a constructor?
bool aAny = (cs & CSXany_ctor) != 0;
bool bAny = (callSuper & CSXany_ctor) != 0;
// Have any branches returned?
bool aRet = (cs & CSXreturn) != 0;
bool bRet = (callSuper & CSXreturn) != 0;
// Have any branches halted?
bool aHalt = (cs & CSXhalt) != 0;
bool bHalt = (callSuper & CSXhalt) != 0;
bool ok = true;
if (aHalt && bHalt)
{
callSuper = CSXhalt;
}
else if ((!aHalt && aRet && !aAny && bAny) || (!bHalt && bRet && !bAny && aAny))
{
// If one has returned without a constructor call, there must be never
// have been ctor calls in the other.
ok = false;
}
else if (aHalt || aRet && aAll)
{
// If one branch has called a ctor and then exited, anything the
// other branch has done is OK (except returning without a
// ctor call, but we already checked that).
callSuper |= cs & (CSXany_ctor | CSXlabel);
}
else if (bHalt || bRet && bAll)
{
callSuper = cs | (callSuper & (CSXany_ctor | CSXlabel));
}
else
{
// Both branches must have called ctors, or both not.
ok = (aAll == bAll);
// If one returned without a ctor, we must remember that
// (Don't bother if we've already found an error)
if (ok && aRet && !aAny)
callSuper |= CSXreturn;
callSuper |= cs & (CSXany_ctor | CSXlabel);
}
if (!ok)
error(loc, "one path skips constructor");
}
}
extern (C++) uint* saveFieldInit()
{
uint* fi = null;
if (fieldinit) // copy
{
size_t dim = fieldinit_dim;
fi = cast(uint*)mem.xmalloc(uint.sizeof * dim);
for (size_t i = 0; i < dim; i++)
fi[i] = fieldinit[i];
}
return fi;
}
extern (C++) void mergeFieldInit(Loc loc, uint* fies)
{
if (fieldinit && fies)
{
FuncDeclaration f = func;
if (fes)
f = fes.func;
auto ad = f.isMember2();
assert(ad);
for (size_t i = 0; i < ad.fields.dim; i++)
{
VarDeclaration v = ad.fields[i];
bool mustInit = (v.storage_class & STCnodefaultctor || v.type.needsNested());
if (!.mergeFieldInit(loc, fieldinit[i], fies[i], mustInit))
{
.error(loc, "one path skips field %s", ad.fields[i].toChars());
}
}
}
}
extern (C++) Module instantiatingModule()
{
// TODO: in speculative context, returning 'module' is correct?
return minst ? minst : _module;
}
/************************************
* Perform unqualified name lookup by following the chain of scopes up
* until found.
*
* Params:
* loc = location to use for error messages
* ident = name to look up
* pscopesym = if supplied and name is found, set to scope that ident was found in
* flags = modify search based on flags
*
* Returns:
* symbol if found, null if not
*/
extern (C++) Dsymbol search(Loc loc, Identifier ident, Dsymbol* pscopesym, int flags = IgnoreNone)
{
version (LOGSEARCH)
{
printf("Scope.search(%p, '%s' flags=x%x)\n", &this, ident.toChars(), flags);
// Print scope chain
for (Scope* sc = &this; sc; sc = sc.enclosing)
{
if (!sc.scopesym)
continue;
printf("\tscope %s\n", sc.scopesym.toChars());
}
static void printMsg(string txt, Dsymbol s)
{
printf("%.*s %s.%s, kind = '%s'\n", cast(int)msg.length, msg.ptr,
s.parent ? s.parent.toChars() : "", s.toChars(), s.kind());
}
}
// This function is called only for unqualified lookup
assert(!(flags & (SearchLocalsOnly | SearchImportsOnly)));
/* If ident is "start at module scope", only look at module scope
*/
if (ident == Id.empty)
{
// Look for module scope
for (Scope* sc = &this; sc; sc = sc.enclosing)
{
assert(sc != sc.enclosing);
if (!sc.scopesym)
continue;
if (Dsymbol s = sc.scopesym.isModule())
{
//printMsg("\tfound", s);
if (pscopesym)
*pscopesym = sc.scopesym;
return s;
}
}
return null;
}
Dsymbol searchScopes(int flags)
{
for (Scope* sc = &this; sc; sc = sc.enclosing)
{
assert(sc != sc.enclosing);
if (!sc.scopesym)
continue;
//printf("\tlooking in scopesym '%s', kind = '%s', flags = x%x\n", sc.scopesym.toChars(), sc.scopesym.kind(), flags);
if (sc.scopesym.isModule())
flags |= SearchUnqualifiedModule; // tell Module.search() that SearchLocalsOnly is to be obeyed
if (Dsymbol s = sc.scopesym.search(loc, ident, flags))
{
if (!(flags & (SearchImportsOnly | IgnoreErrors)) &&
ident == Id.length && sc.scopesym.isArrayScopeSymbol() &&
sc.enclosing && sc.enclosing.search(loc, ident, null, flags))
{
warning(s.loc, "array 'length' hides other 'length' name in outer scope");
}
//printMsg("\tfound local", s);
if (pscopesym)
*pscopesym = sc.scopesym;
return s;
}
// Stop when we hit a module, but keep going if that is not just under the global scope
if (sc.scopesym.isModule() && !(sc.enclosing && !sc.enclosing.enclosing))
break;
}
return null;
}
Dsymbol sold = void;
if (global.params.bug10378 || global.params.check10378)
{
sold = searchScopes(flags | IgnoreSymbolVisibility);
if (!global.params.check10378)
return sold;
if (ident == Id.dollar) // Bugzilla 15825
return sold;
// Search both ways
}
// First look in local scopes
Dsymbol s = searchScopes(flags | SearchLocalsOnly);
version (LOGSEARCH) if (s) printMsg("-Scope.search() found local", s);
if (!s)
{
// Second look in imported modules
s = searchScopes(flags | SearchImportsOnly);
version (LOGSEARCH) if (s) printMsg("-Scope.search() found import", s);
/** Still find private symbols, so that symbols that weren't access
* checked by the compiler remain usable. Once the deprecation is over,
* this should be moved to search_correct instead.
*/
if (!s)
{
s = searchScopes(flags | SearchLocalsOnly | IgnoreSymbolVisibility);
if (!s)
s = searchScopes(flags | SearchImportsOnly | IgnoreSymbolVisibility);
if (s && !(flags & IgnoreErrors))
.deprecation(loc, "%s is not visible from module %s", s.toPrettyChars(), _module.toChars());
version (LOGSEARCH) if (s) printMsg("-Scope.search() found imported private symbol", s);
}
}
if (global.params.check10378)
{
alias snew = s;
if (sold !is snew)
deprecation10378(loc, sold, snew);
if (global.params.bug10378)
s = sold;
}
return s;
}
/* A helper function to show deprecation message for new name lookup rule.
*/
extern (C++) static void deprecation10378(Loc loc, Dsymbol sold, Dsymbol snew)
{
OutBuffer buf;
buf.writestring("local import search method found ");
if (sold)
buf.printf("%s %s", sold.kind(), sold.toPrettyChars());
else
buf.writestring("nothing");
buf.writestring(" instead of ");
if (snew)
buf.printf("%s %s", snew.kind(), snew.toPrettyChars());
else
buf.writestring("nothing");
deprecation(loc, buf.peekString());
}
extern (C++) Dsymbol search_correct(Identifier ident)
{
if (global.gag)
return null; // don't do it for speculative compiles; too time consuming
/************************************************
* Given the failed search attempt, try to find
* one with a close spelling.
*/
extern (D) void* scope_search_fp(const(char)* seed, ref int cost)
{
//printf("scope_search_fp('%s')\n", seed);
/* If not in the lexer's string table, it certainly isn't in the symbol table.
* Doing this first is a lot faster.
*/
size_t len = strlen(seed);
if (!len)
return null;
Identifier id = Identifier.lookup(seed, len);
if (!id)
return null;
Scope* sc = &this;
Module.clearCache();
Dsymbol scopesym = null;
Dsymbol s = sc.search(Loc(), id, &scopesym, IgnoreErrors);
if (s)
{
for (cost = 0; sc; sc = sc.enclosing, ++cost)
if (sc.scopesym == scopesym)
break;
if (scopesym != s.parent)
{
++cost; // got to the symbol through an import
if (s.prot().kind == PROTprivate)
return null;
}
}
return cast(void*)s;
}
return cast(Dsymbol)speller(ident.toChars(), &scope_search_fp, idchars);
}
extern (C++) Dsymbol insert(Dsymbol s)
{
if (VarDeclaration vd = s.isVarDeclaration())
{
if (lastVar)
vd.lastVar = lastVar;
lastVar = vd;
}
else if (WithScopeSymbol ss = s.isWithScopeSymbol())
{
if (VarDeclaration vd = ss.withstate.wthis)
{
if (lastVar)
vd.lastVar = lastVar;
lastVar = vd;
}
return null;
}
for (Scope* sc = &this; sc; sc = sc.enclosing)
{
//printf("\tsc = %p\n", sc);
if (sc.scopesym)
{
//printf("\t\tsc->scopesym = %p\n", sc->scopesym);
if (!sc.scopesym.symtab)
sc.scopesym.symtab = new DsymbolTable();
return sc.scopesym.symtabInsert(s);
}
}
assert(0);
}
/********************************************
* Search enclosing scopes for ClassDeclaration.
*/
extern (C++) ClassDeclaration getClassScope()
{
for (Scope* sc = &this; sc; sc = sc.enclosing)
{
if (!sc.scopesym)
continue;
ClassDeclaration cd = sc.scopesym.isClassDeclaration();
if (cd)
return cd;
}
return null;
}
/********************************************
* Search enclosing scopes for ClassDeclaration.
*/
extern (C++) AggregateDeclaration getStructClassScope()
{
for (Scope* sc = &this; sc; sc = sc.enclosing)
{
if (!sc.scopesym)
continue;
AggregateDeclaration ad = sc.scopesym.isClassDeclaration();
if (ad)
return ad;
ad = sc.scopesym.isStructDeclaration();
if (ad)
return ad;
}
return null;
}
/*******************************************
* For TemplateDeclarations, we need to remember the Scope
* where it was declared. So mark the Scope as not
* to be free'd.
*/
extern (C++) void setNoFree()
{
//int i = 0;
//printf("Scope::setNoFree(this = %p)\n", this);
for (Scope* sc = &this; sc; sc = sc.enclosing)
{
//printf("\tsc = %p\n", sc);
sc.nofree = 1;
assert(!(flags & SCOPEfree));
//assert(sc != sc->enclosing);
//assert(!sc->enclosing || sc != sc->enclosing->enclosing);
//if (++i == 10)
// assert(0);
}
}
extern (D) this(ref Scope sc)
{
this._module = sc._module;
this.scopesym = sc.scopesym;
this.sds = sc.sds;
this.enclosing = sc.enclosing;
this.parent = sc.parent;
this.sw = sc.sw;
this.tf = sc.tf;
this.os = sc.os;
this.tinst = sc.tinst;
this.minst = sc.minst;
this.sbreak = sc.sbreak;
this.scontinue = sc.scontinue;
this.fes = sc.fes;
this.callsc = sc.callsc;
this.structalign = sc.structalign;
this.func = sc.func;
this.slabel = sc.slabel;
this.linkage = sc.linkage;
this.inlining = sc.inlining;
this.protection = sc.protection;
this.explicitProtection = sc.explicitProtection;
this.stc = sc.stc;
this.depdecl = sc.depdecl;
this.inunion = sc.inunion;
this.nofree = sc.nofree;
this.noctor = sc.noctor;
this.intypeof = sc.intypeof;
this.lastVar = sc.lastVar;
this.callSuper = sc.callSuper;
this.fieldinit = sc.fieldinit;
this.fieldinit_dim = sc.fieldinit_dim;
this.flags = sc.flags;
this.lastdc = sc.lastdc;
this.anchorCounts = sc.anchorCounts;
this.prevAnchor = sc.prevAnchor;
this.userAttribDecl = sc.userAttribDecl;
}
}
|
D
|
/Users/haruna/Documents/iOSdev/Tumblr_1/Build/Intermediates/Pods.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/ParameterEncoding.o : /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/MultipartFormData.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Timeline.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Alamofire.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Response.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/TaskDelegate.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/SessionDelegate.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/ParameterEncoding.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Validation.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/ResponseSerialization.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/SessionManager.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/NetworkReachabilityManager.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/AFError.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Notifications.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Result.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Request.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/ServerTrustPolicy.swift /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/CoreImage.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/QuartzCore.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Metal.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Swift.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/UIKit.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Target\ Support\ Files/Alamofire/Alamofire-umbrella.h /Users/haruna/Documents/iOSdev/Tumblr_1/Build/Intermediates/Pods.build/Debug-iphonesimulator/Alamofire.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/haruna/Documents/iOSdev/Tumblr_1/Build/Intermediates/Pods.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/ParameterEncoding~partial.swiftmodule : /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/MultipartFormData.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Timeline.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Alamofire.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Response.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/TaskDelegate.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/SessionDelegate.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/ParameterEncoding.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Validation.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/ResponseSerialization.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/SessionManager.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/NetworkReachabilityManager.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/AFError.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Notifications.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Result.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Request.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/ServerTrustPolicy.swift /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/CoreImage.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/QuartzCore.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Metal.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Swift.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/UIKit.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Target\ Support\ Files/Alamofire/Alamofire-umbrella.h /Users/haruna/Documents/iOSdev/Tumblr_1/Build/Intermediates/Pods.build/Debug-iphonesimulator/Alamofire.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/haruna/Documents/iOSdev/Tumblr_1/Build/Intermediates/Pods.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/ParameterEncoding~partial.swiftdoc : /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/MultipartFormData.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Timeline.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Alamofire.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Response.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/TaskDelegate.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/SessionDelegate.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/ParameterEncoding.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Validation.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/ResponseSerialization.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/SessionManager.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/NetworkReachabilityManager.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/AFError.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Notifications.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Result.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/Request.swift /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Alamofire/Source/ServerTrustPolicy.swift /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/CoreImage.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/QuartzCore.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Metal.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Swift.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/UIKit.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/haruna/Documents/iOSdev/Tumblr_1/Pods/Target\ Support\ Files/Alamofire/Alamofire-umbrella.h /Users/haruna/Documents/iOSdev/Tumblr_1/Build/Intermediates/Pods.build/Debug-iphonesimulator/Alamofire.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
|
D
|
the stage of a theater
the boarding that surrounds an ice hockey rink
a committee having supervisory powers
a stout length of sawn timber
a flat piece of material designed for a special purpose
food or meals in general
a vertical surface on which information can be displayed to public view
a table at which meals are served
electrical device consisting of a flat insulated surface that contains switches and dials and meters for controlling other electrical devices
a printed circuit that can be inserted into expansion slots in a computer to increase the computer's capabilities
a flat portable surface (usually rectangular) designed for board games
get on board of (trains, buses, ships, aircraft, etc.)
live and take one's meals at or in
lodge and take meals (at)
provide food and lodging (for
|
D
|
/*
Copyright (c) 2017-2019 Timur Gafarov
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
module dagon.resource.obj;
import std.stdio;
import std.string;
import std.format;
//import std.regex;
import dlib.core.memory;
import dlib.core.ownership;
import dlib.core.stream;
import dlib.math.vector;
import dlib.geometry.triangle;
import dlib.filesystem.filesystem;
import dlib.filesystem.stdfs;
import dlib.container.array;
import dagon.core.bindings;
import dagon.resource.asset;
import dagon.graphics.mesh;
struct ObjFace
{
uint[3] v;
uint[3] t;
uint[3] n;
}
class OBJAsset: Asset
{
Mesh mesh;
this(Owner o)
{
super(o);
mesh = New!Mesh(this);
}
~this()
{
release();
}
override bool loadThreadSafePart(string filename, InputStream istrm, ReadOnlyFileSystem fs, AssetManager mngr)
{
uint numVerts = 0;
uint numNormals = 0;
uint numTexcoords = 0;
uint numFaces = 0;
string fileStr = readText(istrm);
foreach(line; lineSplitter(fileStr))
{
if (line.startsWith("v "))
numVerts++;
else if (line.startsWith("vn "))
numNormals++;
else if (line.startsWith("vt "))
numTexcoords++;
else if (line.startsWith("f "))
numFaces++;
}
Vector3f[] tmpVertices;
Vector3f[] tmpNormals;
Vector2f[] tmpTexcoords;
ObjFace[] tmpFaces;
bool needGenNormals = false;
if (!numVerts)
writeln("Warning: OBJ file \"", filename, "\" has no vertices");
if (!numNormals)
{
writeln("Warning: OBJ file \"", filename, "\" has no normals (they will be generated)");
numNormals = numVerts;
needGenNormals = true;
}
if (!numTexcoords)
{
writeln("Warning: OBJ file \"", filename, "\" has no texcoords");
numTexcoords = numVerts;
}
if (numVerts)
tmpVertices = New!(Vector3f[])(numVerts);
if (numNormals)
tmpNormals = New!(Vector3f[])(numNormals);
if (numTexcoords)
tmpTexcoords = New!(Vector2f[])(numTexcoords);
if (numFaces)
tmpFaces = New!(ObjFace[])(numFaces);
tmpVertices[] = Vector3f(0, 0, 0);
tmpNormals[] = Vector3f(0, 0, 0);
tmpTexcoords[] = Vector2f(0, 0);
float x, y, z;
int v1, v2, v3, v4;
int t1, t2, t3, t4;
int n1, n2, n3, n4;
uint vi = 0;
uint ni = 0;
uint ti = 0;
uint fi = 0;
bool warnAboutQuads = false;
foreach(line; lineSplitter(fileStr))
{
if (line.startsWith("v "))
{
if (formattedRead(line, "v %s %s %s", &x, &y, &z))
{
tmpVertices[vi] = Vector3f(x, y, z);
vi++;
}
}
else if (line.startsWith("vn"))
{
if (formattedRead(line, "vn %s %s %s", &x, &y, &z))
{
tmpNormals[ni] = Vector3f(x, y, z);
ni++;
}
}
else if (line.startsWith("vt"))
{
if (formattedRead(line, "vt %s %s", &x, &y))
{
tmpTexcoords[ti] = Vector2f(x, -y);
ti++;
}
}
else if (line.startsWith("vp"))
{
}
else if (line.startsWith("f"))
{
char[256] tmpStr;
tmpStr[0..line.length] = line[];
tmpStr[line.length] = 0;
if (sscanf(tmpStr.ptr, "f %u/%u/%u %u/%u/%u %u/%u/%u %u/%u/%u", &v1, &t1, &n1, &v2, &t2, &n2, &v3, &t3, &n3, &v4, &t4, &n4) == 12)
{
tmpFaces[fi].v[0] = v1-1;
tmpFaces[fi].v[1] = v2-1;
tmpFaces[fi].v[2] = v3-1;
tmpFaces[fi].t[0] = t1-1;
tmpFaces[fi].t[1] = t2-1;
tmpFaces[fi].t[2] = t3-1;
tmpFaces[fi].n[0] = n1-1;
tmpFaces[fi].n[1] = n2-1;
tmpFaces[fi].n[2] = n3-1;
fi++;
warnAboutQuads = true;
}
if (sscanf(tmpStr.ptr, "f %u/%u/%u %u/%u/%u %u/%u/%u", &v1, &t1, &n1, &v2, &t2, &n2, &v3, &t3, &n3) == 9)
{
tmpFaces[fi].v[0] = v1-1;
tmpFaces[fi].v[1] = v2-1;
tmpFaces[fi].v[2] = v3-1;
tmpFaces[fi].t[0] = t1-1;
tmpFaces[fi].t[1] = t2-1;
tmpFaces[fi].t[2] = t3-1;
tmpFaces[fi].n[0] = n1-1;
tmpFaces[fi].n[1] = n2-1;
tmpFaces[fi].n[2] = n3-1;
fi++;
}
else if (sscanf(tmpStr.ptr, "f %u//%u %u//%u %u//%u %u//%u", &v1, &n1, &v2, &n2, &v3, &n3, &v4, &n4) == 8)
{
tmpFaces[fi].v[0] = v1-1;
tmpFaces[fi].v[1] = v2-1;
tmpFaces[fi].v[2] = v3-1;
tmpFaces[fi].n[0] = n1-1;
tmpFaces[fi].n[1] = n2-1;
tmpFaces[fi].n[2] = n3-1;
fi++;
warnAboutQuads = true;
}
else if (sscanf(tmpStr.ptr, "f %u/%u %u/%u %u/%u", &v1, &t1, &v2, &t2, &v3, &t3) == 6)
{
tmpFaces[fi].v[0] = v1-1;
tmpFaces[fi].v[1] = v2-1;
tmpFaces[fi].v[2] = v3-1;
tmpFaces[fi].t[0] = t1-1;
tmpFaces[fi].t[1] = t2-1;
tmpFaces[fi].t[2] = t3-1;
fi++;
}
else if (sscanf(tmpStr.ptr, "f %u//%u %u//%u %u//%u", &v1, &n1, &v2, &n2, &v3, &n3) == 6)
{
tmpFaces[fi].v[0] = v1-1;
tmpFaces[fi].v[1] = v2-1;
tmpFaces[fi].v[2] = v3-1;
tmpFaces[fi].n[0] = n1-1;
tmpFaces[fi].n[1] = n2-1;
tmpFaces[fi].n[2] = n3-1;
fi++;
}
else if (sscanf(tmpStr.ptr, "f %u %u %u %u", &v1, &v2, &v3, &v4) == 4)
{
tmpFaces[fi].v[0] = v1-1;
tmpFaces[fi].v[1] = v2-1;
tmpFaces[fi].v[2] = v3-1;
fi++;
warnAboutQuads = true;
}
else if (sscanf(tmpStr.ptr, "f %u %u %u", &v1, &v2, &v3) == 3)
{
tmpFaces[fi].v[0] = v1-1;
tmpFaces[fi].v[1] = v2-1;
tmpFaces[fi].v[2] = v3-1;
fi++;
}
else
assert(0);
}
}
Delete(fileStr);
if (warnAboutQuads)
writeln("Warning: OBJ file \"", filename, "\" includes quads, but Dagon supports only triangles");
mesh.indices = New!(uint[3][])(tmpFaces.length);
uint numUniqueVerts = cast(uint)mesh.indices.length * 3;
mesh.vertices = New!(Vector3f[])(numUniqueVerts);
mesh.normals = New!(Vector3f[])(numUniqueVerts);
mesh.texcoords = New!(Vector2f[])(numUniqueVerts);
uint index = 0;
foreach(i, ref ObjFace f; tmpFaces)
{
if (numVerts)
{
mesh.vertices[index] = tmpVertices[f.v[0]];
mesh.vertices[index+1] = tmpVertices[f.v[1]];
mesh.vertices[index+2] = tmpVertices[f.v[2]];
}
else
{
mesh.vertices[index] = Vector3f(0, 0, 0);
mesh.vertices[index+1] = Vector3f(0, 0, 0);
mesh.vertices[index+2] = Vector3f(0, 0, 0);
}
if (numNormals)
{
mesh.normals[index] = tmpNormals[f.n[0]];
mesh.normals[index+1] = tmpNormals[f.n[1]];
mesh.normals[index+2] = tmpNormals[f.n[2]];
}
else
{
mesh.normals[index] = Vector3f(0, 0, 0);
mesh.normals[index+1] = Vector3f(0, 0, 0);
mesh.normals[index+2] = Vector3f(0, 0, 0);
}
if (numTexcoords)
{
mesh.texcoords[index] = tmpTexcoords[f.t[0]];
mesh.texcoords[index+1] = tmpTexcoords[f.t[1]];
mesh.texcoords[index+2] = tmpTexcoords[f.t[2]];
}
else
{
mesh.texcoords[index] = Vector2f(0, 0);
mesh.texcoords[index+1] = Vector2f(0, 0);
mesh.texcoords[index+2] = Vector2f(0, 0);
}
mesh.indices[i][0] = index;
mesh.indices[i][1] = index + 1;
mesh.indices[i][2] = index + 2;
index += 3;
}
if (needGenNormals)
mesh.generateNormals();
if (tmpVertices.length)
Delete(tmpVertices);
if (tmpNormals.length)
Delete(tmpNormals);
if (tmpTexcoords.length)
Delete(tmpTexcoords);
if (tmpFaces.length)
Delete(tmpFaces);
mesh.calcBoundingBox();
mesh.dataReady = true;
return true;
}
override bool loadThreadUnsafePart()
{
mesh.prepareVAO();
return true;
}
override void release()
{
clearOwnedObjects();
}
}
|
D
|
/* REQUIRED_ARGS: -betterC
*/
// https://issues.dlang.org/show_bug.cgi?id=19268
mixin(`void foo(){}`.idup);
|
D
|
/**
Whirlpool hashing algorithm implementation. This module conforms to the APIs defined in std.digest.
Based on the original Whirlpool implementation by Paulo S.L.M. Barreto and Vincent Rijmen.
*/
module nxt.digestx.whirlpool;
public import std.digest;
import std.range;
/**
* Template API Whirlpool implementation.
*/
struct Whirlpool
{
/// Initializes the digest calculation.
void start() @safe pure nothrow @nogc
{
_lenBuf = 0;
_bufferPos = 0;
_hash[] = 0;
_tailBlock = false;
_bitLength[] = 0;
}
/// Feed the digest with data.
void put(scope const(ubyte)[] data...) @trusted pure nothrow @nogc
{
bufLength(data.length);
while (true)
{
immutable cap = _buffer.length - _bufferPos;
if (cap <= data.length)
{
_buffer[_bufferPos .. $] = data[0 .. cap];
processBuffer();
_bufferPos = 0;
data = data[cap .. $];
}
else
{
_buffer[_bufferPos .. _bufferPos + data.length] = data;
_bufferPos += data.length;
data = null;
break;
}
}
}
void put(R)(R r) if (isInputRange!R && hasLength!R)
{
bufLength(r.length);
foreach (immutable i; r)
{
_buffer[_bufferPos] = i;
_bufferPos++;
if (_bufferPos == _buffer.length)
{
processBuffer();
_bufferPos = 0;
}
}
}
/// Returns the Whirlpool hash. This also calls start to reset the internal state.
ubyte[64] finish() @trusted pure nothrow @nogc
{
// append a '1'-bit
// As the buffer is byte-wise in this implementation, _buffer[_bufferPos] is not used yet.
_buffer[_bufferPos] = 0x80;
_bufferPos++;
if (_bufferPos > 32)
{
_buffer[_bufferPos .. $] = 0;
processBuffer();
_bufferPos = 0;
}
if (_bufferPos < 32)
_buffer[_bufferPos .. 32] = 0;
if (_lenBuf != 0)
addLength(_lenBuf);
_buffer[32 .. $] = _bitLength;
processBuffer();
ubyte[64] digest = void;
for (int i = 0, j = 0; i < 8; i++, j += 8)
{
immutable h = _hash[i];
digest[j] = cast(ubyte)(h >> 56);
digest[j + 1] = cast(ubyte)(h >> 48);
digest[j + 2] = cast(ubyte)(h >> 40);
digest[j + 3] = cast(ubyte)(h >> 32);
digest[j + 4] = cast(ubyte)(h >> 24);
digest[j + 5] = cast(ubyte)(h >> 16);
digest[j + 6] = cast(ubyte)(h >> 8);
digest[j + 7] = cast(ubyte) h;
}
start();
return digest;
}
private:
// buffers sum of data length and add into _bitLength when necessary,
// to reduce bignum operation.
ulong _lenBuf = void;
void bufLength(ulong bytes) @safe pure nothrow @nogc
{
ulong sum = _lenBuf + bytes;
if (sum < _lenBuf || sum < bytes)
{
addLength(_lenBuf);
_lenBuf = bytes;
}
else
{
_lenBuf = sum;
}
}
ubyte[32] _bitLength = void;
void addLength(ulong bytes) @trusted pure nothrow @nogc
{
uint carry = _bitLength[31] + ((bytes << 3) & 0xFF);
_bitLength[31] = cast(ubyte) carry;
carry >>= 8;
bytes >>= 5;
for (int i = 30; i >= 0; i--)
{
carry += _bitLength[i] + (bytes & 0xFF);
_bitLength[i] = cast(ubyte) carry;
carry >>= 8;
bytes >>= 8;
}
}
ubyte[64] _buffer = void;
size_t _bufferPos = void;
ulong[8] _hash = void;
bool _tailBlock;
void processBuffer() @trusted pure nothrow @nogc
{
ulong[8] block = void;
// map the buffer to a block
for (int i = 0, j = 0; i < 8; i++, j += 8)
{
block[i] = (cast(ulong) _buffer[j] << 56) ^ (cast(ulong) _buffer[j + 1] << 48) ^ (
cast(ulong) _buffer[j + 2] << 40) ^ (cast(ulong) _buffer[j + 3] << 32) ^ (
cast(ulong) _buffer[j + 4] << 24) ^ (cast(ulong) _buffer[j + 5] << 16) ^ (
cast(ulong) _buffer[j + 6] << 8) ^ (cast(ulong) _buffer[j + 7]);
}
// compute and apply K^0 to the cipher state
ulong[8] state = void;
state[] = block[] ^ _hash[];
// iterate over all rounds
if (_tailBlock) // not the first block
{
ulong[8] K = _hash;
foreach (immutable rcr; rc)
{
ulong[8] L = void;
// compute K^r from K^{r-1}
mixin(genTransform("L", "K"));
L[0] ^= rcr;
K = L;
// apply the r-th round transformation
mixin(genTransform("L", "state"));
state[] = L[] ^ K[];
}
}
else // use precompiled K[] for first block
{
foreach (immutable k; pcK)
{
ulong[8] L = void;
mixin(genTransform("L", "state"));
state[] = L[] ^ k[];
}
_tailBlock = true;
}
// apply the Miyaguchi-Preneel compression function:
_hash[] ^= state[] ^ block[];
}
}
/// Convenience alias for digest function in std.digest using the Whirlpool implementation.
auto whirlpoolOf(T...)(T data)
{
return digest!(Whirlpool, T)(data);
}
/// OOP API for Whirlpool
alias WhirlpoolDigest = WrapperDigest!Whirlpool;
///
unittest
{
import nxt.digestx.whirlpool;
ubyte[1024] data;
Whirlpool wp;
wp.start();
wp.put(data[]);
wp.start();
wp.put(data[]);
ubyte[64] hash = wp.finish();
// Template API
ubyte[64] hash2 = whirlpoolOf("abc");
assert(digest!Whirlpool("abc") == hash2);
assert(hexDigest!Whirlpool("abc") == toHexString(hash2));
// OOP API
Digest wpDigest = new WhirlpoolDigest;
ubyte[] hash3 = wpDigest.digest("abc");
assert(toHexString(hash3) == "4E2448A4C6F486BB16B6562C73B4020BF3043E3A731BCE721AE1B303D97E6D4C"
~ "7181EEBDB6C57E277D0E34957114CBD6C797FC9D95D8B582D225292076D4EEF5");
}
@safe pure nothrow /*@nogc*/ unittest
{
static assert(isDigest!Whirlpool);
assert(digest!Whirlpool("The quick brown fox jumps over the lazy dog")
== hexString!"B97DE512E91E3828B40D2B0FDCE9CEB3C4A71F9BEA8D88E75C4FA854DF36725F"
~ hexString!"D2B52EB6544EDCACD6F8BEDDFEA403CB55AE31F03AD62A5EF54E42EE82C3FB35");
// ISO test vectors
assert(digest!Whirlpool("") == hexString!"19FA61D75522A4669B44E39C1D2E1726C530232130D407F89AFEE0964997F7A7"
~ hexString!"3E83BE698B288FEBCF88E3E03C4F0757EA8964E59B63D93708B138CC42A66EB3");
assert(digest!Whirlpool("a") == hexString!"8ACA2602792AEC6F11A67206531FB7D7F0DFF59413145E6973C45001D0087B42"
~ hexString!"D11BC645413AEFF63A42391A39145A591A92200D560195E53B478584FDAE231A");
assert(digest!Whirlpool("abc") == hexString!"4E2448A4C6F486BB16B6562C73B4020BF3043E3A731BCE721AE1B303D97E6D4C"
~ hexString!"7181EEBDB6C57E277D0E34957114CBD6C797FC9D95D8B582D225292076D4EEF5");
assert(digest!Whirlpool("message digest") == hexString!"378C84A4126E2DC6E56DCC7458377AAC838D00032230F53CE1F5700C0FFB4D3B"
~ hexString!"8421557659EF55C106B4B52AC5A4AAA692ED920052838F3362E86DBD37A8903E");
assert(digest!Whirlpool("abcdefghijklmnopqrstuvwxyz")
== hexString!"F1D754662636FFE92C82EBB9212A484A8D38631EAD4238F5442EE13B8054E41B"
~ hexString!"08BF2A9251C30B6A0B8AAE86177AB4A6F68F673E7207865D5D9819A3DBA4EB3B");
assert(digest!Whirlpool("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
== hexString!"DC37E008CF9EE69BF11F00ED9ABA26901DD7C28CDEC066CC6AF42E40F82F3A1E"
~ hexString!"08EBA26629129D8FB7CB57211B9281A65517CC879D7B962142C65F5A7AF01467");
assert(digest!Whirlpool("1234567890123456789012345678901234567890" ~ "1234567890123456789012345678901234567890")
== hexString!"466EF18BABB0154D25B9D38A6414F5C08784372BCCB204D6549C4AFADB601429"
~ hexString!"4D5BD8DF2A6C44E538CD047B2681A51A2C60481E88C5A20B2C2A80CF3A9A083B");
assert(digest!Whirlpool("abcdbcdecdefdefgefghfghighijhijk")
== hexString!"2A987EA40F917061F5D6F0A0E4644F488A7A5A52DEEE656207C562F988E95C69"
~ hexString!"16BDC8031BC5BE1B7B947639FE050B56939BAAA0ADFF9AE6745B7B181C3BE3FD");
}
pure nothrow /*@nogc*/ unittest
{
import std.range : repeat;
assert(digest!Whirlpool(repeat('a',
10 ^^ 6)) == hexString!"0C99005BEB57EFF50A7CF005560DDF5D29057FD86B20BFD62DECA0F1CCEA4AF5"
~ hexString!"1FC15490EDDC47AF32BB2B66C34FF9AD8C6008AD677F77126953B226E4ED8B01");
}
@trusted pure nothrow /*@nogc*/ unittest
{
Whirlpool wp;
wp.put(cast(ubyte[])("abc"));
wp.start();
wp.put(cast(ubyte[])("abc"));
assert(wp.finish() == hexString!"4E2448A4C6F486BB16B6562C73B4020BF3043E3A731BCE721AE1B303D97E6D4C"
~ hexString!"7181EEBDB6C57E277D0E34957114CBD6C797FC9D95D8B582D225292076D4EEF5");
}
private:
string genTransform(string assignTo, string from)
{
import std.string : format;
string ret;
foreach (i; 0 .. 8)
{
ret ~= format("%s[%s]=", assignTo, i);
for (int t = 0, s = 56; t < 8; t++, s -= 8)
{
ret ~= format("C[%s][(%s[%s] >> %s) & 0xFF]", t, from, (i - t) & 7, s);
if (t != 7)
ret ~= "^";
}
ret ~= ";\n";
}
return ret;
}
// number of rounds
enum int numRounds = 10;
// circulant table
immutable ulong[256][8] C = [
[
0x18186018c07830d8UL, 0x23238c2305af4626UL, 0xc6c63fc67ef991b8UL,
0xe8e887e8136fcdfbUL, 0x878726874ca113cbUL, 0xb8b8dab8a9626d11UL,
0x0101040108050209UL, 0x4f4f214f426e9e0dUL, 0x3636d836adee6c9bUL,
0xa6a6a2a6590451ffUL,
0xd2d26fd2debdb90cUL, 0xf5f5f3f5fb06f70eUL, 0x7979f979ef80f296UL,
0x6f6fa16f5fcede30UL, 0x91917e91fcef3f6dUL, 0x52525552aa07a4f8UL,
0x60609d6027fdc047UL, 0xbcbccabc89766535UL, 0x9b9b569baccd2b37UL,
0x8e8e028e048c018aUL, 0xa3a3b6a371155bd2UL, 0x0c0c300c603c186cUL,
0x7b7bf17bff8af684UL,
0x3535d435b5e16a80UL,
0x1d1d741de8693af5UL, 0xe0e0a7e05347ddb3UL, 0xd7d77bd7f6acb321UL,
0xc2c22fc25eed999cUL, 0x2e2eb82e6d965c43UL, 0x4b4b314b627a9629UL,
0xfefedffea321e15dUL, 0x575741578216aed5UL, 0x15155415a8412abdUL,
0x7777c1779fb6eee8UL, 0x3737dc37a5eb6e92UL, 0xe5e5b3e57b56d79eUL,
0x9f9f469f8cd92313UL,
0xf0f0e7f0d317fd23UL,
0x4a4a354a6a7f9420UL, 0xdada4fda9e95a944UL, 0x58587d58fa25b0a2UL,
0xc9c903c906ca8fcfUL, 0x2929a429558d527cUL, 0x0a0a280a5022145aUL,
0xb1b1feb1e14f7f50UL, 0xa0a0baa0691a5dc9UL, 0x6b6bb16b7fdad614UL,
0x85852e855cab17d9UL, 0xbdbdcebd8173673cUL, 0x5d5d695dd234ba8fUL,
0x1010401080502090UL,
0xf4f4f7f4f303f507UL,
0xcbcb0bcb16c08bddUL, 0x3e3ef83eedc67cd3UL, 0x0505140528110a2dUL,
0x676781671fe6ce78UL, 0xe4e4b7e47353d597UL, 0x27279c2725bb4e02UL,
0x4141194132588273UL, 0x8b8b168b2c9d0ba7UL, 0xa7a7a6a7510153f6UL,
0x7d7de97dcf94fab2UL, 0x95956e95dcfb3749UL, 0xd8d847d88e9fad56UL,
0xfbfbcbfb8b30eb70UL,
0xeeee9fee2371c1cdUL,
0x7c7ced7cc791f8bbUL, 0x6666856617e3cc71UL, 0xdddd53dda68ea77bUL,
0x17175c17b84b2eafUL, 0x4747014702468e45UL, 0x9e9e429e84dc211aUL,
0xcaca0fca1ec589d4UL, 0x2d2db42d75995a58UL, 0xbfbfc6bf9179632eUL,
0x07071c07381b0e3fUL, 0xadad8ead012347acUL, 0x5a5a755aea2fb4b0UL,
0x838336836cb51befUL,
0x3333cc3385ff66b6UL,
0x636391633ff2c65cUL, 0x02020802100a0412UL, 0xaaaa92aa39384993UL,
0x7171d971afa8e2deUL, 0xc8c807c80ecf8dc6UL, 0x19196419c87d32d1UL,
0x494939497270923bUL, 0xd9d943d9869aaf5fUL, 0xf2f2eff2c31df931UL,
0xe3e3abe34b48dba8UL, 0x5b5b715be22ab6b9UL, 0x88881a8834920dbcUL,
0x9a9a529aa4c8293eUL,
0x262698262dbe4c0bUL,
0x3232c8328dfa64bfUL, 0xb0b0fab0e94a7d59UL, 0xe9e983e91b6acff2UL,
0x0f0f3c0f78331e77UL, 0xd5d573d5e6a6b733UL, 0x80803a8074ba1df4UL,
0xbebec2be997c6127UL, 0xcdcd13cd26de87ebUL, 0x3434d034bde46889UL,
0x48483d487a759032UL, 0xffffdbffab24e354UL, 0x7a7af57af78ff48dUL,
0x90907a90f4ea3d64UL,
0x5f5f615fc23ebe9dUL,
0x202080201da0403dUL, 0x6868bd6867d5d00fUL, 0x1a1a681ad07234caUL,
0xaeae82ae192c41b7UL, 0xb4b4eab4c95e757dUL, 0x54544d549a19a8ceUL,
0x93937693ece53b7fUL, 0x222288220daa442fUL, 0x64648d6407e9c863UL,
0xf1f1e3f1db12ff2aUL, 0x7373d173bfa2e6ccUL, 0x12124812905a2482UL,
0x40401d403a5d807aUL,
0x0808200840281048UL,
0xc3c32bc356e89b95UL, 0xecec97ec337bc5dfUL, 0xdbdb4bdb9690ab4dUL,
0xa1a1bea1611f5fc0UL, 0x8d8d0e8d1c830791UL, 0x3d3df43df5c97ac8UL,
0x97976697ccf1335bUL, 0x0000000000000000UL, 0xcfcf1bcf36d483f9UL,
0x2b2bac2b4587566eUL, 0x7676c57697b3ece1UL, 0x8282328264b019e6UL,
0xd6d67fd6fea9b128UL,
0x1b1b6c1bd87736c3UL,
0xb5b5eeb5c15b7774UL, 0xafaf86af112943beUL, 0x6a6ab56a77dfd41dUL,
0x50505d50ba0da0eaUL, 0x45450945124c8a57UL, 0xf3f3ebf3cb18fb38UL,
0x3030c0309df060adUL, 0xefef9bef2b74c3c4UL, 0x3f3ffc3fe5c37edaUL,
0x55554955921caac7UL, 0xa2a2b2a2791059dbUL, 0xeaea8fea0365c9e9UL,
0x656589650fecca6aUL,
0xbabad2bab9686903UL,
0x2f2fbc2f65935e4aUL, 0xc0c027c04ee79d8eUL, 0xdede5fdebe81a160UL,
0x1c1c701ce06c38fcUL, 0xfdfdd3fdbb2ee746UL, 0x4d4d294d52649a1fUL,
0x92927292e4e03976UL, 0x7575c9758fbceafaUL, 0x06061806301e0c36UL,
0x8a8a128a249809aeUL, 0xb2b2f2b2f940794bUL, 0xe6e6bfe66359d185UL,
0x0e0e380e70361c7eUL,
0x1f1f7c1ff8633ee7UL,
0x6262956237f7c455UL, 0xd4d477d4eea3b53aUL, 0xa8a89aa829324d81UL,
0x96966296c4f43152UL, 0xf9f9c3f99b3aef62UL, 0xc5c533c566f697a3UL,
0x2525942535b14a10UL, 0x59597959f220b2abUL, 0x84842a8454ae15d0UL,
0x7272d572b7a7e4c5UL, 0x3939e439d5dd72ecUL, 0x4c4c2d4c5a619816UL,
0x5e5e655eca3bbc94UL,
0x7878fd78e785f09fUL,
0x3838e038ddd870e5UL, 0x8c8c0a8c14860598UL, 0xd1d163d1c6b2bf17UL,
0xa5a5aea5410b57e4UL, 0xe2e2afe2434dd9a1UL, 0x616199612ff8c24eUL,
0xb3b3f6b3f1457b42UL, 0x2121842115a54234UL, 0x9c9c4a9c94d62508UL,
0x1e1e781ef0663ceeUL, 0x4343114322528661UL, 0xc7c73bc776fc93b1UL,
0xfcfcd7fcb32be54fUL,
0x0404100420140824UL,
0x51515951b208a2e3UL, 0x99995e99bcc72f25UL, 0x6d6da96d4fc4da22UL,
0x0d0d340d68391a65UL, 0xfafacffa8335e979UL, 0xdfdf5bdfb684a369UL,
0x7e7ee57ed79bfca9UL, 0x242490243db44819UL, 0x3b3bec3bc5d776feUL,
0xabab96ab313d4b9aUL, 0xcece1fce3ed181f0UL, 0x1111441188552299UL,
0x8f8f068f0c890383UL,
0x4e4e254e4a6b9c04UL,
0xb7b7e6b7d1517366UL, 0xebeb8beb0b60cbe0UL, 0x3c3cf03cfdcc78c1UL,
0x81813e817cbf1ffdUL, 0x94946a94d4fe3540UL, 0xf7f7fbf7eb0cf31cUL,
0xb9b9deb9a1676f18UL, 0x13134c13985f268bUL, 0x2c2cb02c7d9c5851UL,
0xd3d36bd3d6b8bb05UL, 0xe7e7bbe76b5cd38cUL, 0x6e6ea56e57cbdc39UL,
0xc4c437c46ef395aaUL,
0x03030c03180f061bUL,
0x565645568a13acdcUL, 0x44440d441a49885eUL, 0x7f7fe17fdf9efea0UL,
0xa9a99ea921374f88UL, 0x2a2aa82a4d825467UL, 0xbbbbd6bbb16d6b0aUL,
0xc1c123c146e29f87UL, 0x53535153a202a6f1UL, 0xdcdc57dcae8ba572UL,
0x0b0b2c0b58271653UL, 0x9d9d4e9d9cd32701UL, 0x6c6cad6c47c1d82bUL,
0x3131c43195f562a4UL,
0x7474cd7487b9e8f3UL,
0xf6f6fff6e309f115UL, 0x464605460a438c4cUL, 0xacac8aac092645a5UL,
0x89891e893c970fb5UL, 0x14145014a04428b4UL, 0xe1e1a3e15b42dfbaUL,
0x16165816b04e2ca6UL, 0x3a3ae83acdd274f7UL, 0x6969b9696fd0d206UL,
0x09092409482d1241UL, 0x7070dd70a7ade0d7UL, 0xb6b6e2b6d954716fUL,
0xd0d067d0ceb7bd1eUL,
0xeded93ed3b7ec7d6UL,
0xcccc17cc2edb85e2UL, 0x424215422a578468UL, 0x98985a98b4c22d2cUL,
0xa4a4aaa4490e55edUL, 0x2828a0285d885075UL, 0x5c5c6d5cda31b886UL,
0xf8f8c7f8933fed6bUL, 0x8686228644a411c2UL,
], [
0xd818186018c07830UL, 0x2623238c2305af46UL, 0xb8c6c63fc67ef991UL,
0xfbe8e887e8136fcdUL, 0xcb878726874ca113UL, 0x11b8b8dab8a9626dUL,
0x0901010401080502UL, 0x0d4f4f214f426e9eUL, 0x9b3636d836adee6cUL,
0xffa6a6a2a6590451UL,
0x0cd2d26fd2debdb9UL, 0x0ef5f5f3f5fb06f7UL, 0x967979f979ef80f2UL,
0x306f6fa16f5fcedeUL, 0x6d91917e91fcef3fUL, 0xf852525552aa07a4UL,
0x4760609d6027fdc0UL, 0x35bcbccabc897665UL, 0x379b9b569baccd2bUL,
0x8a8e8e028e048c01UL, 0xd2a3a3b6a371155bUL, 0x6c0c0c300c603c18UL,
0x847b7bf17bff8af6UL,
0x803535d435b5e16aUL,
0xf51d1d741de8693aUL, 0xb3e0e0a7e05347ddUL, 0x21d7d77bd7f6acb3UL,
0x9cc2c22fc25eed99UL, 0x432e2eb82e6d965cUL, 0x294b4b314b627a96UL,
0x5dfefedffea321e1UL, 0xd5575741578216aeUL, 0xbd15155415a8412aUL,
0xe87777c1779fb6eeUL, 0x923737dc37a5eb6eUL, 0x9ee5e5b3e57b56d7UL,
0x139f9f469f8cd923UL,
0x23f0f0e7f0d317fdUL,
0x204a4a354a6a7f94UL, 0x44dada4fda9e95a9UL, 0xa258587d58fa25b0UL,
0xcfc9c903c906ca8fUL, 0x7c2929a429558d52UL, 0x5a0a0a280a502214UL,
0x50b1b1feb1e14f7fUL, 0xc9a0a0baa0691a5dUL, 0x146b6bb16b7fdad6UL,
0xd985852e855cab17UL, 0x3cbdbdcebd817367UL, 0x8f5d5d695dd234baUL,
0x9010104010805020UL,
0x07f4f4f7f4f303f5UL,
0xddcbcb0bcb16c08bUL, 0xd33e3ef83eedc67cUL, 0x2d0505140528110aUL,
0x78676781671fe6ceUL, 0x97e4e4b7e47353d5UL, 0x0227279c2725bb4eUL,
0x7341411941325882UL, 0xa78b8b168b2c9d0bUL, 0xf6a7a7a6a7510153UL,
0xb27d7de97dcf94faUL, 0x4995956e95dcfb37UL, 0x56d8d847d88e9fadUL,
0x70fbfbcbfb8b30ebUL,
0xcdeeee9fee2371c1UL,
0xbb7c7ced7cc791f8UL, 0x716666856617e3ccUL, 0x7bdddd53dda68ea7UL,
0xaf17175c17b84b2eUL, 0x454747014702468eUL, 0x1a9e9e429e84dc21UL,
0xd4caca0fca1ec589UL, 0x582d2db42d75995aUL, 0x2ebfbfc6bf917963UL,
0x3f07071c07381b0eUL, 0xacadad8ead012347UL, 0xb05a5a755aea2fb4UL,
0xef838336836cb51bUL,
0xb63333cc3385ff66UL,
0x5c636391633ff2c6UL, 0x1202020802100a04UL, 0x93aaaa92aa393849UL,
0xde7171d971afa8e2UL, 0xc6c8c807c80ecf8dUL, 0xd119196419c87d32UL,
0x3b49493949727092UL, 0x5fd9d943d9869aafUL, 0x31f2f2eff2c31df9UL,
0xa8e3e3abe34b48dbUL, 0xb95b5b715be22ab6UL, 0xbc88881a8834920dUL,
0x3e9a9a529aa4c829UL,
0x0b262698262dbe4cUL,
0xbf3232c8328dfa64UL, 0x59b0b0fab0e94a7dUL, 0xf2e9e983e91b6acfUL,
0x770f0f3c0f78331eUL, 0x33d5d573d5e6a6b7UL, 0xf480803a8074ba1dUL,
0x27bebec2be997c61UL, 0xebcdcd13cd26de87UL, 0x893434d034bde468UL,
0x3248483d487a7590UL, 0x54ffffdbffab24e3UL, 0x8d7a7af57af78ff4UL,
0x6490907a90f4ea3dUL,
0x9d5f5f615fc23ebeUL,
0x3d202080201da040UL, 0x0f6868bd6867d5d0UL, 0xca1a1a681ad07234UL,
0xb7aeae82ae192c41UL, 0x7db4b4eab4c95e75UL, 0xce54544d549a19a8UL,
0x7f93937693ece53bUL, 0x2f222288220daa44UL, 0x6364648d6407e9c8UL,
0x2af1f1e3f1db12ffUL, 0xcc7373d173bfa2e6UL, 0x8212124812905a24UL,
0x7a40401d403a5d80UL,
0x4808082008402810UL,
0x95c3c32bc356e89bUL, 0xdfecec97ec337bc5UL, 0x4ddbdb4bdb9690abUL,
0xc0a1a1bea1611f5fUL, 0x918d8d0e8d1c8307UL, 0xc83d3df43df5c97aUL,
0x5b97976697ccf133UL, 0x0000000000000000UL, 0xf9cfcf1bcf36d483UL,
0x6e2b2bac2b458756UL, 0xe17676c57697b3ecUL, 0xe68282328264b019UL,
0x28d6d67fd6fea9b1UL,
0xc31b1b6c1bd87736UL,
0x74b5b5eeb5c15b77UL, 0xbeafaf86af112943UL, 0x1d6a6ab56a77dfd4UL,
0xea50505d50ba0da0UL, 0x5745450945124c8aUL, 0x38f3f3ebf3cb18fbUL,
0xad3030c0309df060UL, 0xc4efef9bef2b74c3UL, 0xda3f3ffc3fe5c37eUL,
0xc755554955921caaUL, 0xdba2a2b2a2791059UL, 0xe9eaea8fea0365c9UL,
0x6a656589650feccaUL,
0x03babad2bab96869UL,
0x4a2f2fbc2f65935eUL, 0x8ec0c027c04ee79dUL, 0x60dede5fdebe81a1UL,
0xfc1c1c701ce06c38UL, 0x46fdfdd3fdbb2ee7UL, 0x1f4d4d294d52649aUL,
0x7692927292e4e039UL, 0xfa7575c9758fbceaUL, 0x3606061806301e0cUL,
0xae8a8a128a249809UL, 0x4bb2b2f2b2f94079UL, 0x85e6e6bfe66359d1UL,
0x7e0e0e380e70361cUL,
0xe71f1f7c1ff8633eUL,
0x556262956237f7c4UL, 0x3ad4d477d4eea3b5UL, 0x81a8a89aa829324dUL,
0x5296966296c4f431UL, 0x62f9f9c3f99b3aefUL, 0xa3c5c533c566f697UL,
0x102525942535b14aUL, 0xab59597959f220b2UL, 0xd084842a8454ae15UL,
0xc57272d572b7a7e4UL, 0xec3939e439d5dd72UL, 0x164c4c2d4c5a6198UL,
0x945e5e655eca3bbcUL,
0x9f7878fd78e785f0UL,
0xe53838e038ddd870UL, 0x988c8c0a8c148605UL, 0x17d1d163d1c6b2bfUL,
0xe4a5a5aea5410b57UL, 0xa1e2e2afe2434dd9UL, 0x4e616199612ff8c2UL,
0x42b3b3f6b3f1457bUL, 0x342121842115a542UL, 0x089c9c4a9c94d625UL,
0xee1e1e781ef0663cUL, 0x6143431143225286UL, 0xb1c7c73bc776fc93UL,
0x4ffcfcd7fcb32be5UL,
0x2404041004201408UL,
0xe351515951b208a2UL, 0x2599995e99bcc72fUL, 0x226d6da96d4fc4daUL,
0x650d0d340d68391aUL, 0x79fafacffa8335e9UL, 0x69dfdf5bdfb684a3UL,
0xa97e7ee57ed79bfcUL, 0x19242490243db448UL, 0xfe3b3bec3bc5d776UL,
0x9aabab96ab313d4bUL, 0xf0cece1fce3ed181UL, 0x9911114411885522UL,
0x838f8f068f0c8903UL,
0x044e4e254e4a6b9cUL,
0x66b7b7e6b7d15173UL, 0xe0ebeb8beb0b60cbUL, 0xc13c3cf03cfdcc78UL,
0xfd81813e817cbf1fUL, 0x4094946a94d4fe35UL, 0x1cf7f7fbf7eb0cf3UL,
0x18b9b9deb9a1676fUL, 0x8b13134c13985f26UL, 0x512c2cb02c7d9c58UL,
0x05d3d36bd3d6b8bbUL, 0x8ce7e7bbe76b5cd3UL, 0x396e6ea56e57cbdcUL,
0xaac4c437c46ef395UL,
0x1b03030c03180f06UL,
0xdc565645568a13acUL, 0x5e44440d441a4988UL, 0xa07f7fe17fdf9efeUL,
0x88a9a99ea921374fUL, 0x672a2aa82a4d8254UL, 0x0abbbbd6bbb16d6bUL,
0x87c1c123c146e29fUL, 0xf153535153a202a6UL, 0x72dcdc57dcae8ba5UL,
0x530b0b2c0b582716UL, 0x019d9d4e9d9cd327UL, 0x2b6c6cad6c47c1d8UL,
0xa43131c43195f562UL,
0xf37474cd7487b9e8UL,
0x15f6f6fff6e309f1UL, 0x4c464605460a438cUL, 0xa5acac8aac092645UL,
0xb589891e893c970fUL, 0xb414145014a04428UL, 0xbae1e1a3e15b42dfUL,
0xa616165816b04e2cUL, 0xf73a3ae83acdd274UL, 0x066969b9696fd0d2UL,
0x4109092409482d12UL, 0xd77070dd70a7ade0UL, 0x6fb6b6e2b6d95471UL,
0x1ed0d067d0ceb7bdUL,
0xd6eded93ed3b7ec7UL,
0xe2cccc17cc2edb85UL, 0x68424215422a5784UL, 0x2c98985a98b4c22dUL,
0xeda4a4aaa4490e55UL, 0x752828a0285d8850UL, 0x865c5c6d5cda31b8UL,
0x6bf8f8c7f8933fedUL, 0xc28686228644a411UL,
], [
0x30d818186018c078UL, 0x462623238c2305afUL, 0x91b8c6c63fc67ef9UL,
0xcdfbe8e887e8136fUL, 0x13cb878726874ca1UL, 0x6d11b8b8dab8a962UL,
0x0209010104010805UL, 0x9e0d4f4f214f426eUL, 0x6c9b3636d836adeeUL,
0x51ffa6a6a2a65904UL,
0xb90cd2d26fd2debdUL, 0xf70ef5f5f3f5fb06UL, 0xf2967979f979ef80UL,
0xde306f6fa16f5fceUL, 0x3f6d91917e91fcefUL, 0xa4f852525552aa07UL,
0xc04760609d6027fdUL, 0x6535bcbccabc8976UL, 0x2b379b9b569baccdUL,
0x018a8e8e028e048cUL, 0x5bd2a3a3b6a37115UL, 0x186c0c0c300c603cUL,
0xf6847b7bf17bff8aUL,
0x6a803535d435b5e1UL,
0x3af51d1d741de869UL, 0xddb3e0e0a7e05347UL, 0xb321d7d77bd7f6acUL,
0x999cc2c22fc25eedUL, 0x5c432e2eb82e6d96UL, 0x96294b4b314b627aUL,
0xe15dfefedffea321UL, 0xaed5575741578216UL, 0x2abd15155415a841UL,
0xeee87777c1779fb6UL, 0x6e923737dc37a5ebUL, 0xd79ee5e5b3e57b56UL,
0x23139f9f469f8cd9UL,
0xfd23f0f0e7f0d317UL,
0x94204a4a354a6a7fUL, 0xa944dada4fda9e95UL, 0xb0a258587d58fa25UL,
0x8fcfc9c903c906caUL, 0x527c2929a429558dUL, 0x145a0a0a280a5022UL,
0x7f50b1b1feb1e14fUL, 0x5dc9a0a0baa0691aUL, 0xd6146b6bb16b7fdaUL,
0x17d985852e855cabUL, 0x673cbdbdcebd8173UL, 0xba8f5d5d695dd234UL,
0x2090101040108050UL,
0xf507f4f4f7f4f303UL,
0x8bddcbcb0bcb16c0UL, 0x7cd33e3ef83eedc6UL, 0x0a2d050514052811UL,
0xce78676781671fe6UL, 0xd597e4e4b7e47353UL, 0x4e0227279c2725bbUL,
0x8273414119413258UL, 0x0ba78b8b168b2c9dUL, 0x53f6a7a7a6a75101UL,
0xfab27d7de97dcf94UL, 0x374995956e95dcfbUL, 0xad56d8d847d88e9fUL,
0xeb70fbfbcbfb8b30UL,
0xc1cdeeee9fee2371UL,
0xf8bb7c7ced7cc791UL, 0xcc716666856617e3UL, 0xa77bdddd53dda68eUL,
0x2eaf17175c17b84bUL, 0x8e45474701470246UL, 0x211a9e9e429e84dcUL,
0x89d4caca0fca1ec5UL, 0x5a582d2db42d7599UL, 0x632ebfbfc6bf9179UL,
0x0e3f07071c07381bUL, 0x47acadad8ead0123UL, 0xb4b05a5a755aea2fUL,
0x1bef838336836cb5UL,
0x66b63333cc3385ffUL,
0xc65c636391633ff2UL, 0x041202020802100aUL, 0x4993aaaa92aa3938UL,
0xe2de7171d971afa8UL, 0x8dc6c8c807c80ecfUL, 0x32d119196419c87dUL,
0x923b494939497270UL, 0xaf5fd9d943d9869aUL, 0xf931f2f2eff2c31dUL,
0xdba8e3e3abe34b48UL, 0xb6b95b5b715be22aUL, 0x0dbc88881a883492UL,
0x293e9a9a529aa4c8UL,
0x4c0b262698262dbeUL,
0x64bf3232c8328dfaUL, 0x7d59b0b0fab0e94aUL, 0xcff2e9e983e91b6aUL,
0x1e770f0f3c0f7833UL, 0xb733d5d573d5e6a6UL, 0x1df480803a8074baUL,
0x6127bebec2be997cUL, 0x87ebcdcd13cd26deUL, 0x68893434d034bde4UL,
0x903248483d487a75UL, 0xe354ffffdbffab24UL, 0xf48d7a7af57af78fUL,
0x3d6490907a90f4eaUL,
0xbe9d5f5f615fc23eUL,
0x403d202080201da0UL, 0xd00f6868bd6867d5UL, 0x34ca1a1a681ad072UL,
0x41b7aeae82ae192cUL, 0x757db4b4eab4c95eUL, 0xa8ce54544d549a19UL,
0x3b7f93937693ece5UL, 0x442f222288220daaUL, 0xc86364648d6407e9UL,
0xff2af1f1e3f1db12UL, 0xe6cc7373d173bfa2UL, 0x248212124812905aUL,
0x807a40401d403a5dUL,
0x1048080820084028UL,
0x9b95c3c32bc356e8UL, 0xc5dfecec97ec337bUL, 0xab4ddbdb4bdb9690UL,
0x5fc0a1a1bea1611fUL, 0x07918d8d0e8d1c83UL, 0x7ac83d3df43df5c9UL,
0x335b97976697ccf1UL, 0x0000000000000000UL, 0x83f9cfcf1bcf36d4UL,
0x566e2b2bac2b4587UL, 0xece17676c57697b3UL, 0x19e68282328264b0UL,
0xb128d6d67fd6fea9UL,
0x36c31b1b6c1bd877UL,
0x7774b5b5eeb5c15bUL, 0x43beafaf86af1129UL, 0xd41d6a6ab56a77dfUL,
0xa0ea50505d50ba0dUL, 0x8a5745450945124cUL, 0xfb38f3f3ebf3cb18UL,
0x60ad3030c0309df0UL, 0xc3c4efef9bef2b74UL, 0x7eda3f3ffc3fe5c3UL,
0xaac755554955921cUL, 0x59dba2a2b2a27910UL, 0xc9e9eaea8fea0365UL,
0xca6a656589650fecUL,
0x6903babad2bab968UL,
0x5e4a2f2fbc2f6593UL, 0x9d8ec0c027c04ee7UL, 0xa160dede5fdebe81UL,
0x38fc1c1c701ce06cUL, 0xe746fdfdd3fdbb2eUL, 0x9a1f4d4d294d5264UL,
0x397692927292e4e0UL, 0xeafa7575c9758fbcUL, 0x0c3606061806301eUL,
0x09ae8a8a128a2498UL, 0x794bb2b2f2b2f940UL, 0xd185e6e6bfe66359UL,
0x1c7e0e0e380e7036UL,
0x3ee71f1f7c1ff863UL,
0xc4556262956237f7UL, 0xb53ad4d477d4eea3UL, 0x4d81a8a89aa82932UL,
0x315296966296c4f4UL, 0xef62f9f9c3f99b3aUL, 0x97a3c5c533c566f6UL,
0x4a102525942535b1UL, 0xb2ab59597959f220UL, 0x15d084842a8454aeUL,
0xe4c57272d572b7a7UL, 0x72ec3939e439d5ddUL, 0x98164c4c2d4c5a61UL,
0xbc945e5e655eca3bUL,
0xf09f7878fd78e785UL,
0x70e53838e038ddd8UL, 0x05988c8c0a8c1486UL, 0xbf17d1d163d1c6b2UL,
0x57e4a5a5aea5410bUL, 0xd9a1e2e2afe2434dUL, 0xc24e616199612ff8UL,
0x7b42b3b3f6b3f145UL, 0x42342121842115a5UL, 0x25089c9c4a9c94d6UL,
0x3cee1e1e781ef066UL, 0x8661434311432252UL, 0x93b1c7c73bc776fcUL,
0xe54ffcfcd7fcb32bUL,
0x0824040410042014UL,
0xa2e351515951b208UL, 0x2f2599995e99bcc7UL, 0xda226d6da96d4fc4UL,
0x1a650d0d340d6839UL, 0xe979fafacffa8335UL, 0xa369dfdf5bdfb684UL,
0xfca97e7ee57ed79bUL, 0x4819242490243db4UL, 0x76fe3b3bec3bc5d7UL,
0x4b9aabab96ab313dUL, 0x81f0cece1fce3ed1UL, 0x2299111144118855UL,
0x03838f8f068f0c89UL,
0x9c044e4e254e4a6bUL,
0x7366b7b7e6b7d151UL, 0xcbe0ebeb8beb0b60UL, 0x78c13c3cf03cfdccUL,
0x1ffd81813e817cbfUL, 0x354094946a94d4feUL, 0xf31cf7f7fbf7eb0cUL,
0x6f18b9b9deb9a167UL, 0x268b13134c13985fUL, 0x58512c2cb02c7d9cUL,
0xbb05d3d36bd3d6b8UL, 0xd38ce7e7bbe76b5cUL, 0xdc396e6ea56e57cbUL,
0x95aac4c437c46ef3UL,
0x061b03030c03180fUL,
0xacdc565645568a13UL, 0x885e44440d441a49UL, 0xfea07f7fe17fdf9eUL,
0x4f88a9a99ea92137UL, 0x54672a2aa82a4d82UL, 0x6b0abbbbd6bbb16dUL,
0x9f87c1c123c146e2UL, 0xa6f153535153a202UL, 0xa572dcdc57dcae8bUL,
0x16530b0b2c0b5827UL, 0x27019d9d4e9d9cd3UL, 0xd82b6c6cad6c47c1UL,
0x62a43131c43195f5UL,
0xe8f37474cd7487b9UL,
0xf115f6f6fff6e309UL, 0x8c4c464605460a43UL, 0x45a5acac8aac0926UL,
0x0fb589891e893c97UL, 0x28b414145014a044UL, 0xdfbae1e1a3e15b42UL,
0x2ca616165816b04eUL, 0x74f73a3ae83acdd2UL, 0xd2066969b9696fd0UL,
0x124109092409482dUL, 0xe0d77070dd70a7adUL, 0x716fb6b6e2b6d954UL,
0xbd1ed0d067d0ceb7UL,
0xc7d6eded93ed3b7eUL,
0x85e2cccc17cc2edbUL, 0x8468424215422a57UL, 0x2d2c98985a98b4c2UL,
0x55eda4a4aaa4490eUL, 0x50752828a0285d88UL, 0xb8865c5c6d5cda31UL,
0xed6bf8f8c7f8933fUL, 0x11c28686228644a4UL,
], [
0x7830d818186018c0UL, 0xaf462623238c2305UL, 0xf991b8c6c63fc67eUL,
0x6fcdfbe8e887e813UL, 0xa113cb878726874cUL, 0x626d11b8b8dab8a9UL,
0x0502090101040108UL, 0x6e9e0d4f4f214f42UL, 0xee6c9b3636d836adUL,
0x0451ffa6a6a2a659UL,
0xbdb90cd2d26fd2deUL, 0x06f70ef5f5f3f5fbUL, 0x80f2967979f979efUL,
0xcede306f6fa16f5fUL, 0xef3f6d91917e91fcUL, 0x07a4f852525552aaUL,
0xfdc04760609d6027UL, 0x766535bcbccabc89UL, 0xcd2b379b9b569bacUL,
0x8c018a8e8e028e04UL, 0x155bd2a3a3b6a371UL, 0x3c186c0c0c300c60UL,
0x8af6847b7bf17bffUL,
0xe16a803535d435b5UL,
0x693af51d1d741de8UL, 0x47ddb3e0e0a7e053UL, 0xacb321d7d77bd7f6UL,
0xed999cc2c22fc25eUL, 0x965c432e2eb82e6dUL, 0x7a96294b4b314b62UL,
0x21e15dfefedffea3UL, 0x16aed55757415782UL, 0x412abd15155415a8UL,
0xb6eee87777c1779fUL, 0xeb6e923737dc37a5UL, 0x56d79ee5e5b3e57bUL,
0xd923139f9f469f8cUL,
0x17fd23f0f0e7f0d3UL,
0x7f94204a4a354a6aUL, 0x95a944dada4fda9eUL, 0x25b0a258587d58faUL,
0xca8fcfc9c903c906UL, 0x8d527c2929a42955UL, 0x22145a0a0a280a50UL,
0x4f7f50b1b1feb1e1UL, 0x1a5dc9a0a0baa069UL, 0xdad6146b6bb16b7fUL,
0xab17d985852e855cUL, 0x73673cbdbdcebd81UL, 0x34ba8f5d5d695dd2UL,
0x5020901010401080UL,
0x03f507f4f4f7f4f3UL,
0xc08bddcbcb0bcb16UL, 0xc67cd33e3ef83eedUL, 0x110a2d0505140528UL,
0xe6ce78676781671fUL, 0x53d597e4e4b7e473UL, 0xbb4e0227279c2725UL,
0x5882734141194132UL, 0x9d0ba78b8b168b2cUL, 0x0153f6a7a7a6a751UL,
0x94fab27d7de97dcfUL, 0xfb374995956e95dcUL, 0x9fad56d8d847d88eUL,
0x30eb70fbfbcbfb8bUL,
0x71c1cdeeee9fee23UL,
0x91f8bb7c7ced7cc7UL, 0xe3cc716666856617UL, 0x8ea77bdddd53dda6UL,
0x4b2eaf17175c17b8UL, 0x468e454747014702UL, 0xdc211a9e9e429e84UL,
0xc589d4caca0fca1eUL, 0x995a582d2db42d75UL, 0x79632ebfbfc6bf91UL,
0x1b0e3f07071c0738UL, 0x2347acadad8ead01UL, 0x2fb4b05a5a755aeaUL,
0xb51bef838336836cUL,
0xff66b63333cc3385UL,
0xf2c65c636391633fUL, 0x0a04120202080210UL, 0x384993aaaa92aa39UL,
0xa8e2de7171d971afUL, 0xcf8dc6c8c807c80eUL, 0x7d32d119196419c8UL,
0x70923b4949394972UL, 0x9aaf5fd9d943d986UL, 0x1df931f2f2eff2c3UL,
0x48dba8e3e3abe34bUL, 0x2ab6b95b5b715be2UL, 0x920dbc88881a8834UL,
0xc8293e9a9a529aa4UL,
0xbe4c0b262698262dUL,
0xfa64bf3232c8328dUL, 0x4a7d59b0b0fab0e9UL, 0x6acff2e9e983e91bUL,
0x331e770f0f3c0f78UL, 0xa6b733d5d573d5e6UL, 0xba1df480803a8074UL,
0x7c6127bebec2be99UL, 0xde87ebcdcd13cd26UL, 0xe468893434d034bdUL,
0x75903248483d487aUL, 0x24e354ffffdbffabUL, 0x8ff48d7a7af57af7UL,
0xea3d6490907a90f4UL,
0x3ebe9d5f5f615fc2UL,
0xa0403d202080201dUL, 0xd5d00f6868bd6867UL, 0x7234ca1a1a681ad0UL,
0x2c41b7aeae82ae19UL, 0x5e757db4b4eab4c9UL, 0x19a8ce54544d549aUL,
0xe53b7f93937693ecUL, 0xaa442f222288220dUL, 0xe9c86364648d6407UL,
0x12ff2af1f1e3f1dbUL, 0xa2e6cc7373d173bfUL, 0x5a24821212481290UL,
0x5d807a40401d403aUL,
0x2810480808200840UL,
0xe89b95c3c32bc356UL, 0x7bc5dfecec97ec33UL, 0x90ab4ddbdb4bdb96UL,
0x1f5fc0a1a1bea161UL, 0x8307918d8d0e8d1cUL, 0xc97ac83d3df43df5UL,
0xf1335b97976697ccUL, 0x0000000000000000UL, 0xd483f9cfcf1bcf36UL,
0x87566e2b2bac2b45UL, 0xb3ece17676c57697UL, 0xb019e68282328264UL,
0xa9b128d6d67fd6feUL,
0x7736c31b1b6c1bd8UL,
0x5b7774b5b5eeb5c1UL, 0x2943beafaf86af11UL, 0xdfd41d6a6ab56a77UL,
0x0da0ea50505d50baUL, 0x4c8a574545094512UL, 0x18fb38f3f3ebf3cbUL,
0xf060ad3030c0309dUL, 0x74c3c4efef9bef2bUL, 0xc37eda3f3ffc3fe5UL,
0x1caac75555495592UL, 0x1059dba2a2b2a279UL, 0x65c9e9eaea8fea03UL,
0xecca6a656589650fUL,
0x686903babad2bab9UL,
0x935e4a2f2fbc2f65UL, 0xe79d8ec0c027c04eUL, 0x81a160dede5fdebeUL,
0x6c38fc1c1c701ce0UL, 0x2ee746fdfdd3fdbbUL, 0x649a1f4d4d294d52UL,
0xe0397692927292e4UL, 0xbceafa7575c9758fUL, 0x1e0c360606180630UL,
0x9809ae8a8a128a24UL, 0x40794bb2b2f2b2f9UL, 0x59d185e6e6bfe663UL,
0x361c7e0e0e380e70UL,
0x633ee71f1f7c1ff8UL,
0xf7c4556262956237UL, 0xa3b53ad4d477d4eeUL, 0x324d81a8a89aa829UL,
0xf4315296966296c4UL, 0x3aef62f9f9c3f99bUL, 0xf697a3c5c533c566UL,
0xb14a102525942535UL, 0x20b2ab59597959f2UL, 0xae15d084842a8454UL,
0xa7e4c57272d572b7UL, 0xdd72ec3939e439d5UL, 0x6198164c4c2d4c5aUL,
0x3bbc945e5e655ecaUL,
0x85f09f7878fd78e7UL,
0xd870e53838e038ddUL, 0x8605988c8c0a8c14UL, 0xb2bf17d1d163d1c6UL,
0x0b57e4a5a5aea541UL, 0x4dd9a1e2e2afe243UL, 0xf8c24e616199612fUL,
0x457b42b3b3f6b3f1UL, 0xa542342121842115UL, 0xd625089c9c4a9c94UL,
0x663cee1e1e781ef0UL, 0x5286614343114322UL, 0xfc93b1c7c73bc776UL,
0x2be54ffcfcd7fcb3UL,
0x1408240404100420UL,
0x08a2e351515951b2UL, 0xc72f2599995e99bcUL, 0xc4da226d6da96d4fUL,
0x391a650d0d340d68UL, 0x35e979fafacffa83UL, 0x84a369dfdf5bdfb6UL,
0x9bfca97e7ee57ed7UL, 0xb44819242490243dUL, 0xd776fe3b3bec3bc5UL,
0x3d4b9aabab96ab31UL, 0xd181f0cece1fce3eUL, 0x5522991111441188UL,
0x8903838f8f068f0cUL,
0x6b9c044e4e254e4aUL,
0x517366b7b7e6b7d1UL, 0x60cbe0ebeb8beb0bUL, 0xcc78c13c3cf03cfdUL,
0xbf1ffd81813e817cUL, 0xfe354094946a94d4UL, 0x0cf31cf7f7fbf7ebUL,
0x676f18b9b9deb9a1UL, 0x5f268b13134c1398UL, 0x9c58512c2cb02c7dUL,
0xb8bb05d3d36bd3d6UL, 0x5cd38ce7e7bbe76bUL, 0xcbdc396e6ea56e57UL,
0xf395aac4c437c46eUL,
0x0f061b03030c0318UL,
0x13acdc565645568aUL, 0x49885e44440d441aUL, 0x9efea07f7fe17fdfUL,
0x374f88a9a99ea921UL, 0x8254672a2aa82a4dUL, 0x6d6b0abbbbd6bbb1UL,
0xe29f87c1c123c146UL, 0x02a6f153535153a2UL, 0x8ba572dcdc57dcaeUL,
0x2716530b0b2c0b58UL, 0xd327019d9d4e9d9cUL, 0xc1d82b6c6cad6c47UL,
0xf562a43131c43195UL,
0xb9e8f37474cd7487UL,
0x09f115f6f6fff6e3UL, 0x438c4c464605460aUL, 0x2645a5acac8aac09UL,
0x970fb589891e893cUL, 0x4428b414145014a0UL, 0x42dfbae1e1a3e15bUL,
0x4e2ca616165816b0UL, 0xd274f73a3ae83acdUL, 0xd0d2066969b9696fUL,
0x2d12410909240948UL, 0xade0d77070dd70a7UL, 0x54716fb6b6e2b6d9UL,
0xb7bd1ed0d067d0ceUL,
0x7ec7d6eded93ed3bUL,
0xdb85e2cccc17cc2eUL, 0x578468424215422aUL, 0xc22d2c98985a98b4UL,
0x0e55eda4a4aaa449UL, 0x8850752828a0285dUL, 0x31b8865c5c6d5cdaUL,
0x3fed6bf8f8c7f893UL, 0xa411c28686228644UL,
], [
0xc07830d818186018UL, 0x05af462623238c23UL, 0x7ef991b8c6c63fc6UL,
0x136fcdfbe8e887e8UL, 0x4ca113cb87872687UL, 0xa9626d11b8b8dab8UL,
0x0805020901010401UL, 0x426e9e0d4f4f214fUL, 0xadee6c9b3636d836UL,
0x590451ffa6a6a2a6UL,
0xdebdb90cd2d26fd2UL, 0xfb06f70ef5f5f3f5UL, 0xef80f2967979f979UL,
0x5fcede306f6fa16fUL, 0xfcef3f6d91917e91UL, 0xaa07a4f852525552UL,
0x27fdc04760609d60UL, 0x89766535bcbccabcUL, 0xaccd2b379b9b569bUL,
0x048c018a8e8e028eUL, 0x71155bd2a3a3b6a3UL, 0x603c186c0c0c300cUL,
0xff8af6847b7bf17bUL,
0xb5e16a803535d435UL,
0xe8693af51d1d741dUL, 0x5347ddb3e0e0a7e0UL, 0xf6acb321d7d77bd7UL,
0x5eed999cc2c22fc2UL, 0x6d965c432e2eb82eUL, 0x627a96294b4b314bUL,
0xa321e15dfefedffeUL, 0x8216aed557574157UL, 0xa8412abd15155415UL,
0x9fb6eee87777c177UL, 0xa5eb6e923737dc37UL, 0x7b56d79ee5e5b3e5UL,
0x8cd923139f9f469fUL,
0xd317fd23f0f0e7f0UL,
0x6a7f94204a4a354aUL, 0x9e95a944dada4fdaUL, 0xfa25b0a258587d58UL,
0x06ca8fcfc9c903c9UL, 0x558d527c2929a429UL, 0x5022145a0a0a280aUL,
0xe14f7f50b1b1feb1UL, 0x691a5dc9a0a0baa0UL, 0x7fdad6146b6bb16bUL,
0x5cab17d985852e85UL, 0x8173673cbdbdcebdUL, 0xd234ba8f5d5d695dUL,
0x8050209010104010UL,
0xf303f507f4f4f7f4UL,
0x16c08bddcbcb0bcbUL, 0xedc67cd33e3ef83eUL, 0x28110a2d05051405UL,
0x1fe6ce7867678167UL, 0x7353d597e4e4b7e4UL, 0x25bb4e0227279c27UL,
0x3258827341411941UL, 0x2c9d0ba78b8b168bUL, 0x510153f6a7a7a6a7UL,
0xcf94fab27d7de97dUL, 0xdcfb374995956e95UL, 0x8e9fad56d8d847d8UL,
0x8b30eb70fbfbcbfbUL,
0x2371c1cdeeee9feeUL,
0xc791f8bb7c7ced7cUL, 0x17e3cc7166668566UL, 0xa68ea77bdddd53ddUL,
0xb84b2eaf17175c17UL, 0x02468e4547470147UL, 0x84dc211a9e9e429eUL,
0x1ec589d4caca0fcaUL, 0x75995a582d2db42dUL, 0x9179632ebfbfc6bfUL,
0x381b0e3f07071c07UL, 0x012347acadad8eadUL, 0xea2fb4b05a5a755aUL,
0x6cb51bef83833683UL,
0x85ff66b63333cc33UL,
0x3ff2c65c63639163UL, 0x100a041202020802UL, 0x39384993aaaa92aaUL,
0xafa8e2de7171d971UL, 0x0ecf8dc6c8c807c8UL, 0xc87d32d119196419UL,
0x7270923b49493949UL, 0x869aaf5fd9d943d9UL, 0xc31df931f2f2eff2UL,
0x4b48dba8e3e3abe3UL, 0xe22ab6b95b5b715bUL, 0x34920dbc88881a88UL,
0xa4c8293e9a9a529aUL,
0x2dbe4c0b26269826UL,
0x8dfa64bf3232c832UL, 0xe94a7d59b0b0fab0UL, 0x1b6acff2e9e983e9UL,
0x78331e770f0f3c0fUL, 0xe6a6b733d5d573d5UL, 0x74ba1df480803a80UL,
0x997c6127bebec2beUL, 0x26de87ebcdcd13cdUL, 0xbde468893434d034UL,
0x7a75903248483d48UL, 0xab24e354ffffdbffUL, 0xf78ff48d7a7af57aUL,
0xf4ea3d6490907a90UL,
0xc23ebe9d5f5f615fUL,
0x1da0403d20208020UL, 0x67d5d00f6868bd68UL, 0xd07234ca1a1a681aUL,
0x192c41b7aeae82aeUL, 0xc95e757db4b4eab4UL, 0x9a19a8ce54544d54UL,
0xece53b7f93937693UL, 0x0daa442f22228822UL, 0x07e9c86364648d64UL,
0xdb12ff2af1f1e3f1UL, 0xbfa2e6cc7373d173UL, 0x905a248212124812UL,
0x3a5d807a40401d40UL,
0x4028104808082008UL,
0x56e89b95c3c32bc3UL, 0x337bc5dfecec97ecUL, 0x9690ab4ddbdb4bdbUL,
0x611f5fc0a1a1bea1UL, 0x1c8307918d8d0e8dUL, 0xf5c97ac83d3df43dUL,
0xccf1335b97976697UL, 0x0000000000000000UL, 0x36d483f9cfcf1bcfUL,
0x4587566e2b2bac2bUL, 0x97b3ece17676c576UL, 0x64b019e682823282UL,
0xfea9b128d6d67fd6UL,
0xd87736c31b1b6c1bUL,
0xc15b7774b5b5eeb5UL, 0x112943beafaf86afUL, 0x77dfd41d6a6ab56aUL,
0xba0da0ea50505d50UL, 0x124c8a5745450945UL, 0xcb18fb38f3f3ebf3UL,
0x9df060ad3030c030UL, 0x2b74c3c4efef9befUL, 0xe5c37eda3f3ffc3fUL,
0x921caac755554955UL, 0x791059dba2a2b2a2UL, 0x0365c9e9eaea8feaUL,
0x0fecca6a65658965UL,
0xb9686903babad2baUL,
0x65935e4a2f2fbc2fUL, 0x4ee79d8ec0c027c0UL, 0xbe81a160dede5fdeUL,
0xe06c38fc1c1c701cUL, 0xbb2ee746fdfdd3fdUL, 0x52649a1f4d4d294dUL,
0xe4e0397692927292UL, 0x8fbceafa7575c975UL, 0x301e0c3606061806UL,
0x249809ae8a8a128aUL, 0xf940794bb2b2f2b2UL, 0x6359d185e6e6bfe6UL,
0x70361c7e0e0e380eUL,
0xf8633ee71f1f7c1fUL,
0x37f7c45562629562UL, 0xeea3b53ad4d477d4UL, 0x29324d81a8a89aa8UL,
0xc4f4315296966296UL, 0x9b3aef62f9f9c3f9UL, 0x66f697a3c5c533c5UL,
0x35b14a1025259425UL, 0xf220b2ab59597959UL, 0x54ae15d084842a84UL,
0xb7a7e4c57272d572UL, 0xd5dd72ec3939e439UL, 0x5a6198164c4c2d4cUL,
0xca3bbc945e5e655eUL,
0xe785f09f7878fd78UL,
0xddd870e53838e038UL, 0x148605988c8c0a8cUL, 0xc6b2bf17d1d163d1UL,
0x410b57e4a5a5aea5UL, 0x434dd9a1e2e2afe2UL, 0x2ff8c24e61619961UL,
0xf1457b42b3b3f6b3UL, 0x15a5423421218421UL, 0x94d625089c9c4a9cUL,
0xf0663cee1e1e781eUL, 0x2252866143431143UL, 0x76fc93b1c7c73bc7UL,
0xb32be54ffcfcd7fcUL,
0x2014082404041004UL,
0xb208a2e351515951UL, 0xbcc72f2599995e99UL, 0x4fc4da226d6da96dUL,
0x68391a650d0d340dUL, 0x8335e979fafacffaUL, 0xb684a369dfdf5bdfUL,
0xd79bfca97e7ee57eUL, 0x3db4481924249024UL, 0xc5d776fe3b3bec3bUL,
0x313d4b9aabab96abUL, 0x3ed181f0cece1fceUL, 0x8855229911114411UL,
0x0c8903838f8f068fUL,
0x4a6b9c044e4e254eUL,
0xd1517366b7b7e6b7UL, 0x0b60cbe0ebeb8bebUL, 0xfdcc78c13c3cf03cUL,
0x7cbf1ffd81813e81UL, 0xd4fe354094946a94UL, 0xeb0cf31cf7f7fbf7UL,
0xa1676f18b9b9deb9UL, 0x985f268b13134c13UL, 0x7d9c58512c2cb02cUL,
0xd6b8bb05d3d36bd3UL, 0x6b5cd38ce7e7bbe7UL, 0x57cbdc396e6ea56eUL,
0x6ef395aac4c437c4UL,
0x180f061b03030c03UL,
0x8a13acdc56564556UL, 0x1a49885e44440d44UL, 0xdf9efea07f7fe17fUL,
0x21374f88a9a99ea9UL, 0x4d8254672a2aa82aUL, 0xb16d6b0abbbbd6bbUL,
0x46e29f87c1c123c1UL, 0xa202a6f153535153UL, 0xae8ba572dcdc57dcUL,
0x582716530b0b2c0bUL, 0x9cd327019d9d4e9dUL, 0x47c1d82b6c6cad6cUL,
0x95f562a43131c431UL,
0x87b9e8f37474cd74UL,
0xe309f115f6f6fff6UL, 0x0a438c4c46460546UL, 0x092645a5acac8aacUL,
0x3c970fb589891e89UL, 0xa04428b414145014UL, 0x5b42dfbae1e1a3e1UL,
0xb04e2ca616165816UL, 0xcdd274f73a3ae83aUL, 0x6fd0d2066969b969UL,
0x482d124109092409UL, 0xa7ade0d77070dd70UL, 0xd954716fb6b6e2b6UL,
0xceb7bd1ed0d067d0UL,
0x3b7ec7d6eded93edUL,
0x2edb85e2cccc17ccUL, 0x2a57846842421542UL, 0xb4c22d2c98985a98UL,
0x490e55eda4a4aaa4UL, 0x5d8850752828a028UL, 0xda31b8865c5c6d5cUL,
0x933fed6bf8f8c7f8UL, 0x44a411c286862286UL,
], [
0x18c07830d8181860UL, 0x2305af462623238cUL, 0xc67ef991b8c6c63fUL,
0xe8136fcdfbe8e887UL, 0x874ca113cb878726UL, 0xb8a9626d11b8b8daUL,
0x0108050209010104UL, 0x4f426e9e0d4f4f21UL, 0x36adee6c9b3636d8UL,
0xa6590451ffa6a6a2UL,
0xd2debdb90cd2d26fUL, 0xf5fb06f70ef5f5f3UL, 0x79ef80f2967979f9UL,
0x6f5fcede306f6fa1UL, 0x91fcef3f6d91917eUL, 0x52aa07a4f8525255UL,
0x6027fdc04760609dUL, 0xbc89766535bcbccaUL, 0x9baccd2b379b9b56UL,
0x8e048c018a8e8e02UL, 0xa371155bd2a3a3b6UL, 0x0c603c186c0c0c30UL,
0x7bff8af6847b7bf1UL,
0x35b5e16a803535d4UL,
0x1de8693af51d1d74UL, 0xe05347ddb3e0e0a7UL, 0xd7f6acb321d7d77bUL,
0xc25eed999cc2c22fUL, 0x2e6d965c432e2eb8UL, 0x4b627a96294b4b31UL,
0xfea321e15dfefedfUL, 0x578216aed5575741UL, 0x15a8412abd151554UL,
0x779fb6eee87777c1UL, 0x37a5eb6e923737dcUL, 0xe57b56d79ee5e5b3UL,
0x9f8cd923139f9f46UL,
0xf0d317fd23f0f0e7UL,
0x4a6a7f94204a4a35UL, 0xda9e95a944dada4fUL, 0x58fa25b0a258587dUL,
0xc906ca8fcfc9c903UL, 0x29558d527c2929a4UL, 0x0a5022145a0a0a28UL,
0xb1e14f7f50b1b1feUL, 0xa0691a5dc9a0a0baUL, 0x6b7fdad6146b6bb1UL,
0x855cab17d985852eUL, 0xbd8173673cbdbdceUL, 0x5dd234ba8f5d5d69UL,
0x1080502090101040UL,
0xf4f303f507f4f4f7UL,
0xcb16c08bddcbcb0bUL, 0x3eedc67cd33e3ef8UL, 0x0528110a2d050514UL,
0x671fe6ce78676781UL, 0xe47353d597e4e4b7UL, 0x2725bb4e0227279cUL,
0x4132588273414119UL, 0x8b2c9d0ba78b8b16UL, 0xa7510153f6a7a7a6UL,
0x7dcf94fab27d7de9UL, 0x95dcfb374995956eUL, 0xd88e9fad56d8d847UL,
0xfb8b30eb70fbfbcbUL,
0xee2371c1cdeeee9fUL,
0x7cc791f8bb7c7cedUL, 0x6617e3cc71666685UL, 0xdda68ea77bdddd53UL,
0x17b84b2eaf17175cUL, 0x4702468e45474701UL, 0x9e84dc211a9e9e42UL,
0xca1ec589d4caca0fUL, 0x2d75995a582d2db4UL, 0xbf9179632ebfbfc6UL,
0x07381b0e3f07071cUL, 0xad012347acadad8eUL, 0x5aea2fb4b05a5a75UL,
0x836cb51bef838336UL,
0x3385ff66b63333ccUL,
0x633ff2c65c636391UL, 0x02100a0412020208UL, 0xaa39384993aaaa92UL,
0x71afa8e2de7171d9UL, 0xc80ecf8dc6c8c807UL, 0x19c87d32d1191964UL,
0x497270923b494939UL, 0xd9869aaf5fd9d943UL, 0xf2c31df931f2f2efUL,
0xe34b48dba8e3e3abUL, 0x5be22ab6b95b5b71UL, 0x8834920dbc88881aUL,
0x9aa4c8293e9a9a52UL,
0x262dbe4c0b262698UL,
0x328dfa64bf3232c8UL, 0xb0e94a7d59b0b0faUL, 0xe91b6acff2e9e983UL,
0x0f78331e770f0f3cUL, 0xd5e6a6b733d5d573UL, 0x8074ba1df480803aUL,
0xbe997c6127bebec2UL, 0xcd26de87ebcdcd13UL, 0x34bde468893434d0UL,
0x487a75903248483dUL, 0xffab24e354ffffdbUL, 0x7af78ff48d7a7af5UL,
0x90f4ea3d6490907aUL,
0x5fc23ebe9d5f5f61UL,
0x201da0403d202080UL, 0x6867d5d00f6868bdUL, 0x1ad07234ca1a1a68UL,
0xae192c41b7aeae82UL, 0xb4c95e757db4b4eaUL, 0x549a19a8ce54544dUL,
0x93ece53b7f939376UL, 0x220daa442f222288UL, 0x6407e9c86364648dUL,
0xf1db12ff2af1f1e3UL, 0x73bfa2e6cc7373d1UL, 0x12905a2482121248UL,
0x403a5d807a40401dUL,
0x0840281048080820UL,
0xc356e89b95c3c32bUL, 0xec337bc5dfecec97UL, 0xdb9690ab4ddbdb4bUL,
0xa1611f5fc0a1a1beUL, 0x8d1c8307918d8d0eUL, 0x3df5c97ac83d3df4UL,
0x97ccf1335b979766UL, 0x0000000000000000UL, 0xcf36d483f9cfcf1bUL,
0x2b4587566e2b2bacUL, 0x7697b3ece17676c5UL, 0x8264b019e6828232UL,
0xd6fea9b128d6d67fUL,
0x1bd87736c31b1b6cUL,
0xb5c15b7774b5b5eeUL, 0xaf112943beafaf86UL, 0x6a77dfd41d6a6ab5UL,
0x50ba0da0ea50505dUL, 0x45124c8a57454509UL, 0xf3cb18fb38f3f3ebUL,
0x309df060ad3030c0UL, 0xef2b74c3c4efef9bUL, 0x3fe5c37eda3f3ffcUL,
0x55921caac7555549UL, 0xa2791059dba2a2b2UL, 0xea0365c9e9eaea8fUL,
0x650fecca6a656589UL,
0xbab9686903babad2UL,
0x2f65935e4a2f2fbcUL, 0xc04ee79d8ec0c027UL, 0xdebe81a160dede5fUL,
0x1ce06c38fc1c1c70UL, 0xfdbb2ee746fdfdd3UL, 0x4d52649a1f4d4d29UL,
0x92e4e03976929272UL, 0x758fbceafa7575c9UL, 0x06301e0c36060618UL,
0x8a249809ae8a8a12UL, 0xb2f940794bb2b2f2UL, 0xe66359d185e6e6bfUL,
0x0e70361c7e0e0e38UL,
0x1ff8633ee71f1f7cUL,
0x6237f7c455626295UL, 0xd4eea3b53ad4d477UL, 0xa829324d81a8a89aUL,
0x96c4f43152969662UL, 0xf99b3aef62f9f9c3UL, 0xc566f697a3c5c533UL,
0x2535b14a10252594UL, 0x59f220b2ab595979UL, 0x8454ae15d084842aUL,
0x72b7a7e4c57272d5UL, 0x39d5dd72ec3939e4UL, 0x4c5a6198164c4c2dUL,
0x5eca3bbc945e5e65UL,
0x78e785f09f7878fdUL,
0x38ddd870e53838e0UL, 0x8c148605988c8c0aUL, 0xd1c6b2bf17d1d163UL,
0xa5410b57e4a5a5aeUL, 0xe2434dd9a1e2e2afUL, 0x612ff8c24e616199UL,
0xb3f1457b42b3b3f6UL, 0x2115a54234212184UL, 0x9c94d625089c9c4aUL,
0x1ef0663cee1e1e78UL, 0x4322528661434311UL, 0xc776fc93b1c7c73bUL,
0xfcb32be54ffcfcd7UL,
0x0420140824040410UL,
0x51b208a2e3515159UL, 0x99bcc72f2599995eUL, 0x6d4fc4da226d6da9UL,
0x0d68391a650d0d34UL, 0xfa8335e979fafacfUL, 0xdfb684a369dfdf5bUL,
0x7ed79bfca97e7ee5UL, 0x243db44819242490UL, 0x3bc5d776fe3b3becUL,
0xab313d4b9aabab96UL, 0xce3ed181f0cece1fUL, 0x1188552299111144UL,
0x8f0c8903838f8f06UL,
0x4e4a6b9c044e4e25UL,
0xb7d1517366b7b7e6UL, 0xeb0b60cbe0ebeb8bUL, 0x3cfdcc78c13c3cf0UL,
0x817cbf1ffd81813eUL, 0x94d4fe354094946aUL, 0xf7eb0cf31cf7f7fbUL,
0xb9a1676f18b9b9deUL, 0x13985f268b13134cUL, 0x2c7d9c58512c2cb0UL,
0xd3d6b8bb05d3d36bUL, 0xe76b5cd38ce7e7bbUL, 0x6e57cbdc396e6ea5UL,
0xc46ef395aac4c437UL,
0x03180f061b03030cUL,
0x568a13acdc565645UL, 0x441a49885e44440dUL, 0x7fdf9efea07f7fe1UL,
0xa921374f88a9a99eUL, 0x2a4d8254672a2aa8UL, 0xbbb16d6b0abbbbd6UL,
0xc146e29f87c1c123UL, 0x53a202a6f1535351UL, 0xdcae8ba572dcdc57UL,
0x0b582716530b0b2cUL, 0x9d9cd327019d9d4eUL, 0x6c47c1d82b6c6cadUL,
0x3195f562a43131c4UL,
0x7487b9e8f37474cdUL,
0xf6e309f115f6f6ffUL, 0x460a438c4c464605UL, 0xac092645a5acac8aUL,
0x893c970fb589891eUL, 0x14a04428b4141450UL, 0xe15b42dfbae1e1a3UL,
0x16b04e2ca6161658UL, 0x3acdd274f73a3ae8UL, 0x696fd0d2066969b9UL,
0x09482d1241090924UL, 0x70a7ade0d77070ddUL, 0xb6d954716fb6b6e2UL,
0xd0ceb7bd1ed0d067UL,
0xed3b7ec7d6eded93UL,
0xcc2edb85e2cccc17UL, 0x422a578468424215UL, 0x98b4c22d2c98985aUL,
0xa4490e55eda4a4aaUL, 0x285d8850752828a0UL, 0x5cda31b8865c5c6dUL,
0xf8933fed6bf8f8c7UL, 0x8644a411c2868622UL,
], [
0x6018c07830d81818UL, 0x8c2305af46262323UL, 0x3fc67ef991b8c6c6UL,
0x87e8136fcdfbe8e8UL, 0x26874ca113cb8787UL, 0xdab8a9626d11b8b8UL,
0x0401080502090101UL, 0x214f426e9e0d4f4fUL, 0xd836adee6c9b3636UL,
0xa2a6590451ffa6a6UL,
0x6fd2debdb90cd2d2UL, 0xf3f5fb06f70ef5f5UL, 0xf979ef80f2967979UL,
0xa16f5fcede306f6fUL, 0x7e91fcef3f6d9191UL, 0x5552aa07a4f85252UL,
0x9d6027fdc0476060UL, 0xcabc89766535bcbcUL, 0x569baccd2b379b9bUL,
0x028e048c018a8e8eUL, 0xb6a371155bd2a3a3UL, 0x300c603c186c0c0cUL,
0xf17bff8af6847b7bUL,
0xd435b5e16a803535UL,
0x741de8693af51d1dUL, 0xa7e05347ddb3e0e0UL, 0x7bd7f6acb321d7d7UL,
0x2fc25eed999cc2c2UL, 0xb82e6d965c432e2eUL, 0x314b627a96294b4bUL,
0xdffea321e15dfefeUL, 0x41578216aed55757UL, 0x5415a8412abd1515UL,
0xc1779fb6eee87777UL, 0xdc37a5eb6e923737UL, 0xb3e57b56d79ee5e5UL,
0x469f8cd923139f9fUL,
0xe7f0d317fd23f0f0UL,
0x354a6a7f94204a4aUL, 0x4fda9e95a944dadaUL, 0x7d58fa25b0a25858UL,
0x03c906ca8fcfc9c9UL, 0xa429558d527c2929UL, 0x280a5022145a0a0aUL,
0xfeb1e14f7f50b1b1UL, 0xbaa0691a5dc9a0a0UL, 0xb16b7fdad6146b6bUL,
0x2e855cab17d98585UL, 0xcebd8173673cbdbdUL, 0x695dd234ba8f5d5dUL,
0x4010805020901010UL,
0xf7f4f303f507f4f4UL,
0x0bcb16c08bddcbcbUL, 0xf83eedc67cd33e3eUL, 0x140528110a2d0505UL,
0x81671fe6ce786767UL, 0xb7e47353d597e4e4UL, 0x9c2725bb4e022727UL,
0x1941325882734141UL, 0x168b2c9d0ba78b8bUL, 0xa6a7510153f6a7a7UL,
0xe97dcf94fab27d7dUL, 0x6e95dcfb37499595UL, 0x47d88e9fad56d8d8UL,
0xcbfb8b30eb70fbfbUL,
0x9fee2371c1cdeeeeUL,
0xed7cc791f8bb7c7cUL, 0x856617e3cc716666UL, 0x53dda68ea77bddddUL,
0x5c17b84b2eaf1717UL, 0x014702468e454747UL, 0x429e84dc211a9e9eUL,
0x0fca1ec589d4cacaUL, 0xb42d75995a582d2dUL, 0xc6bf9179632ebfbfUL,
0x1c07381b0e3f0707UL, 0x8ead012347acadadUL, 0x755aea2fb4b05a5aUL,
0x36836cb51bef8383UL,
0xcc3385ff66b63333UL,
0x91633ff2c65c6363UL, 0x0802100a04120202UL, 0x92aa39384993aaaaUL,
0xd971afa8e2de7171UL, 0x07c80ecf8dc6c8c8UL, 0x6419c87d32d11919UL,
0x39497270923b4949UL, 0x43d9869aaf5fd9d9UL, 0xeff2c31df931f2f2UL,
0xabe34b48dba8e3e3UL, 0x715be22ab6b95b5bUL, 0x1a8834920dbc8888UL,
0x529aa4c8293e9a9aUL,
0x98262dbe4c0b2626UL,
0xc8328dfa64bf3232UL, 0xfab0e94a7d59b0b0UL, 0x83e91b6acff2e9e9UL,
0x3c0f78331e770f0fUL, 0x73d5e6a6b733d5d5UL, 0x3a8074ba1df48080UL,
0xc2be997c6127bebeUL, 0x13cd26de87ebcdcdUL, 0xd034bde468893434UL,
0x3d487a7590324848UL, 0xdbffab24e354ffffUL, 0xf57af78ff48d7a7aUL,
0x7a90f4ea3d649090UL,
0x615fc23ebe9d5f5fUL,
0x80201da0403d2020UL, 0xbd6867d5d00f6868UL, 0x681ad07234ca1a1aUL,
0x82ae192c41b7aeaeUL, 0xeab4c95e757db4b4UL, 0x4d549a19a8ce5454UL,
0x7693ece53b7f9393UL, 0x88220daa442f2222UL, 0x8d6407e9c8636464UL,
0xe3f1db12ff2af1f1UL, 0xd173bfa2e6cc7373UL, 0x4812905a24821212UL,
0x1d403a5d807a4040UL,
0x2008402810480808UL,
0x2bc356e89b95c3c3UL, 0x97ec337bc5dfececUL, 0x4bdb9690ab4ddbdbUL,
0xbea1611f5fc0a1a1UL, 0x0e8d1c8307918d8dUL, 0xf43df5c97ac83d3dUL,
0x6697ccf1335b9797UL, 0x0000000000000000UL, 0x1bcf36d483f9cfcfUL,
0xac2b4587566e2b2bUL, 0xc57697b3ece17676UL, 0x328264b019e68282UL,
0x7fd6fea9b128d6d6UL,
0x6c1bd87736c31b1bUL,
0xeeb5c15b7774b5b5UL, 0x86af112943beafafUL, 0xb56a77dfd41d6a6aUL,
0x5d50ba0da0ea5050UL, 0x0945124c8a574545UL, 0xebf3cb18fb38f3f3UL,
0xc0309df060ad3030UL, 0x9bef2b74c3c4efefUL, 0xfc3fe5c37eda3f3fUL,
0x4955921caac75555UL, 0xb2a2791059dba2a2UL, 0x8fea0365c9e9eaeaUL,
0x89650fecca6a6565UL,
0xd2bab9686903babaUL,
0xbc2f65935e4a2f2fUL, 0x27c04ee79d8ec0c0UL, 0x5fdebe81a160dedeUL,
0x701ce06c38fc1c1cUL, 0xd3fdbb2ee746fdfdUL, 0x294d52649a1f4d4dUL,
0x7292e4e039769292UL, 0xc9758fbceafa7575UL, 0x1806301e0c360606UL,
0x128a249809ae8a8aUL, 0xf2b2f940794bb2b2UL, 0xbfe66359d185e6e6UL,
0x380e70361c7e0e0eUL,
0x7c1ff8633ee71f1fUL,
0x956237f7c4556262UL, 0x77d4eea3b53ad4d4UL, 0x9aa829324d81a8a8UL,
0x6296c4f431529696UL, 0xc3f99b3aef62f9f9UL, 0x33c566f697a3c5c5UL,
0x942535b14a102525UL, 0x7959f220b2ab5959UL, 0x2a8454ae15d08484UL,
0xd572b7a7e4c57272UL, 0xe439d5dd72ec3939UL, 0x2d4c5a6198164c4cUL,
0x655eca3bbc945e5eUL,
0xfd78e785f09f7878UL,
0xe038ddd870e53838UL, 0x0a8c148605988c8cUL, 0x63d1c6b2bf17d1d1UL,
0xaea5410b57e4a5a5UL, 0xafe2434dd9a1e2e2UL, 0x99612ff8c24e6161UL,
0xf6b3f1457b42b3b3UL, 0x842115a542342121UL, 0x4a9c94d625089c9cUL,
0x781ef0663cee1e1eUL, 0x1143225286614343UL, 0x3bc776fc93b1c7c7UL,
0xd7fcb32be54ffcfcUL,
0x1004201408240404UL,
0x5951b208a2e35151UL, 0x5e99bcc72f259999UL, 0xa96d4fc4da226d6dUL,
0x340d68391a650d0dUL, 0xcffa8335e979fafaUL, 0x5bdfb684a369dfdfUL,
0xe57ed79bfca97e7eUL, 0x90243db448192424UL, 0xec3bc5d776fe3b3bUL,
0x96ab313d4b9aababUL, 0x1fce3ed181f0ceceUL, 0x4411885522991111UL,
0x068f0c8903838f8fUL,
0x254e4a6b9c044e4eUL,
0xe6b7d1517366b7b7UL, 0x8beb0b60cbe0ebebUL, 0xf03cfdcc78c13c3cUL,
0x3e817cbf1ffd8181UL, 0x6a94d4fe35409494UL, 0xfbf7eb0cf31cf7f7UL,
0xdeb9a1676f18b9b9UL, 0x4c13985f268b1313UL, 0xb02c7d9c58512c2cUL,
0x6bd3d6b8bb05d3d3UL, 0xbbe76b5cd38ce7e7UL, 0xa56e57cbdc396e6eUL,
0x37c46ef395aac4c4UL,
0x0c03180f061b0303UL,
0x45568a13acdc5656UL, 0x0d441a49885e4444UL, 0xe17fdf9efea07f7fUL,
0x9ea921374f88a9a9UL, 0xa82a4d8254672a2aUL, 0xd6bbb16d6b0abbbbUL,
0x23c146e29f87c1c1UL, 0x5153a202a6f15353UL, 0x57dcae8ba572dcdcUL,
0x2c0b582716530b0bUL, 0x4e9d9cd327019d9dUL, 0xad6c47c1d82b6c6cUL,
0xc43195f562a43131UL,
0xcd7487b9e8f37474UL,
0xfff6e309f115f6f6UL, 0x05460a438c4c4646UL, 0x8aac092645a5acacUL,
0x1e893c970fb58989UL, 0x5014a04428b41414UL, 0xa3e15b42dfbae1e1UL,
0x5816b04e2ca61616UL, 0xe83acdd274f73a3aUL, 0xb9696fd0d2066969UL,
0x2409482d12410909UL, 0xdd70a7ade0d77070UL, 0xe2b6d954716fb6b6UL,
0x67d0ceb7bd1ed0d0UL,
0x93ed3b7ec7d6ededUL,
0x17cc2edb85e2ccccUL, 0x15422a5784684242UL, 0x5a98b4c22d2c9898UL,
0xaaa4490e55eda4a4UL, 0xa0285d8850752828UL, 0x6d5cda31b8865c5cUL,
0xc7f8933fed6bf8f8UL, 0x228644a411c28686UL,
], [
0x186018c07830d818UL, 0x238c2305af462623UL, 0xc63fc67ef991b8c6UL,
0xe887e8136fcdfbe8UL, 0x8726874ca113cb87UL, 0xb8dab8a9626d11b8UL,
0x0104010805020901UL, 0x4f214f426e9e0d4fUL, 0x36d836adee6c9b36UL,
0xa6a2a6590451ffa6UL,
0xd26fd2debdb90cd2UL, 0xf5f3f5fb06f70ef5UL, 0x79f979ef80f29679UL,
0x6fa16f5fcede306fUL, 0x917e91fcef3f6d91UL, 0x525552aa07a4f852UL,
0x609d6027fdc04760UL, 0xbccabc89766535bcUL, 0x9b569baccd2b379bUL,
0x8e028e048c018a8eUL, 0xa3b6a371155bd2a3UL, 0x0c300c603c186c0cUL,
0x7bf17bff8af6847bUL,
0x35d435b5e16a8035UL,
0x1d741de8693af51dUL, 0xe0a7e05347ddb3e0UL, 0xd77bd7f6acb321d7UL,
0xc22fc25eed999cc2UL, 0x2eb82e6d965c432eUL, 0x4b314b627a96294bUL,
0xfedffea321e15dfeUL, 0x5741578216aed557UL, 0x155415a8412abd15UL,
0x77c1779fb6eee877UL, 0x37dc37a5eb6e9237UL, 0xe5b3e57b56d79ee5UL,
0x9f469f8cd923139fUL,
0xf0e7f0d317fd23f0UL,
0x4a354a6a7f94204aUL, 0xda4fda9e95a944daUL, 0x587d58fa25b0a258UL,
0xc903c906ca8fcfc9UL, 0x29a429558d527c29UL, 0x0a280a5022145a0aUL,
0xb1feb1e14f7f50b1UL, 0xa0baa0691a5dc9a0UL, 0x6bb16b7fdad6146bUL,
0x852e855cab17d985UL, 0xbdcebd8173673cbdUL, 0x5d695dd234ba8f5dUL,
0x1040108050209010UL,
0xf4f7f4f303f507f4UL,
0xcb0bcb16c08bddcbUL, 0x3ef83eedc67cd33eUL, 0x05140528110a2d05UL,
0x6781671fe6ce7867UL, 0xe4b7e47353d597e4UL, 0x279c2725bb4e0227UL,
0x4119413258827341UL, 0x8b168b2c9d0ba78bUL, 0xa7a6a7510153f6a7UL,
0x7de97dcf94fab27dUL, 0x956e95dcfb374995UL, 0xd847d88e9fad56d8UL,
0xfbcbfb8b30eb70fbUL,
0xee9fee2371c1cdeeUL,
0x7ced7cc791f8bb7cUL, 0x66856617e3cc7166UL, 0xdd53dda68ea77bddUL,
0x175c17b84b2eaf17UL, 0x47014702468e4547UL, 0x9e429e84dc211a9eUL,
0xca0fca1ec589d4caUL, 0x2db42d75995a582dUL, 0xbfc6bf9179632ebfUL,
0x071c07381b0e3f07UL, 0xad8ead012347acadUL, 0x5a755aea2fb4b05aUL,
0x8336836cb51bef83UL,
0x33cc3385ff66b633UL,
0x6391633ff2c65c63UL, 0x020802100a041202UL, 0xaa92aa39384993aaUL,
0x71d971afa8e2de71UL, 0xc807c80ecf8dc6c8UL, 0x196419c87d32d119UL,
0x4939497270923b49UL, 0xd943d9869aaf5fd9UL, 0xf2eff2c31df931f2UL,
0xe3abe34b48dba8e3UL, 0x5b715be22ab6b95bUL, 0x881a8834920dbc88UL,
0x9a529aa4c8293e9aUL,
0x2698262dbe4c0b26UL,
0x32c8328dfa64bf32UL, 0xb0fab0e94a7d59b0UL, 0xe983e91b6acff2e9UL,
0x0f3c0f78331e770fUL, 0xd573d5e6a6b733d5UL, 0x803a8074ba1df480UL,
0xbec2be997c6127beUL, 0xcd13cd26de87ebcdUL, 0x34d034bde4688934UL,
0x483d487a75903248UL, 0xffdbffab24e354ffUL, 0x7af57af78ff48d7aUL,
0x907a90f4ea3d6490UL,
0x5f615fc23ebe9d5fUL,
0x2080201da0403d20UL, 0x68bd6867d5d00f68UL, 0x1a681ad07234ca1aUL,
0xae82ae192c41b7aeUL, 0xb4eab4c95e757db4UL, 0x544d549a19a8ce54UL,
0x937693ece53b7f93UL, 0x2288220daa442f22UL, 0x648d6407e9c86364UL,
0xf1e3f1db12ff2af1UL, 0x73d173bfa2e6cc73UL, 0x124812905a248212UL,
0x401d403a5d807a40UL,
0x0820084028104808UL,
0xc32bc356e89b95c3UL, 0xec97ec337bc5dfecUL, 0xdb4bdb9690ab4ddbUL,
0xa1bea1611f5fc0a1UL, 0x8d0e8d1c8307918dUL, 0x3df43df5c97ac83dUL,
0x976697ccf1335b97UL, 0x0000000000000000UL, 0xcf1bcf36d483f9cfUL,
0x2bac2b4587566e2bUL, 0x76c57697b3ece176UL, 0x82328264b019e682UL,
0xd67fd6fea9b128d6UL,
0x1b6c1bd87736c31bUL,
0xb5eeb5c15b7774b5UL, 0xaf86af112943beafUL, 0x6ab56a77dfd41d6aUL,
0x505d50ba0da0ea50UL, 0x450945124c8a5745UL, 0xf3ebf3cb18fb38f3UL,
0x30c0309df060ad30UL, 0xef9bef2b74c3c4efUL, 0x3ffc3fe5c37eda3fUL,
0x554955921caac755UL, 0xa2b2a2791059dba2UL, 0xea8fea0365c9e9eaUL,
0x6589650fecca6a65UL,
0xbad2bab9686903baUL,
0x2fbc2f65935e4a2fUL, 0xc027c04ee79d8ec0UL, 0xde5fdebe81a160deUL,
0x1c701ce06c38fc1cUL, 0xfdd3fdbb2ee746fdUL, 0x4d294d52649a1f4dUL,
0x927292e4e0397692UL, 0x75c9758fbceafa75UL, 0x061806301e0c3606UL,
0x8a128a249809ae8aUL, 0xb2f2b2f940794bb2UL, 0xe6bfe66359d185e6UL,
0x0e380e70361c7e0eUL,
0x1f7c1ff8633ee71fUL,
0x62956237f7c45562UL, 0xd477d4eea3b53ad4UL, 0xa89aa829324d81a8UL,
0x966296c4f4315296UL, 0xf9c3f99b3aef62f9UL, 0xc533c566f697a3c5UL,
0x25942535b14a1025UL, 0x597959f220b2ab59UL, 0x842a8454ae15d084UL,
0x72d572b7a7e4c572UL, 0x39e439d5dd72ec39UL, 0x4c2d4c5a6198164cUL,
0x5e655eca3bbc945eUL,
0x78fd78e785f09f78UL,
0x38e038ddd870e538UL, 0x8c0a8c148605988cUL, 0xd163d1c6b2bf17d1UL,
0xa5aea5410b57e4a5UL, 0xe2afe2434dd9a1e2UL, 0x6199612ff8c24e61UL,
0xb3f6b3f1457b42b3UL, 0x21842115a5423421UL, 0x9c4a9c94d625089cUL,
0x1e781ef0663cee1eUL, 0x4311432252866143UL, 0xc73bc776fc93b1c7UL,
0xfcd7fcb32be54ffcUL,
0x0410042014082404UL,
0x515951b208a2e351UL, 0x995e99bcc72f2599UL, 0x6da96d4fc4da226dUL,
0x0d340d68391a650dUL, 0xfacffa8335e979faUL, 0xdf5bdfb684a369dfUL,
0x7ee57ed79bfca97eUL, 0x2490243db4481924UL, 0x3bec3bc5d776fe3bUL,
0xab96ab313d4b9aabUL, 0xce1fce3ed181f0ceUL, 0x1144118855229911UL,
0x8f068f0c8903838fUL,
0x4e254e4a6b9c044eUL,
0xb7e6b7d1517366b7UL, 0xeb8beb0b60cbe0ebUL, 0x3cf03cfdcc78c13cUL,
0x813e817cbf1ffd81UL, 0x946a94d4fe354094UL, 0xf7fbf7eb0cf31cf7UL,
0xb9deb9a1676f18b9UL, 0x134c13985f268b13UL, 0x2cb02c7d9c58512cUL,
0xd36bd3d6b8bb05d3UL, 0xe7bbe76b5cd38ce7UL, 0x6ea56e57cbdc396eUL,
0xc437c46ef395aac4UL,
0x030c03180f061b03UL,
0x5645568a13acdc56UL, 0x440d441a49885e44UL, 0x7fe17fdf9efea07fUL,
0xa99ea921374f88a9UL, 0x2aa82a4d8254672aUL, 0xbbd6bbb16d6b0abbUL,
0xc123c146e29f87c1UL, 0x535153a202a6f153UL, 0xdc57dcae8ba572dcUL,
0x0b2c0b582716530bUL, 0x9d4e9d9cd327019dUL, 0x6cad6c47c1d82b6cUL,
0x31c43195f562a431UL,
0x74cd7487b9e8f374UL,
0xf6fff6e309f115f6UL, 0x4605460a438c4c46UL, 0xac8aac092645a5acUL,
0x891e893c970fb589UL, 0x145014a04428b414UL, 0xe1a3e15b42dfbae1UL,
0x165816b04e2ca616UL, 0x3ae83acdd274f73aUL, 0x69b9696fd0d20669UL,
0x092409482d124109UL, 0x70dd70a7ade0d770UL, 0xb6e2b6d954716fb6UL,
0xd067d0ceb7bd1ed0UL,
0xed93ed3b7ec7d6edUL,
0xcc17cc2edb85e2ccUL, 0x4215422a57846842UL, 0x985a98b4c22d2c98UL,
0xa4aaa4490e55eda4UL, 0x28a0285d88507528UL, 0x5c6d5cda31b8865cUL,
0xf8c7f8933fed6bf8UL, 0x86228644a411c286UL,
]];
immutable ulong[numRounds] rc = [
0x1823c6e887b8014fUL, 0x36a6d2f5796f9152UL, 0x60bc9b8ea30c7b35UL,
0x1de0d7c22e4bfe57UL, 0x157737e59ff04adaUL, 0x58c9290ab1a06b85UL,
0xbd5d10f4cb3e0567UL, 0xe427418ba77d95d8UL, 0xfbee7c66dd17479eUL, 0xca2dbf07ad5a8333UL,
];
// precomputed K[] based on the initial state
immutable ulong[8][numRounds] pcK = [
[
0x300BEEC0AF902967, 0x2828282828282828, 0x2828282828282828, 0x2828282828282828,
0x2828282828282828, 0x2828282828282828, 0x2828282828282828, 0x2828282828282828
], [
0x3BAB89F8EAD1AE24, 0x4445456645E9CBAF, 0x70FEA4A4C5A4B289, 0xC5FAA9E1E1CCE1A0,
0x48ACC05CFCFCB8FC, 0x8FF70E26908F8F69, 0x96791407D7857979, 0xF8A8F868B8C878F8
], [
0xD319BFDB30467058, 0x295B23D1AFCF37DB, 0x12C8AC28B95AC98, 0x81639EB1C0B206A7,
0x445E607AB0B209DB, 0x735B2CCFBC8CBC71, 0xDC670924EFEDDDD3, 0x7B8D3BF0D73B7D19
], [
0x38BEAAC1DE116586, 0x687CF3D04A87337F, 0xF337FADB98ADF057, 0xC5E24258EE358DBC,
0x1109F0E8996E247E, 0x1C5D6ED10B03401, 0xFBC952F17B28ECD3, 0x3256DC0CC7F12740
], [
0xAF25A520949BCF14, 0xC13626A9E3C4534D, 0xE60F7D867740F9E1, 0x915DE6BBE26A0629,
0x965A54CC4CFE5E8D, 0xBEE931CB62323AA6, 0xB17B591896846A47, 0xD4F0C9362759AF31
], [
0xE2F9B5C025370BB0, 0x392BCBA2168494A5, 0x608AF8CEFA348C14, 0x7AA53764418C9219,
0xB3F346A1FA833F89, 0x97493F487802CF7C, 0xDCADE8BA1E008F23, 0x92774F49EDB0323D
], [
0x75416382774DFF2F, 0xFFFA38D055034600, 0xBF7D02493E98F361, 0xF4A860C29AE5CE0B,
0xC8DF5A44EE5D9D27, 0x23F45A55047500A4, 0xB016101202F9E28C, 0xAC30CD296833331D
], [
0x36BF1826884AD89, 0x9940C662D8467163, 0x4C433E174B19C210, 0xE29CCFD34CFF86C5,
0x21FF11A042DF2653, 0x1B8E00CB6CE44B13, 0xA6123BF7A347B7CE, 0xD918900E3B2833CA
], [
0xD01C677A0A9A2CF9, 0x2A942F534A63B6B2, 0x88422246FEACA8B4, 0x474A5CC73D583559,
0x74A6925DA55C6FA1, 0x7717E68CC4735C39, 0x82A3B0B53EC1AC6, 0x2AF658EB814DE762
], [
0x489548B601EEBC3A, 0xA50D6BC66BED8E81, 0xE0CE3DCF88265A75, 0xC28C4ADBC0F69CE9,
0x54B79CD57F718513, 0x43414B8A977D0B7B, 0x631935BBDBF6157A, 0x6A7A4EF637018227
],];
version(unittest)
{
import std.conv : hexString;
}
|
D
|
/Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/DatabaseKit.build/Database/Database.swift.o : /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/Deprecated.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/KeyedCache.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/DatabaseKeyedCache.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/DictionaryKeyedCache.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/MemoryKeyedCache.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/DatabaseConnectionPoolCache.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/DatabaseStringFindable.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/DatabaseConnectable.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Database/DatabaseQueryable.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/URL+DatabaseName.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Database/Database.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Database/ConfiguredDatabase.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Database/DatabaseConfig.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/DatabaseConnectionPoolConfig.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/KeyedCacheSupporting.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Log/LogSupporting.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Log/DatabaseLog.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/Container+ConnectionPool.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/DatabaseConnectionPool.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/Container+CachedConnection.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/DatabaseConnection.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/Container+NewConnection.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Service/DatabaseKitProvider.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Log/DatabaseLogger.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Database/DatabaseIdentifier.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Log/DatabaseLogHandler.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Log/PrintLogHandler.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/DatabaseKitError.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Database/Databases.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/Exports.swift /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/XPC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Swift.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/IOKit.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-macos.swiftinterface /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/Service.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/swift-nio-zlib-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/DatabaseKit.build/Database/Database~partial.swiftmodule : /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/Deprecated.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/KeyedCache.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/DatabaseKeyedCache.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/DictionaryKeyedCache.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/MemoryKeyedCache.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/DatabaseConnectionPoolCache.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/DatabaseStringFindable.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/DatabaseConnectable.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Database/DatabaseQueryable.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/URL+DatabaseName.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Database/Database.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Database/ConfiguredDatabase.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Database/DatabaseConfig.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/DatabaseConnectionPoolConfig.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/KeyedCacheSupporting.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Log/LogSupporting.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Log/DatabaseLog.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/Container+ConnectionPool.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/DatabaseConnectionPool.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/Container+CachedConnection.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/DatabaseConnection.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/Container+NewConnection.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Service/DatabaseKitProvider.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Log/DatabaseLogger.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Database/DatabaseIdentifier.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Log/DatabaseLogHandler.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Log/PrintLogHandler.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/DatabaseKitError.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Database/Databases.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/Exports.swift /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/XPC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Swift.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/IOKit.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-macos.swiftinterface /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/Service.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/swift-nio-zlib-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/DatabaseKit.build/Database/Database~partial.swiftdoc : /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/Deprecated.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/KeyedCache.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/DatabaseKeyedCache.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/DictionaryKeyedCache.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/MemoryKeyedCache.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/DatabaseConnectionPoolCache.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/DatabaseStringFindable.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/DatabaseConnectable.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Database/DatabaseQueryable.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/URL+DatabaseName.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Database/Database.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Database/ConfiguredDatabase.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Database/DatabaseConfig.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/DatabaseConnectionPoolConfig.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/KeyedCacheSupporting.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Log/LogSupporting.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Log/DatabaseLog.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/Container+ConnectionPool.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/DatabaseConnectionPool.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/Container+CachedConnection.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/DatabaseConnection.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/Container+NewConnection.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Service/DatabaseKitProvider.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Log/DatabaseLogger.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Database/DatabaseIdentifier.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Log/DatabaseLogHandler.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Log/PrintLogHandler.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/DatabaseKitError.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Database/Databases.swift /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/Exports.swift /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/XPC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Swift.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/IOKit.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-macos.swiftinterface /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/Service.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/weirujian/Desktop/WeiRuJian/Vapor/AuthServer/.build/checkouts/swift-nio-zlib-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
|
D
|
of or relating to a paramagnet
|
D
|
//#fileifdef MC152
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stanhebben.minetweaker.mods.ic2.actions;
import ic2.api.recipe.Recipes;
import net.minecraft.item.ItemStack;
import stanhebben.minetweaker.api.IUndoableAction;
/**
*
* @author Stanneke
*/
public class CompressorRemoveRecipeAction implements IUndoableAction {
private ItemStack input;
private ItemStack output;
public CompressorRemoveRecipeAction(ItemStack input) {
this.input = input;
output = Recipes.compressor.getRecipes().get(input);
}
public void apply() {
Recipes.compressor.getRecipes().remove(input);
}
public boolean canUndo() {
return true;
}
public void undo() {
Recipes.compressor.getRecipes().put(input, output);
}
public String describe() {
return "Removing a compressor recipe for " + output.getDisplayName();
}
public String describeUndo() {
return "Restoring a compressor recipe for " + output.getDisplayName();
}
}
|
D
|
version https://git-lfs.github.com/spec/v1
oid sha256:86b3da6e5476e5f713e78027a7f557db3e49f789d9e661926831f6e0a42b00af
size 300
|
D
|
/*
* Copyright (c) 2004-2015 Derelict Developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the names 'Derelict', 'DerelictSDL', nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
module derelict.cocoa.foundation;
version(OSX):
import std.string;
import std.utf;
import derelict.util.loader;
import derelict.util.system;
import derelict.cocoa.runtime;
// NSZone
extern (C) nothrow @nogc
{
alias void* function(NSUInteger bytes) pfNSAllocateMemoryPages;
alias void function (void* ptr, NSUInteger bytes) pfNSDeallocateMemoryPages;
alias void function(id format, ...) pfNSLog;
}
__gshared
{
pfNSDeallocateMemoryPages NSDeallocateMemoryPages;
pfNSAllocateMemoryPages NSAllocateMemoryPages;
pfNSLog NSLog;
}
__gshared
{
NSString NSDefaultRunLoopMode;
NSString NSRunLoopCommonModes;
}
alias NSTimeInterval = double;
// Mixin'd by all Cocoa objects
mixin template NSObjectTemplate(T, string className)
{
// create from an id
this (id id_) nothrow @nogc
{
this._id = id_;
}
/// Allocates, but do not init
static T alloc()
{
alias fun_t = extern(C) id function (id obj, SEL sel);
return T( (cast(fun_t)objc_msgSend)(getClassID(), sel!"alloc") );
}
static Class getClass() nothrow
{
return cast(Class)( lazyClass!className() );
}
static id getClassID() nothrow
{
return lazyClass!className();
}
}
struct NSObject
{
// The only field available in all NSObject hierarchy
// That makes all these destructs idempotent with an id,
// and the size of a pointer.
id _id = null;
// Subtype id
bool opCast()
{
return _id != null;
}
mixin NSObjectTemplate!(NSObject, "NSObject");
~this()
{
}
NSObject init_()
{
alias fun_t = extern(C) id function (id, const(SEL));
id result = (cast(fun_t)objc_msgSend)(_id, sel!"init");
return NSObject(result);
}
void retain()
{
alias fun_t = extern(C) void function (id, const(SEL));
(cast(fun_t)objc_msgSend)(_id, sel!"retain");
}
void release()
{
alias fun_t = extern(C) void function (id, const(SEL));
(cast(fun_t)objc_msgSend)(_id, sel!"release");
}
}
struct NSData
{
NSObject parent;
alias parent this;
mixin NSObjectTemplate!(NSData, "NSData");
static NSData data()
{
alias fun_t = extern(C) id function (id obj, const(SEL) sel);
id result = (cast(fun_t)objc_msgSend)(getClassID(), sel!"data");
return NSData(result);
}
static NSData dataWithBytesNoCopy(void* bytes, NSUInteger length, bool freeWhenDone)
{
alias fun_t = extern(C) id function(id, const(SEL), void*, NSUInteger, BOOL);
id result = (cast(fun_t)objc_msgSend)(getClassID(), sel!"dataWithBytesNoCopy:length:freeWhenDone:",
bytes, length, freeWhenDone ? YES : NO);
return NSData(result);
}
}
struct NSString
{
NSObject parent;
alias parent this;
mixin NSObjectTemplate!(NSString, "NSString");
static NSString stringWith (string str)
{
alias fun_t = extern(C) id function(id, SEL, const(wchar)*, NSUInteger);
id result = (cast(fun_t)objc_msgSend)(getClassID(), sel!"stringWithCharacters:length:",
str.toUTF16z(), cast(NSUInteger)(str.length));
return NSString(result);
}
string toString()
{
return fromStringz(UTF8String()).idup;
}
size_t length ()
{
alias fun_t = extern(C) NSUInteger function(id, SEL);
return cast(size_t)( (cast(fun_t)objc_msgSend)(_id, sel!"length") );
}
char* UTF8String ()
{
alias fun_t = extern(C) char* function(id, SEL);
return (cast(fun_t)objc_msgSend)(_id, sel!"UTF8String");
}
void getCharacters (wchar* buffer, NSRange range)
{
alias fun_t = extern(C) void function(id, SEL, wchar*, NSRange);
(cast(fun_t)objc_msgSend)(_id, sel!"getCharacters:range:", buffer, range);
}
NSString stringWithCharacters (wchar* chars, size_t length)
{
alias fun_t = extern(C) id function(id, SEL, wchar*, NSUInteger);
id result = (cast(fun_t)objc_msgSend)(_id, sel!"stringWithCharacters:length:", chars, cast(NSUInteger)length);
return NSString(result);
}
NSRange rangeOfString (NSString aString)
{
alias fun_t = extern(C) NSRange function(id, SEL, id);
return (cast(fun_t)objc_msgSend)(_id, sel!"rangeOfString", aString._id);
}
NSString stringByAppendingString (NSString aString)
{
alias fun_t = extern(C) id function(id, SEL, id);
id result = (cast(fun_t)objc_msgSend)(_id, sel!"stringByAppendingString:", aString._id);
return NSString(result);
}
}
struct NSURL
{
NSObject parent;
alias parent this;
mixin NSObjectTemplate!(NSURL, "NSURL");
static NSURL URLWithString(NSString str)
{
alias fun_t = extern(C) id function(id, SEL, id);
id result = (cast(fun_t)objc_msgSend)(getClassID(), sel!"URLWithString:", str._id);
return NSURL(result);
}
}
struct NSEnumerator
{
NSObject parent;
alias parent this;
mixin NSObjectTemplate!(NSEnumerator, "NSEnumerator");
id nextObject ()
{
alias fun_t = extern(C) id function(id, SEL);
return (cast(fun_t)objc_msgSend)(_id, sel!"nextObject");
}
}
struct NSArray
{
NSObject parent;
alias parent this;
mixin NSObjectTemplate!(NSArray, "NSArray");
NSEnumerator objectEnumerator ()
{
alias fun_t = extern(C) id function(id, SEL);
id result = (cast(fun_t)objc_msgSend)(_id, sel!"objectEnumerator");
return NSEnumerator(result);
}
}
struct NSProcessInfo
{
NSObject parent;
alias parent this;
mixin NSObjectTemplate!(NSProcessInfo, "NSProcessInfo");
static NSProcessInfo processInfo ()
{
alias fun_t = extern(C) id function(id, SEL);
id result = (cast(fun_t)objc_msgSend)(lazyClass!"NSProcessInfo", sel!"processInfo");
return NSProcessInfo(result);
}
NSString processName ()
{
alias fun_t = extern(C) id function(id, SEL);
id result = (cast(fun_t)objc_msgSend)(_id, sel!"processName");
return NSString(result);
}
}
struct NSNotification
{
NSObject parent;
alias parent this;
mixin NSObjectTemplate!(NSNotification, "NSNotification");
}
struct NSDictionary
{
NSObject parent;
alias parent this;
mixin NSObjectTemplate!(NSDictionary, "NSDictionary");
id objectForKey(id key)
{
alias fun_t = extern(C) id function(id, SEL, id);
id result = (cast(fun_t)objc_msgSend)(_id, sel!"objectForKey:", key);
return result;
}
}
struct NSAutoreleasePool
{
NSObject parent;
alias parent this;
mixin NSObjectTemplate!(NSAutoreleasePool, "NSAutoreleasePool");
}
enum : int
{
NSFileErrorMaximum = 1023,
NSFileErrorMinimum = 0,
NSFileLockingError = 255,
NSFileNoSuchFileError = 4,
NSFileReadCorruptFileError = 259,
NSFileReadInapplicableStringEncodingError = 261,
NSFileReadInvalidFileNameError = 258,
NSFileReadNoPermissionError = 257,
NSFileReadNoSuchFileError = 260,
NSFileReadUnknownError = 256,
NSFileReadUnsupportedSchemeError = 262,
NSFileWriteInapplicableStringEncodingError = 517,
NSFileWriteInvalidFileNameError = 514,
NSFileWriteNoPermissionError = 513,
NSFileWriteOutOfSpaceError = 640,
NSFileWriteUnknownError = 512,
NSFileWriteUnsupportedSchemeError = 518,
NSFormattingError = 2048,
NSFormattingErrorMaximum = 2559,
NSFormattingErrorMinimum = 2048,
NSKeyValueValidationError = 1024,
NSUserCancelledError = 3072,
NSValidationErrorMaximum = 2047,
NSValidationErrorMinimum = 1024,
NSExecutableArchitectureMismatchError = 3585,
NSExecutableErrorMaximum = 3839,
NSExecutableErrorMinimum = 3584,
NSExecutableLinkError = 3588,
NSExecutableLoadError = 3587,
NSExecutableNotLoadableError = 3584,
NSExecutableRuntimeMismatchError = 3586,
NSFileReadTooLargeError = 263,
NSFileReadUnknownStringEncodingError = 264,
GSFoundationPlaceHolderError = 9999
}
struct NSError
{
NSObject parent;
alias parent this;
mixin NSObjectTemplate!(NSError, "NSError");
NSString localizedDescription()
{
alias fun_t = extern(C) id function(id, SEL);
id res = (cast(fun_t)objc_msgSend)(_id, sel!"localizedDescription");
return NSString(res);
}
}
struct NSBundle
{
NSObject parent;
alias parent this;
mixin NSObjectTemplate!(NSBundle, "NSBundle");
void initWithPath(NSString path)
{
alias fun_t = extern(C) void function(id, SEL, id);
(cast(fun_t)objc_msgSend)(_id, sel!"initWithPath:", path._id);
}
bool load()
{
alias fun_t = extern(C) BOOL function(id, SEL);
return (cast(fun_t)objc_msgSend)(_id, sel!"load") != NO;
}
bool unload()
{
alias fun_t = extern(C) BOOL function(id, SEL);
return (cast(fun_t)objc_msgSend)(_id, sel!"unload") != NO;
}
bool loadAndReturnError(NSError error)
{
alias fun_t = extern(C) BOOL function(id, SEL, id);
return (cast(fun_t)objc_msgSend)(_id, sel!"loadAndReturnError:", error._id) != NO;
}
}
struct NSTimer
{
NSObject parent;
alias parent this;
mixin NSObjectTemplate!(NSTimer, "NSTimer");
static NSTimer timerWithTimeInterval(double seconds, NSObject target, SEL selector, void* userInfo, bool repeats)
{
alias fun_t = extern(C) id function(id, SEL, double, id, SEL, id, BOOL);
id result = (cast(fun_t)objc_msgSend)(getClassID(), sel!"timerWithTimeInterval:target:selector:userInfo:repeats:",
seconds, target._id, selector, cast(id)userInfo, repeats ? YES : NO);
return NSTimer(result);
}
void invalidate()
{
alias fun_t = extern(C) void function(id, SEL);
(cast(fun_t)objc_msgSend)(_id, sel!"invalidate");
}
}
struct NSRunLoop
{
NSObject parent;
alias parent this;
mixin NSObjectTemplate!(NSRunLoop, "NSRunLoop");
static NSRunLoop currentRunLoop()
{
alias fun_t = extern(C) id function(id, SEL);
id result = (cast(fun_t)objc_msgSend)(getClassID(), sel!"currentRunLoop");
return NSRunLoop(result);
}
void addTimer(NSTimer aTimer, NSString forMode)
{
alias fun_t = extern(C) void function(id, SEL, id, id);
(cast(fun_t)objc_msgSend)(_id, sel!"addTimer:forMode:", aTimer._id, forMode._id);
}
}
struct NSDate
{
NSObject parent;
alias parent this;
mixin NSObjectTemplate!(NSDate, "NSDate");
static NSDate date()
{
return NSDate(objc_msgSend(getClassID(), sel!"date"));
}
static NSTimeInterval timeIntervalSinceReferenceDate()
{
alias fun_t = extern(C) NSTimeInterval function(id, SEL);
version(X86)
return (cast(fun_t)objc_msgSend_fpret)(getClassID(), sel!"timeIntervalSinceReferenceDate");
else version(X86_64)
return (cast(fun_t)objc_msgSend)(getClassID(), sel!"timeIntervalSinceReferenceDate");
else
static assert(false);
}
}
|
D
|
instance Grd_612_Gardist (Npc_Default)
{
//-------- primary data --------
name = "Pinto";
npctype = npctype_guard;
guild = GIL_GRD;
level = 25;
voice = 6;
id = 612;
//-------- abilities --------
attribute[ATR_STRENGTH] = 80;
attribute[ATR_DEXTERITY] = 120;
attribute[ATR_MANA_MAX] = 0;
attribute[ATR_MANA] = 0;
attribute[ATR_HITPOINTS_MAX]= 380;
attribute[ATR_HITPOINTS] = 380;
//-------- visuals --------
// animations
Mdl_SetVisual (self,"HUMANS.MDS");
Mdl_ApplyOverlayMds (self,"Humans_Militia.mds");
// body mesh ,bdytex,skin,head mesh ,headtex,teethtex,ruestung
Mdl_SetVisualBody (self,"hum_body_Naked0",0,1,"Hum_Head_Bald",10,1,GRD_ARMOR_L);
B_Scale (self);
Mdl_SetModelFatness(self,0);
fight_tactic = FAI_HUMAN_STRONG;
//-------- Talente --------
Npc_SetTalentSkill (self,NPC_TALENT_1H,2);
Npc_SetTalentSkill (self,NPC_TALENT_2H,1);
Npc_SetTalentSkill (self,NPC_TALENT_BOW,2);
//-------- inventory --------
EquipItem (self,GRD_MW_02);
EquipItem (self,GRD_RW_02);
CreateInvItems (self,ItAmBolt,30);
CreateInvItem (self,ItFoCheese);
CreateInvItem (self,ItFoApple);
CreateInvItem (self,ItLsTorch);
//-------------Daily Routine-------------
/*B_InitNPCAddins(self);*/ daily_routine = Rtn_prestart_612;
};
FUNC VOID Rtn_start_612 ()
{
TA_Boss (06,00,23,00,"NC_EN_ONGATE_BACK");
TA_Sleep (23,00,06,00,"NC_EN_BARACK_SMALLTALK");
};
FUNC VOID Rtn_prestart_612 ()
{
TA_Smalltalk (07,00,23,00,"NC_EN_PATH1_01");
TA_Smalltalk (23,00,07,00,"NC_EN_PATH1_01");
};
FUNC VOID Rtn_fight_612 ()
{
TA_Boss (07,00,23,00,"NC_EN_MAINPATH_04");
TA_Boss (23,00,07,00,"NC_EN_MAINPATH_04");
};
FUNC VOID Rtn_wait_612 ()
{
TA_Boss (06,00,22,00,"NC_EN_ONGATE_BACK");
TA_Stand (22,00,04,00,"NC_EN_MAINHALL1_02");
TA_Sleep (04,00,06,00,"NC_EN_BARACK_SMALLTALK");
};
|
D
|
import std.exception : assumeUnique;
import std.conv : text;
import std.range : take, chain, drop;
import std.string : startsWith, replace;
import std.format : formattedWrite, format;
import std.uni : asCapitalized;
import std.json;
import std.getopt;
import std.file : readText;
import std.stdio;
bool keepDeco = false;
void usage()
{
writeln("Usage: santize_json [--keep-deco] <input-json> [<output-json>]");
}
int main(string[] args)
{
getopt(args,
"keep-deco", &keepDeco);
args = args[1 .. $];
if (args.length == 0)
{
usage();
return 1;
}
string inFilename = args[0];
File outFile;
if(args.length == 1)
{
outFile = stdout;
}
else if(args.length == 2)
{
outFile = File(args[1], "w");
}
else
{
writeln("Error: too many command line arguments");
return 1;
}
auto json = parseJSON(readText(inFilename));
sanitize(json);
outFile.write(json.toJSON(true, JSONOptions.doNotEscapeSlashes));
return 0;
}
string capitalize(string s)
{
return text(s.take(1).asCapitalized.chain(s.drop(1)));
}
void sanitize(JSONValue root)
{
if (root.type == JSON_TYPE.ARRAY)
{
sanitizeSyntaxNode(root);
}
else
{
assert(root.type == JSON_TYPE.OBJECT);
auto rootObject = root.object;
static foreach (name; ["compilerInfo", "buildInfo", "semantics"])
{{
auto node = rootObject.get(name, JSONValue.init);
if (node.type != JSON_TYPE.NULL)
{
mixin("sanitize" ~ name.capitalize ~ "(node.object);");
}
}}
{
auto modules = rootObject.get("modules", JSONValue.init);
if (modules.type != JSON_TYPE.NULL)
{
sanitizeSyntaxNode(modules);
}
}
}
}
void removeString(JSONValue* value)
{
assert(value.type == JSON_TYPE.STRING);
*value = JSONValue("VALUE_REMOVED_FOR_TEST");
}
void removeNumber(JSONValue* value)
{
assert(value.type == JSON_TYPE.INTEGER || value.type == JSON_TYPE.UINTEGER);
*value = JSONValue(0);
}
void removeStringIfExists(JSONValue* value)
{
if (value !is null)
removeString(value);
}
void sanitizeCompilerInfo(ref JSONValue[string] buildInfo)
{
removeString(&buildInfo["binary"]);
removeString(&buildInfo["version"]);
}
void sanitizeBuildInfo(ref JSONValue[string] buildInfo)
{
removeString(&buildInfo["cwd"]);
removeStringIfExists("config" in buildInfo);
removeStringIfExists("lib" in buildInfo);
{
auto importPaths = buildInfo["importPaths"].array;
foreach(ref path; importPaths)
{
path = JSONValue(normalizeFile(path.str));
}
}
}
void sanitizeSyntaxNode(ref JSONValue value)
{
if (value.type == JSON_TYPE.ARRAY)
{
foreach (ref element; value.array)
{
sanitizeSyntaxNode(element);
}
}
else if(value.type == JSON_TYPE.OBJECT)
{
foreach (name; value.object.byKey)
{
if (name == "file")
removeString(&value.object[name]);
else if (name == "offset")
removeNumber(&value.object[name]);
else if (!keepDeco && name == "deco")
removeString(&value.object[name]);
else
sanitizeSyntaxNode(value.object[name]);
}
}
}
string getOptionalString(ref JSONValue[string] obj, string name)
{
auto node = obj.get(name, JSONValue.init);
if (node.type == JSON_TYPE.NULL)
return null;
assert(node.type == JSON_TYPE.STRING, format("got %s where STRING was expected", node.type));
return node.str;
}
void sanitizeSemantics(ref JSONValue[string] semantics)
{
import std.array : appender;
auto modulesArrayPtr = &semantics["modules"].array();
auto newModules = appender!(JSONValue[])();
foreach (ref semanticModuleNode; *modulesArrayPtr)
{
auto semanticModule = semanticModuleNode.object();
auto moduleName = semanticModule.getOptionalString("name");
if(moduleName.startsWith("std.", "core.", "etc.") || moduleName == "object")
{
// remove druntime/phobos modules since they can change for each
// platform
continue;
}
auto fileNode = &semanticModule["file"];
*fileNode = JSONValue(normalizeFile(fileNode.str));
newModules.put(JSONValue(semanticModule));
}
*modulesArrayPtr = newModules.data;
}
auto normalizeFile(string file)
{
version(Windows)
return file.replace("\\", "/");
return file;
}
|
D
|
/*
* Copyright 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module ndk_helper.shader;
import core.stdc.stdlib : malloc, free;
import GLES2.gl2;
import ndk_helper.JNIHelper : JNIHelper, LOGI;
enum DEBUG = true;
/******************************************************************
* CompileShader() with vector
*
* arguments:
* out: shader, shader variable
* in: type, shader type (i.e. GL_VERTEX_SHADER/GL_FRAGMENT_SHADER)
* in: data, source vector
* return: true if a shader compilation succeeded, false if it failed
*
*/
bool CompileShader( GLuint *shader, const GLenum type, ref ubyte[] data )
{
if( !data.length )
return false;
const(GLchar)*source = cast(GLchar *) &data[0];
int iSize = data.length;
return CompileShader( shader, type, source, iSize );
}
/******************************************************************
* CompileShader() with buffer
*
* arguments:
* out: shader, shader variable
* in: type, shader type (i.e. GL_VERTEX_SHADER/GL_FRAGMENT_SHADER)
* in: source, source buffer
* in: iSize, buffer size
* return: true if a shader compilation succeeded, false if it failed
*
*/
bool CompileShader( GLuint *shader,
const GLenum type,
const(GLchar)*source,
const int iSize )
{
if( source == null || iSize <= 0 )
return false;
*shader = glCreateShader( type );
glShaderSource( *shader, 1, &source, &iSize ); //Not specifying 3rd parameter (size) could be troublesome..
glCompileShader( *shader );
static if (DEBUG)
{
GLint logLength;
glGetShaderiv( *shader, GL_INFO_LOG_LENGTH, &logLength );
if( logLength > 0 )
{
GLchar *log = cast(GLchar *) malloc( logLength );
glGetShaderInfoLog( *shader, logLength, &logLength, log );
LOGI( "Shader compile log:\n%s", log );
free( log );
}
}
GLint status;
glGetShaderiv( *shader, GL_COMPILE_STATUS, &status );
if( status == 0 )
{
glDeleteShader( *shader );
return false;
}
return true;
}
/******************************************************************
* CompileShader() with filename
*
* arguments:
* out: shader, shader variable
* in: type, shader type (i.e. GL_VERTEX_SHADER/GL_FRAGMENT_SHADER)
* in: strFilename, filename
* return: true if a shader compilation succeeded, false if it failed
*
*/
bool CompileShader( GLuint *shader, const GLenum type, const(char)*strFileName )
{
ubyte[] data;
bool b = JNIHelper.GetInstance().ReadFile( strFileName, &data );
if( !b )
{
LOGI( "Can not open a file:%s", strFileName );
return false;
}
return CompileShader( shader, type, data );
}
/******************************************************************
* CompileShader() with map_parameters helps patching on a shader on the fly.
*
* arguments:
* out: shader, shader variable
* in: type, shader type (i.e. GL_VERTEX_SHADER/GL_FRAGMENT_SHADER)
* in: mapParameters
* For a example,
* map : %KEY% -> %VALUE% replaces all %KEY% entries in the given shader code to %VALUE"
* return: true if a shader compilation succeeded, false if it failed
*
*/
bool CompileShader( GLuint *shader,
const GLenum type,
const(char)*str_file_name,
ref const string[string] map_parameters )
{
import std.conv : to;
ubyte[] data;
if( !JNIHelper.GetInstance().ReadFile( str_file_name, &data ) )
{
LOGI( "Can not open a file:%s", str_file_name );
return false;
}
const char REPLACEMENT_TAG = '*';
//Fill-in parameters
string str = to!string(data);
char[] str_replacement_map = new char[data.length];
str_replacement_map[] = ' ';
/* maybe port later
while( it != itEnd )
{
size_t pos = 0;
while( (pos = str.find( it->first, pos )) != std::string::npos )
{
//Check if the sub string is already touched
size_t replaced_pos = str_replacement_map.find( REPLACEMENT_TAG, pos );
if( replaced_pos == std::string::npos || replaced_pos > pos )
{
str.replace( pos, it->first.length(), it->second );
str_replacement_map.replace( pos, it->first.length(), it->first.length(),
REPLACEMENT_TAG );
pos += it->second.length();
}
else
{
//The replacement target has been touched by other tag, skipping them
pos += it->second.length();
}
}
it++;
}*/
LOGI( "Patched Shader:\n%s", str );
ubyte[] v = cast(ubyte[])str;
return CompileShader( shader, type, v );
}
/******************************************************************
* LinkProgram()
*
* arguments:
* in: program, program
* return: true if a shader linkage succeeded, false if it failed
*
*/
bool LinkProgram( const GLuint prog )
{
GLint status;
glLinkProgram( prog );
static if (DEBUG)
{
GLint logLength;
glGetProgramiv( prog, GL_INFO_LOG_LENGTH, &logLength );
if( logLength > 0 )
{
GLchar *log = cast(GLchar *) malloc( logLength );
glGetProgramInfoLog( prog, logLength, &logLength, log );
LOGI( "Program link log:\n%s", log );
free( log );
}
}
glGetProgramiv( prog, GL_LINK_STATUS, &status );
if( status == 0 )
{
LOGI( "Program link failed\n" );
return false;
}
return true;
}
/******************************************************************
* validateProgram()
*
* arguments:
* in: program, program
* return: true if a shader validation succeeded, false if it failed
*
*/
bool ValidateProgram( const GLuint prog )
{
GLint logLength, status;
glValidateProgram( prog );
glGetProgramiv( prog, GL_INFO_LOG_LENGTH, &logLength );
if( logLength > 0 )
{
GLchar *log = cast(GLchar *) malloc( logLength );
glGetProgramInfoLog( prog, logLength, &logLength, log );
LOGI( "Program validate log:\n%s", log );
free( log );
}
glGetProgramiv( prog, GL_VALIDATE_STATUS, &status );
if( status == 0 )
return false;
return true;
}
|
D
|
the basic unit of length adopted under the Systeme International d'Unites (approximately 1.094 yards)
concentration measured by the number of moles of solute per liter of solution
the cardinal number that is the product of 10 and 100
a unit of information equal to 1000 kilobytes or 10^6 (1,000,000) bytes
a unit of information equal to 1024 kibibytes or 2^20 (1,048,576) bytes
the 13th letter of the Roman alphabet
denoting a quantity consisting of 1,000 items or units
|
D
|
/**
* D header file for C99.
*
* $(C_HEADER_DESCRIPTION pubs.opengroup.org/onlinepubs/009695399/basedefs/_fenv.h.html, _fenv.h)
*
* Copyright: Copyright Sean Kelly 2005 - 2009.
* License: Distributed under the
* $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0).
* (See accompanying file LICENSE)
* Authors: Sean Kelly
* Source: $(DRUNTIMESRC core/stdc/_fenv.d)
* Standards: ISO/IEC 9899:1999 (E)
*/
module core.stdc.fenv;
version (OSX)
version = Darwin;
else version (iOS)
version = Darwin;
else version (TVOS)
version = Darwin;
else version (WatchOS)
version = Darwin;
extern (C):
@system:
nothrow:
@nogc:
version (ARM) version = ARM_Any;
version (AArch64) version = ARM_Any;
version (HPPA) version = HPPA_Any;
version (MIPS32) version = MIPS_Any;
version (MIPS64) version = MIPS_Any;
version (PPC) version = PPC_Any;
version (PPC64) version = PPC_Any;
version (RISCV32) version = RISCV_Any;
version (RISCV64) version = RISCV_Any;
version (S390) version = IBMZ_Any;
version (SPARC) version = SPARC_Any;
version (SPARC64) version = SPARC_Any;
version (SystemZ) version = IBMZ_Any;
version (X86) version = X86_Any;
version (X86_64) version = X86_Any;
version (MinGW)
version = GNUFP;
version (CRuntime_Glibc)
version = GNUFP;
version (GNUFP)
{
// https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/x86/fpu/bits/fenv.h
version (X86)
{
struct fenv_t
{
ushort __control_word;
ushort __unused1;
ushort __status_word;
ushort __unused2;
ushort __tags;
ushort __unused3;
uint __eip;
ushort __cs_selector;
ushort __opcode;
uint __data_offset;
ushort __data_selector;
ushort __unused5;
}
alias fexcept_t = ushort;
}
// https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/x86/fpu/bits/fenv.h
else version (X86_64)
{
struct fenv_t
{
ushort __control_word;
ushort __unused1;
ushort __status_word;
ushort __unused2;
ushort __tags;
ushort __unused3;
uint __eip;
ushort __cs_selector;
ushort __opcode;
uint __data_offset;
ushort __data_selector;
ushort __unused5;
uint __mxcsr;
}
alias fexcept_t = ushort;
}
// https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/hppa/bits/fenv.h
else version (HPPA_Any)
{
struct fenv_t
{
uint __status_word;
uint[7] __exception;
}
alias fexcept_t = uint;
}
// https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/mips/bits/fenv.h
else version (MIPS_Any)
{
struct fenv_t
{
uint __fp_control_register;
}
alias fexcept_t = ushort;
}
// https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/aarch64/bits/fenv.h
else version (AArch64)
{
struct fenv_t
{
uint __fpcr;
uint __fpsr;
}
alias fexcept_t = uint;
}
// https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/arm/bits/fenv.h
else version (ARM)
{
struct fenv_t
{
uint __cw;
}
alias fexcept_t = uint;
}
// https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/powerpc/bits/fenv.h
else version (PPC_Any)
{
alias fenv_t = double;
alias fexcept_t = uint;
}
// https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/riscv/bits/fenv.h
else version (RISCV_Any)
{
alias fenv_t = uint;
alias fexcept_t = uint;
}
// https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/sparc/fpu/bits/fenv.h
else version (SPARC_Any)
{
import core.stdc.config : c_ulong;
alias fenv_t = c_ulong;
alias fexcept_t = c_ulong;
}
// https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/s390/fpu/bits/fenv.h
else version (IBMZ_Any)
{
struct fenv_t
{
fexcept_t __fpc;
void* __unused;
}
alias fexcept_t = uint;
}
else
{
static assert(0, "Unimplemented architecture");
}
}
else version (CRuntime_DigitalMars)
{
struct fenv_t
{
ushort status;
ushort control;
ushort round;
ushort[2] reserved;
}
alias fexcept_t = int;
}
else version (CRuntime_Microsoft)
{
struct fenv_t
{
uint ctl;
uint stat;
}
alias fexcept_t = uint;
}
else version (Darwin)
{
version (BigEndian)
{
alias uint fenv_t;
alias uint fexcept_t;
}
version (LittleEndian)
{
struct fenv_t
{
ushort __control;
ushort __status;
uint __mxcsr;
byte[8] __reserved;
}
alias ushort fexcept_t;
}
}
else version (FreeBSD)
{
struct fenv_t
{
ushort __control;
ushort __mxcsr_hi;
ushort __status;
ushort __mxcsr_lo;
uint __tag;
byte[16] __other;
}
alias ushort fexcept_t;
}
else version (NetBSD)
{
version (X86_64)
{
struct fenv_t
{
struct _x87
{
uint control; /* Control word register */
uint status; /* Status word register */
uint tag; /* Tag word register */
uint[4] others; /* EIP, Pointer Selector, etc */
}
_x87 x87;
uint mxcsr; /* Control and status register */
}
}
version (X86)
{
struct fenv_t
{
struct _x87
{
ushort control; /* Control word register */
ushort unused1;
ushort status; /* Status word register */
ushort unused2;
ushort tag; /* Tag word register */
ushort unused3;
uint[4] others; /* EIP, Pointer Selector, etc */
}
_x87 x87;
uint mxcsr; /* Control and status register */
}
}
alias uint fexcept_t;
}
else version (OpenBSD)
{
struct fenv_t
{
struct __x87
{
uint __control;
uint __status;
uint __tag;
uint[4] __others;
}
}
uint __mxcsr;
alias fexcept_t = uint;
}
else version (DragonFlyBSD)
{
struct fenv_t
{
struct _x87
{
uint control;
uint status;
uint tag;
uint[4] others;
}
_x87 x87;
uint mxcsr;
}
alias uint fexcept_t;
}
else version (CRuntime_Bionic)
{
version (X86)
{
struct fenv_t
{
ushort __control;
ushort __mxcsr_hi;
ushort __status;
ushort __mxcsr_lo;
uint __tag;
byte[16] __other;
}
alias ushort fexcept_t;
}
else version (ARM)
{
alias uint fenv_t;
alias uint fexcept_t;
}
else version (AArch64)
{
struct fenv_t
{
uint __control;
uint __status;
}
alias uint fexcept_t;
}
else version (X86_64)
{
struct fenv_t
{
struct _x87
{
uint __control;
uint __status;
uint __tag;
uint[4] __others;
}
_x87 __x87;
uint __mxcsr;
}
alias uint fexcept_t;
}
else
{
static assert(false, "Architecture not supported.");
}
}
else version (Solaris)
{
import core.stdc.config : c_ulong;
enum FEX_NUM_EXC = 12;
struct fex_handler_t
{
int __mode;
void function() __handler;
}
struct fenv_t
{
fex_handler_t[FEX_NUM_EXC] __handler;
c_ulong __fsr;
}
alias int fexcept_t;
}
else version (CRuntime_Musl)
{
version (AArch64)
{
struct fenv_t
{
uint __fpcr;
uint __fpsr;
}
alias uint fexcept_t;
}
else version (ARM)
{
import core.stdc.config : c_ulong;
struct fenv_t
{
c_ulong __cw;
}
alias c_ulong fexcept_t;
}
else version (IBMZ_Any)
{
alias uint fenv_t;
alias uint fexcept_t;
}
else version (MIPS_Any)
{
struct fenv_t
{
uint __cw;
}
alias ushort fexcept_t;
}
else version (PPC_Any)
{
alias double fenv_t;
alias uint fexcept_t;
}
else version (X86_Any)
{
struct fenv_t
{
ushort __control_word;
ushort __unused1;
ushort __status_word;
ushort __unused2;
ushort __tags;
ushort __unused3;
uint __eip;
ushort __cs_selector;
ushort __opcode;
uint __data_offset;
ushort __data_selector;
ushort __unused5;
version (X86_64)
uint __mxcsr;
}
alias ushort fexcept_t;
}
else
{
static assert(false, "Architecture not supported.");
}
}
else version (CRuntime_UClibc)
{
version (X86)
{
struct fenv_t
{
ushort __control_word;
ushort __unused1;
ushort __status_word;
ushort __unused2;
ushort __tags;
ushort __unused3;
uint __eip;
ushort __cs_selector;
ushort __opcode;
uint __data_offset;
ushort __data_selector;
ushort __unused5;
}
alias fexcept_t = ushort;
}
else version (X86_64)
{
struct fenv_t
{
ushort __control_word;
ushort __unused1;
ushort __status_word;
ushort __unused2;
ushort __tags;
ushort __unused3;
uint __eip;
ushort __cs_selector;
ushort __opcode;
uint __data_offset;
ushort __data_selector;
ushort __unused5;
uint __mxcsr;
}
alias fexcept_t = ushort;
}
else version (MIPS32)
{
struct fenv_t
{
uint __fp_control_register;
}
alias fexcept_t = ushort;
}
else version (ARM)
{
struct fenv_t
{
uint __cw;
}
alias fexcept_t = uint;
}
else
{
static assert(false, "Architecture not supported.");
}
}
else
{
static assert( false, "Unsupported platform" );
}
version (CRuntime_Microsoft)
{
enum
{
FE_INEXACT = 1, ///
FE_UNDERFLOW = 2, ///
FE_OVERFLOW = 4, ///
FE_DIVBYZERO = 8, ///
FE_INVALID = 0x10, ///
FE_ALL_EXCEPT = 0x1F, ///
FE_TONEAREST = 0, ///
FE_UPWARD = 0x100, ///
FE_DOWNWARD = 0x200, ///
FE_TOWARDZERO = 0x300, ///
}
}
else version (Solaris)
{
version (SPARC_Any)
{
enum
{
FE_TONEAREST = 0,
FE_TOWARDZERO = 1,
FE_UPWARD = 2,
FE_DOWNWARD = 3,
}
enum
{
FE_INEXACT = 0x01,
FE_DIVBYZERO = 0x02,
FE_UNDERFLOW = 0x04,
FE_OVERFLOW = 0x08,
FE_INVALID = 0x10,
FE_ALL_EXCEPT = 0x1f,
}
}
else version (X86_Any)
{
enum
{
FE_TONEAREST = 0,
FE_DOWNWARD = 1,
FE_UPWARD = 2,
FE_TOWARDZERO = 3,
}
enum
{
FE_INVALID = 0x01,
FE_DIVBYZERO = 0x04,
FE_OVERFLOW = 0x08,
FE_UNDERFLOW = 0x10,
FE_INEXACT = 0x20,
FE_ALL_EXCEPT = 0x3d,
}
}
else
{
static assert(0, "Unimplemented architecture");
}
}
else
{
version (X86)
{
// Define bits representing the exception.
enum
{
FE_INVALID = 0x01, ///
FE_DENORMAL = 0x02, /// non-standard
FE_DIVBYZERO = 0x04, ///
FE_OVERFLOW = 0x08, ///
FE_UNDERFLOW = 0x10, ///
FE_INEXACT = 0x20, ///
FE_ALL_EXCEPT = 0x3F, ///
}
// The ix87 FPU supports all of the four defined rounding modes.
enum
{
FE_TONEAREST = 0, ///
FE_DOWNWARD = 0x400, ///
FE_UPWARD = 0x800, ///
FE_TOWARDZERO = 0xC00, ///
}
}
else version (X86_64)
{
// Define bits representing the exception.
enum
{
FE_INVALID = 0x01, ///
FE_DENORMAL = 0x02, /// non-standard
FE_DIVBYZERO = 0x04, ///
FE_OVERFLOW = 0x08, ///
FE_UNDERFLOW = 0x10, ///
FE_INEXACT = 0x20, ///
FE_ALL_EXCEPT = 0x3F, ///
}
// The ix87 FPU supports all of the four defined rounding modes.
enum
{
FE_TONEAREST = 0, ///
FE_DOWNWARD = 0x400, ///
FE_UPWARD = 0x800, ///
FE_TOWARDZERO = 0xC00, ///
}
}
else version (ARM_Any)
{
// Define bits representing exceptions in the FPU status word.
enum
{
FE_INVALID = 1, ///
FE_DIVBYZERO = 2, ///
FE_OVERFLOW = 4, ///
FE_UNDERFLOW = 8, ///
FE_INEXACT = 16, ///
FE_ALL_EXCEPT = 31, ///
}
// VFP supports all of the four defined rounding modes.
enum
{
FE_TONEAREST = 0, ///
FE_UPWARD = 0x400000, ///
FE_DOWNWARD = 0x800000, ///
FE_TOWARDZERO = 0xC00000, ///
}
}
else version (HPPA_Any)
{
// Define bits representing the exception.
enum
{
FE_INEXACT = 0x01, ///
FE_UNDERFLOW = 0x02, ///
FE_OVERFLOW = 0x04, ///
FE_DIVBYZERO = 0x08, ///
FE_INVALID = 0x10, ///
FE_ALL_EXCEPT = 0x1F, ///
}
// The HPPA FPU supports all of the four defined rounding modes.
enum
{
FE_TONEAREST = 0x0, ///
FE_TOWARDZERO = 0x200, ///
FE_UPWARD = 0x400, ///
FE_DOWNWARD = 0x600, ///
}
}
else version (MIPS_Any)
{
// Define bits representing the exception.
enum
{
FE_INEXACT = 0x04, ///
FE_UNDERFLOW = 0x08, ///
FE_OVERFLOW = 0x10, ///
FE_DIVBYZERO = 0x20, ///
FE_INVALID = 0x40, ///
FE_ALL_EXCEPT = 0x7C, ///
}
// The MIPS FPU supports all of the four defined rounding modes.
enum
{
FE_TONEAREST = 0x0, ///
FE_TOWARDZERO = 0x1, ///
FE_UPWARD = 0x2, ///
FE_DOWNWARD = 0x3, ///
}
}
else version (PPC_Any)
{
// Define bits representing the exception.
enum
{
FE_INEXACT = 0x2000000, ///
FE_DIVBYZERO = 0x4000000, ///
FE_UNDERFLOW = 0x8000000, ///
FE_OVERFLOW = 0x10000000, ///
FE_INVALID = 0x20000000, ///
FE_INVALID_SNAN = 0x1000000, /// non-standard
FE_INVALID_ISI = 0x800000, /// non-standard
FE_INVALID_IDI = 0x400000, /// non-standard
FE_INVALID_ZDZ = 0x200000, /// non-standard
FE_INVALID_IMZ = 0x100000, /// non-standard
FE_INVALID_COMPARE = 0x80000, /// non-standard
FE_INVALID_SOFTWARE = 0x400, /// non-standard
FE_INVALID_SQRT = 0x200, /// non-standard
FE_INVALID_INTEGER_CONVERSION = 0x100, /// non-standard
FE_ALL_INVALID = 0x1F80700, /// non-standard
FE_ALL_EXCEPT = 0x3E000000, ///
}
// PowerPC chips support all of the four defined rounding modes.
enum
{
FE_TONEAREST = 0, ///
FE_TOWARDZERO = 1, ///
FE_UPWARD = 2, ///
FE_DOWNWARD = 3, ///
}
}
else version (RISCV_Any)
{
// Define bits representing exceptions in the FPSR status word.
enum
{
FE_INEXACT = 0x01, ///
FE_UNDERFLOW = 0x02, ///
FE_OVERFLOW = 0x04, ///
FE_DIVBYZERO = 0x08, ///
FE_INVALID = 0x10, ///
FE_ALL_EXCEPT = 0x1f, ///
}
// Define bits representing rounding modes in the FPCR Rmode field.
enum
{
FE_TONEAREST = 0x0, ///
FE_TOWARDZERO = 0x1, ///
FE_DOWNWARD = 0x2, ///
FE_UPWARD = 0x3, ///
}
}
else version (SPARC_Any)
{
// Define bits representing the exception.
enum
{
FE_INVALID = 0x200, ///
FE_OVERFLOW = 0x100, ///
FE_UNDERFLOW = 0x80, ///
FE_DIVBYZERO = 0x40, ///
FE_INEXACT = 0x20, ///
FE_ALL_EXCEPT = 0x3E0, ///
}
// The Sparc FPU supports all of the four defined rounding modes.
enum
{
FE_TONEAREST = 0x0, ///
FE_TOWARDZERO = 0x40000000, ///
FE_UPWARD = 0x80000000, ///
FE_DOWNWARD = 0xc0000000, ///
}
}
else version (IBMZ_Any)
{
// Define bits representing the exception.
enum
{
FE_INVALID = 0x80, ///
FE_DIVBYZERO = 0x40, ///
FE_OVERFLOW = 0x20, ///
FE_UNDERFLOW = 0x10, ///
FE_INEXACT = 0x08, ///
FE_ALL_EXCEPT = 0xF8, ///
}
// SystemZ supports all of the four defined rounding modes.
enum
{
FE_TONEAREST = 0x0, ///
FE_DOWNWARD = 0x3, ///
FE_UPWARD = 0x2, ///
FE_TOWARDZERO = 0x1, ///
}
}
else
{
static assert(0, "Unimplemented architecture");
}
}
version (GNUFP)
{
///
enum FE_DFL_ENV = cast(fenv_t*)(-1);
}
else version (CRuntime_DigitalMars)
{
private extern __gshared fenv_t _FE_DFL_ENV;
///
enum fenv_t* FE_DFL_ENV = &_FE_DFL_ENV;
}
else version (CRuntime_Microsoft)
{
private extern __gshared fenv_t _Fenv0;
///
enum FE_DFL_ENV = &_Fenv0;
}
else version (Darwin)
{
private extern __gshared fenv_t _FE_DFL_ENV;
///
enum FE_DFL_ENV = &_FE_DFL_ENV;
}
else version (FreeBSD)
{
private extern const fenv_t __fe_dfl_env;
///
enum FE_DFL_ENV = &__fe_dfl_env;
}
else version (NetBSD)
{
private extern const fenv_t __fe_dfl_env;
///
enum FE_DFL_ENV = &__fe_dfl_env;
}
else version (OpenBSD)
{
private extern const fenv_t __fe_dfl_env;
///
enum FE_DFL_ENV = &__fe_dfl_env;
}
else version (DragonFlyBSD)
{
private extern const fenv_t __fe_dfl_env;
///
enum FE_DFL_ENV = &__fe_dfl_env;
}
else version (CRuntime_Bionic)
{
private extern const fenv_t __fe_dfl_env;
///
enum FE_DFL_ENV = &__fe_dfl_env;
}
else version (Solaris)
{
private extern const fenv_t __fenv_def_env;
///
enum FE_DFL_ENV = &__fenv_def_env;
}
else version (CRuntime_Musl)
{
///
enum FE_DFL_ENV = cast(fenv_t*)(-1);
}
else version (CRuntime_UClibc)
{
///
enum FE_DFL_ENV = cast(fenv_t*)(-1);
}
else
{
static assert( false, "Unsupported platform" );
}
///
int feclearexcept(int excepts);
///
int fetestexcept(int excepts);
///
int feholdexcept(fenv_t* envp);
///
int fegetexceptflag(fexcept_t* flagp, int excepts);
///
int fesetexceptflag(const scope fexcept_t* flagp, int excepts);
///
int fegetround();
///
int fesetround(int round);
///
int fegetenv(fenv_t* envp);
///
int fesetenv(const scope fenv_t* envp);
// MS define feraiseexcept() and feupdateenv() inline.
version (CRuntime_Microsoft) // supported since MSVCRT 12 (VS 2013) only
{
///
int feraiseexcept()(int excepts)
{
struct Entry
{
int exceptVal;
double num;
double denom;
}
static __gshared immutable(Entry[5]) table =
[ // Raise exception by evaluating num / denom:
{ FE_INVALID, 0.0, 0.0 },
{ FE_DIVBYZERO, 1.0, 0.0 },
{ FE_OVERFLOW, 1e+300, 1e-300 },
{ FE_UNDERFLOW, 1e-300, 1e+300 },
{ FE_INEXACT, 2.0, 3.0 }
];
if ((excepts &= FE_ALL_EXCEPT) == 0)
return 0;
// Raise the exceptions not masked:
double ans = void;
foreach (i; 0 .. table.length)
{
if ((excepts & table[i].exceptVal) != 0)
ans = table[i].num / table[i].denom;
}
return 0;
}
///
int feupdateenv()(const scope fenv_t* envp)
{
int excepts = fetestexcept(FE_ALL_EXCEPT);
return (fesetenv(envp) != 0 || feraiseexcept(excepts) != 0 ? 1 : 0);
}
}
else
{
///
int feraiseexcept(int excepts);
///
int feupdateenv(const scope fenv_t* envp);
}
|
D
|
module setlattice;
import std.algorithm : canFind;
import std.stdio;
import std.conv : to;
import std.string : split;
import core.stdc.stdlib : exit;
import main;
import setpins;
//-------------------------------------------------------------------//
/**
* Macro information struct for a lattice.
* used in reader.d.
*/
struct Lattice
{
int type; /**< lattoce type. */
double x; /**< center x value. */
double y; /**< center y value. */
int rows; /**< number of rows. */
int columns; /**< number of columns. */
double pitch; /**< pitch, distance between pins. */
int[][] map; /**< pin map layout. */
}
//-------------------------------------------------------------------//
int latticeId, latticeType, rows, columns;
int[][] map;
double xCoor, yCoor, pitch;
Lattice[int] latticeDict; /**< dictionary of defined lattce information. */
string[string] mUniverseType;
void setLattice(string[] paramLine, int lineCount, Universes[int] universes)
{
string rowLine;
try
{
latticeId = to!int(paramLine[1]);
latticeType = to!int(paramLine[2]);
xCoor = to!double(paramLine[3]);
yCoor = to!double(paramLine[4]);
rows = to!int(paramLine[5]);
columns = to!int(paramLine[6]);
pitch = to!double(paramLine[7]);
assert(latticeId !in universes);
universes[latticeId] = Universes("lattice");
}
catch( std.conv.ConvException e)
{
writefln("+++ Error at line: %s, incorrect parameters definition", lineCount);
outputFile.writeln("+++ Error: incorrect parameters definition");
exit(0);
}
catch( core.exception.AssertError e)
{
writefln("+++ Error at line: %s, incorrect parameter definition", lineCount);
outputFile.writeln("+++ Error: universe Id already exist");
exit(0);
}
map = new int[][](rows, columns);
latticeDict[latticeId] = Lattice(latticeType, xCoor, yCoor, rows, columns, pitch, map);
mUniverseType[ paramLine[1] ] = "lattice";
try
{
for (int i; i < rows; i++)
{
rowLine = inputFile.readln();
lineCount++;
outputFile.writef("%s-\t%s", lineCount, rowLine);
auto row = rowLine.split();
for (int j; j < columns; j++)
{
map[i][j] = to!int(row[j]);
try
{
if ( [0, 1].canFind( latticeType ) )
{
if(to!int(row[j]) !in universes || to!int(row[j]) in latticeDict )
{
writefln("+++ Error at line: %s", lineCount);
outputFile.writefln("+++ Error: not universe definition or universe al ready exist");
exit(0);
}
}
}
catch (core.exception.AssertError e)
{
writefln("+++ Error at line: %s", lineCount);
outputFile.write("+++ Error: universe alredy exist");
exit(0);
}
}
}
}
catch (core.exception.RangeError e)
{
writeln("+++ Error 1");
}
catch (std.conv.ConvException e)
{
writeln("+++ Error 2");
}
catch (core.exception.AssertError e)
{
writefln("+++ Error at line: %s", lineCount);
outputFile.write("+++ Error: not universe definition");
exit(0);
}
}
/**
* Getter method: universe type.
* @returns universe type.
*/
@property string[string] getUniType()
{
return mUniverseType;
}
@property Lattice[int] getLattice()
{
return latticeDict;
}
|
D
|
module hunt.sql.dialect.postgresql.visitor;
public import hunt.sql.dialect.postgresql.visitor.PGASTVisitorAdapter;
public import hunt.sql.dialect.postgresql.visitor.PGASTVisitor;
public import hunt.sql.dialect.postgresql.visitor.PGEvalVisitor;
public import hunt.sql.dialect.postgresql.visitor.PGExportParameterVisitor;
public import hunt.sql.dialect.postgresql.visitor.PGOutputVisitor;
public import hunt.sql.dialect.postgresql.visitor.PGSchemaStatVisitor;
|
D
|
// Copyright Ferdinand Majerech 2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
/// Functionality that may sometimes be needed but allows unsafe or unstandard behavior, and should only be used in specific cases.
module dyaml.hacks;
import dyaml.node;
import dyaml.style;
/** Get the scalar style a node had in the file it was loaded from.
*
* This is only useful for nodes loaded from files.
*
* This is a "hack" because a YAML application is supposed to be unaware of styles
* used in YAML styles, i.e. treating different styles differently is unstandard.
* However, determining style may be useful in some cases, e.g. YAML utilities.
*
* May only be called on scalar nodes (nodes where node.isScalar() == true).
*/
ScalarStyle scalarStyleHack(ref const(Node) node) @safe nothrow
{
assert(node.isScalar, "Trying to get scalar style of a non-scalar node");
return node.scalarStyle;
}
///
@safe unittest
{
import dyaml;
Node node = Loader.fromString(`"42"`).load(); // loaded from a file
if(node.isScalar)
{
assert(node.scalarStyleHack() == ScalarStyle.DoubleQuoted);
}
}
@safe unittest
{
auto node = Node(5);
assert(node.scalarStyleHack() == ScalarStyle.Invalid);
}
/** Get the collection style a YAML node had in the file it was loaded from.
*
* May only be called on collection nodes (nodes where node.isScalar() != true).
*
* See_Also: scalarStyleHack
*/
CollectionStyle collectionStyleHack(ref const(Node) node) @safe nothrow
{
assert(!node.isScalar, "Trying to get collection style of a scalar node");
return node.collectionStyle;
}
@safe unittest
{
auto node = Node([1, 2, 3, 4, 5]);
assert(node.collectionStyleHack() == CollectionStyle.Invalid);
}
/** Set the scalar style node should have when written to a file.
*
* Setting the style might be useful when generating YAML or reformatting existing files.
*
* May only be called on scalar nodes (nodes where node.isScalar() == true).
*/
void scalarStyleHack(ref Node node, const ScalarStyle rhs) @safe nothrow
{
assert(node.isScalar, "Trying to set scalar style of a non-scalar node");
node.scalarStyle = rhs;
}
///
@safe unittest
{
auto node = Node(5);
node.scalarStyleHack = ScalarStyle.DoubleQuoted;
assert(node.scalarStyleHack() == ScalarStyle.DoubleQuoted);
}
/** Set the collection style node should have when written to a file.
*
* Setting the style might be useful when generating YAML or reformatting existing files.
*
* May only be called on collection nodes (nodes where node.isScalar() != true).
*/
void collectionStyleHack(ref Node node, const CollectionStyle rhs) @safe nothrow
{
assert(!node.isScalar, "Trying to set collection style of a scalar node");
node.collectionStyle = rhs;
}
///
@safe unittest
{
auto node = Node([1, 2, 3, 4, 5]);
node.collectionStyleHack = CollectionStyle.Block;
assert(node.collectionStyleHack() == CollectionStyle.Block);
}
|
D
|
/Users/radibarq/developer/Chottky/build/Pods.build/Debug-iphonesimulator/FacebookCore.build/Objects-normal/x86_64/AppEventParameterName.o : /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestProtocol.Bridge.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestConnectionDelegateBridge.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/AppEvents/AppEventParameterName.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/AppEvents/AppEventName.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Internal/Extensions/Optional+OnSome.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphResponse.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Common/SDKApplicationDelegate.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphResponseProtocol.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestProtocol.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Common/AccessToken.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/AppEvents/AppEvent.Builtin.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphAPIVersion.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Permissions/Permission.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Permissions/ReadPermission.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Permissions/PublishPermission.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestConnection.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Internal/Extensions/Dictionary+KeyValueMap.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/AppEvents/AppEventsLogger.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Common/SDKLoggingBehavior.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/AppEvents/AppEventsLogger.FlushBehavior.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Common/SDKSettings.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.FetchResult.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestResult.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestDataAttachment.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/AppEvents/AppEvent.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequest.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.PictureView.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFURL.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKURL.h /Users/radibarq/developer/Chottky/Pods/Target\ Support\ Files/FacebookCore/FacebookCore-umbrella.h /Users/radibarq/developer/Chottky/Pods/Target\ Support\ Files/Bolts/Bolts-umbrella.h /Users/radibarq/developer/Chottky/Pods/Target\ Support\ Files/FBSDKCoreKit/FBSDKCoreKit-umbrella.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFGeneric.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFCancellationTokenSource.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFTaskCompletionSource.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKProfile.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKApplicationDelegate.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFAppLinkResolving.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkResolving.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKCopying.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKMutableCopying.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFAppLink.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLink.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFTask.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFCancellationToken.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAccessToken.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFAppLinkNavigation.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkNavigation.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFCancellationTokenRegistration.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphRequestConnection.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKButton.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKTestUsersManager.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFAppLinkReturnToRefererController.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkReturnToRefererController.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkResolver.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFWebViewAppLinkResolver.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKWebViewAppLinkResolver.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphErrorRecoveryProcessor.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFExecutor.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKSettings.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKMacros.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/Bolts.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKConstants.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppEvents.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFAppLinkTarget.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkTarget.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphRequestDataAttachment.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFMeasurementEvent.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKMeasurementEvent.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphRequest.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKProfilePictureView.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFAppLinkReturnToRefererView.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkReturnToRefererView.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKUtility.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkUtility.h /Users/radibarq/developer/Chottky/build/Pods.build/Debug-iphonesimulator/FacebookCore.build/unextended-module.modulemap /Users/radibarq/developer/Chottky/build/Pods.build/Debug-iphonesimulator/Bolts.build/module.modulemap /Users/radibarq/developer/Chottky/build/Pods.build/Debug-iphonesimulator/FBSDKCoreKit.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/WebKit.framework/Headers/WebKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/radibarq/developer/Chottky/build/Pods.build/Debug-iphonesimulator/FacebookCore.build/Objects-normal/x86_64/AppEventParameterName~partial.swiftmodule : /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestProtocol.Bridge.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestConnectionDelegateBridge.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/AppEvents/AppEventParameterName.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/AppEvents/AppEventName.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Internal/Extensions/Optional+OnSome.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphResponse.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Common/SDKApplicationDelegate.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphResponseProtocol.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestProtocol.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Common/AccessToken.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/AppEvents/AppEvent.Builtin.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphAPIVersion.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Permissions/Permission.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Permissions/ReadPermission.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Permissions/PublishPermission.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestConnection.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Internal/Extensions/Dictionary+KeyValueMap.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/AppEvents/AppEventsLogger.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Common/SDKLoggingBehavior.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/AppEvents/AppEventsLogger.FlushBehavior.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Common/SDKSettings.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.FetchResult.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestResult.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestDataAttachment.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/AppEvents/AppEvent.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequest.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.PictureView.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFURL.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKURL.h /Users/radibarq/developer/Chottky/Pods/Target\ Support\ Files/FacebookCore/FacebookCore-umbrella.h /Users/radibarq/developer/Chottky/Pods/Target\ Support\ Files/Bolts/Bolts-umbrella.h /Users/radibarq/developer/Chottky/Pods/Target\ Support\ Files/FBSDKCoreKit/FBSDKCoreKit-umbrella.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFGeneric.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFCancellationTokenSource.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFTaskCompletionSource.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKProfile.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKApplicationDelegate.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFAppLinkResolving.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkResolving.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKCopying.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKMutableCopying.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFAppLink.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLink.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFTask.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFCancellationToken.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAccessToken.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFAppLinkNavigation.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkNavigation.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFCancellationTokenRegistration.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphRequestConnection.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKButton.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKTestUsersManager.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFAppLinkReturnToRefererController.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkReturnToRefererController.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkResolver.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFWebViewAppLinkResolver.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKWebViewAppLinkResolver.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphErrorRecoveryProcessor.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFExecutor.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKSettings.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKMacros.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/Bolts.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKConstants.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppEvents.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFAppLinkTarget.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkTarget.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphRequestDataAttachment.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFMeasurementEvent.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKMeasurementEvent.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphRequest.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKProfilePictureView.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFAppLinkReturnToRefererView.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkReturnToRefererView.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKUtility.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkUtility.h /Users/radibarq/developer/Chottky/build/Pods.build/Debug-iphonesimulator/FacebookCore.build/unextended-module.modulemap /Users/radibarq/developer/Chottky/build/Pods.build/Debug-iphonesimulator/Bolts.build/module.modulemap /Users/radibarq/developer/Chottky/build/Pods.build/Debug-iphonesimulator/FBSDKCoreKit.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/WebKit.framework/Headers/WebKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/radibarq/developer/Chottky/build/Pods.build/Debug-iphonesimulator/FacebookCore.build/Objects-normal/x86_64/AppEventParameterName~partial.swiftdoc : /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestProtocol.Bridge.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestConnectionDelegateBridge.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/AppEvents/AppEventParameterName.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/AppEvents/AppEventName.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Internal/Extensions/Optional+OnSome.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphResponse.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Common/SDKApplicationDelegate.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphResponseProtocol.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestProtocol.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Common/AccessToken.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/AppEvents/AppEvent.Builtin.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphAPIVersion.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Permissions/Permission.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Permissions/ReadPermission.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Permissions/PublishPermission.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestConnection.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Internal/Extensions/Dictionary+KeyValueMap.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/AppEvents/AppEventsLogger.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Common/SDKLoggingBehavior.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/AppEvents/AppEventsLogger.FlushBehavior.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/Common/SDKSettings.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.FetchResult.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestResult.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestDataAttachment.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/AppEvents/AppEvent.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequest.swift /Users/radibarq/developer/Chottky/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.PictureView.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFURL.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKURL.h /Users/radibarq/developer/Chottky/Pods/Target\ Support\ Files/FacebookCore/FacebookCore-umbrella.h /Users/radibarq/developer/Chottky/Pods/Target\ Support\ Files/Bolts/Bolts-umbrella.h /Users/radibarq/developer/Chottky/Pods/Target\ Support\ Files/FBSDKCoreKit/FBSDKCoreKit-umbrella.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFGeneric.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFCancellationTokenSource.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFTaskCompletionSource.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKProfile.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKApplicationDelegate.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFAppLinkResolving.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkResolving.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKCopying.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKMutableCopying.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFAppLink.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLink.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFTask.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFCancellationToken.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAccessToken.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFAppLinkNavigation.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkNavigation.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFCancellationTokenRegistration.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphRequestConnection.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKButton.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKTestUsersManager.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFAppLinkReturnToRefererController.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkReturnToRefererController.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkResolver.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFWebViewAppLinkResolver.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKWebViewAppLinkResolver.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphErrorRecoveryProcessor.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/BFExecutor.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKSettings.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKMacros.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/Common/Bolts.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKConstants.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppEvents.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFAppLinkTarget.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkTarget.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphRequestDataAttachment.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFMeasurementEvent.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKMeasurementEvent.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphRequest.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKProfilePictureView.h /Users/radibarq/developer/Chottky/Pods/Bolts/Bolts/iOS/BFAppLinkReturnToRefererView.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkReturnToRefererView.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKUtility.h /Users/radibarq/developer/Chottky/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkUtility.h /Users/radibarq/developer/Chottky/build/Pods.build/Debug-iphonesimulator/FacebookCore.build/unextended-module.modulemap /Users/radibarq/developer/Chottky/build/Pods.build/Debug-iphonesimulator/Bolts.build/module.modulemap /Users/radibarq/developer/Chottky/build/Pods.build/Debug-iphonesimulator/FBSDKCoreKit.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/WebKit.framework/Headers/WebKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
|
D
|
// https://dpaste.dzfl.pl/7a77355acaec
// Search for: FIXME: leaks if multithreaded gc
// https://freedesktop.org/wiki/Specifications/XDND/
// https://docs.microsoft.com/en-us/windows/win32/dataxchg/html-clipboard-format
// https://www.x.org/releases/X11R7.7/doc/libXext/dbelib.html
// https://www.x.org/releases/X11R7.6/doc/libXext/synclib.html
// on Mac with X11: -L-L/usr/X11/lib
/+
* I might need to set modal hints too _NET_WM_STATE_MODAL and make sure that TRANSIENT_FOR legit works
Progress bar in taskbar
- i can probably just set a property on the window...
it sets that prop to an integer 0 .. 100. Taskbar
deletes it or window deletes it when it is handled.
- prolly display it as a nice little line at the bottom.
from gtk:
#define PROGRESS_HINT "_NET_WM_XAPP_PROGRESS"
#define PROGRESS_PULSE_HINT "_NET_WM_XAPP_PROGRESS_PULSE"
>+ if (cardinal > 0)
>+ {
>+ XChangeProperty (GDK_DISPLAY_XDISPLAY (display),
>+ xid,
>+ gdk_x11_get_xatom_by_name_for_display (display, atom_name),
>+ XA_CARDINAL, 32,
>+ PropModeReplace,
>+ (guchar *) &cardinal, 1);
>+ }
>+ else
>+ {
>+ XDeleteProperty (GDK_DISPLAY_XDISPLAY (display),
>+ xid,
>+ gdk_x11_get_xatom_by_name_for_display (display, atom_name));
>+ }
from Windows:
see: https://docs.microsoft.com/en-us/windows/win32/api/shobjidl_core/nn-shobjidl_core-itaskbarlist3
interface
CoCreateInstance( CLSID_TaskbarList, nullptr, CLSCTX_ALL, __uuidof(ITaskbarList3), (LPVOID*)&m_pTL3 );
auto msg = RegisterWindowMessage(TEXT(“TaskbarButtonCreated”));
listen for msg, return TRUE
interface->SetProgressState(hwnd, TBPF_NORMAL);
interface->SetProgressValue(hwnd, 40, 100);
My new notification system.
- use a unix socket? or a x property? or a udp port?
- could of course also get on the dbus train but ugh.
- it could also reply with the info as a string for easy remote examination.
+/
/*
Event Loop would be nices:
* add on idle - runs when nothing else happens
* which can specify how long to yield for
* send messages without a recipient window
* setTimeout
* setInterval
*/
/*
Classic games I want to add:
* my tetris clone
* pac man
*/
/*
Text layout needs a lot of work. Plain drawText is useful but too
limited. It will need some kind of text context thing which it will
update and you can pass it on and get more details out of it.
It will need a bounding box, a current cursor location that is updated
as drawing continues, and various changable facts (which can also be
changed on the painter i guess) like font, color, size, background,
etc.
We can also fetch the caret location from it somehow.
Should prolly be an overload of drawText
blink taskbar / demand attention cross platform. FlashWindow and demandAttention
WS_EX_NOACTIVATE
WS_CHILD - owner and owned vs parent and child. Does X have something similar?
full screen windows. Can just set the atom on X. Windows will be harder.
moving windows. resizing windows.
hide cursor, capture cursor, change cursor.
REMEMBER: simpledisplay does NOT have to do everything! It just needs to make
sure the pieces are there to do its job easily and make other jobs possible.
*/
/++
simpledisplay.d (often abbreviated to "sdpy") provides basic cross-platform GUI-related functionality,
including creating windows, drawing on them, working with the clipboard,
timers, OpenGL, and more. However, it does NOT provide high level GUI
widgets. See my minigui.d, an extension to this module, for that
functionality.
simpledisplay provides cross-platform wrapping for Windows and Linux
(and perhaps other OSes that use X11), but also does not prevent you
from using the underlying facilities if you need them. It has a goal
of working efficiently over a remote X link (at least as far as Xlib
reasonably allows.)
simpledisplay depends on [arsd.color|color.d], which should be available from the
same place where you got this file. Other than that, however, it has
very few dependencies and ones that don't come with the OS and/or the
compiler are all opt-in.
simpledisplay.d's home base is on my arsd repo on Github. The file is:
https://github.com/adamdruppe/arsd/blob/master/simpledisplay.d
simpledisplay is basically stable. I plan to refactor the internals,
and may add new features and fix bugs, but It do not expect to
significantly change the API. It has been stable a few years already now.
Installation_instructions:
`simpledisplay.d` does not have any dependencies outside the
operating system and `color.d`, so it should just work most the
time, but there are a few caveats on some systems:
On Win32, you can pass `-L/subsystem:windows` if you don't want a
console to be automatically allocated.
Please note when compiling on Win64, you need to explicitly list
`-Lgdi32.lib -Luser32.lib` on the build command. If you want the Windows
subsystem too, use `-L/subsystem:windows -L/entry:mainCRTStartup`.
If using ldc instead of dmd, use `-L/entry:wmainCRTStartup` instead of `mainCRTStartup`;
note the "w".
I provided a `mixin EnableWindowsSubsystem;` helper to do those linker flags for you,
but you still need to use dmd -m32mscoff or -m64 (which dub does by default too fyi).
See [EnableWindowsSubsystem] for more information.
$(PITFALL
With the Windows subsystem, there is no console, so standard writeln will throw!
You can use [sdpyPrintDebugString] instead of stdio writeln instead which will
create a console as needed.
)
On Mac, when compiling with X11, you need XQuartz and -L-L/usr/X11R6/lib passed to dmd. If using the Cocoa implementation on Mac, you need to pass `-L-framework -LCocoa` to dmd. For OpenGL, add `-L-framework -LOpenGL` to the build command.
On Ubuntu, you might need to install X11 development libraries to
successfully link.
$(CONSOLE
$ sudo apt-get install libglc-dev
$ sudo apt-get install libx11-dev
)
Jump_list:
Don't worry, you don't have to read this whole documentation file!
Check out the [#event-example] and [#Pong-example] to get started quickly.
The main classes you may want to create are [SimpleWindow], [Timer],
[Image], and [Sprite].
The main functions you'll want are [setClipboardText] and [getClipboardText].
There are also platform-specific functions available such as [XDisplayConnection]
and [GetAtom] for X11, among others.
See the examples and topics list below to learn more.
$(WARNING
There should only be one GUI thread per application,
and all windows should be created in it and your
event loop should run there.
To do otherwise is undefined behavior and has no
cross platform guarantees.
)
$(H2 About this documentation)
The goal here is to give some complete programs as overview examples first, then a look at each major feature with working examples first, then, finally, the inline class and method list will follow.
Scan for headers for a topic - $(B they will visually stand out) - you're interested in to get started quickly and feel free to copy and paste any example as a starting point for your program. I encourage you to learn the library by experimenting with the examples!
All examples are provided with no copyright restrictions whatsoever. You do not need to credit me or carry any kind of notice with the source if you copy and paste from them.
To get started, download `simpledisplay.d` and `color.d` to a working directory. Copy an example info a file called `example.d` and compile using the command given at the top of each example.
If you need help, email me: destructionator@gmail.com or IRC us, #d on Freenode (I am destructionator or adam_d_ruppe there). If you learn something that isn't documented, I appreciate pull requests on github to this file.
At points, I will talk about implementation details in the documentation. These are sometimes
subject to change, but nevertheless useful to understand what is really going on. You can learn
more about some of the referenced things by searching the web for info about using them from C.
You can always look at the source of simpledisplay.d too for the most authoritative source on
its specific implementation. If you disagree with how I did something, please contact me so we
can discuss it!
$(H2 Using with fibers)
simpledisplay can be used with [core.thread.Fiber], but be warned many of the functions can use a significant amount of stack space. I recommend at least 64 KB stack for each fiber (just set through the second argument to Fiber's constructor).
$(H2 Topics)
$(H3 $(ID topic-windows) Windows)
The [SimpleWindow] class is simpledisplay's flagship feature. It represents a single
window on the user's screen.
You may create multiple windows, if the underlying platform supports it. You may check
`static if(multipleWindowsSupported)` at compile time, or catch exceptions thrown by
SimpleWindow's constructor at runtime to handle those cases.
A single running event loop will handle as many windows as needed.
$(H3 $(ID topic-event-loops) Event loops)
The simpledisplay event loop is designed to handle common cases easily while being extensible for more advanced cases, or replaceable by other libraries.
The most common scenario is creating a window, then calling [SimpleWindow.eventLoop|window.eventLoop] when setup is complete. You can pass several handlers to the `eventLoop` method right there:
---
// dmd example.d simpledisplay.d color.d
import arsd.simpledisplay;
void main() {
auto window = new SimpleWindow(200, 200);
window.eventLoop(0,
delegate (dchar) { /* got a character key press */ }
);
}
---
$(TIP If you get a compile error saying "I can't use this event handler", the most common thing in my experience is passing a function instead of a delegate. The simple solution is to use the `delegate` keyword, like I did in the example above.)
On Linux, the event loop is implemented with the `epoll` system call for efficiency an extensibility to other files. On Windows, it runs a traditional `GetMessage` + `DispatchMessage` loop, with a call to `SleepEx` in each iteration to allow the thread to enter an alertable wait state regularly, primarily so Overlapped I/O callbacks will get a chance to run.
On Linux, simpledisplay also supports my (deprecated) [arsd.eventloop] module. Compile your program, including the eventloop.d file, with the `-version=with_eventloop` switch.
It should be possible to integrate simpledisplay with vibe.d as well, though I haven't tried.
You can also run the event loop independently of a window, with [EventLoop.run|EventLoop.get.run], though since it will automatically terminate when there are no open windows, you will want to have one anyway.
$(H3 $(ID topic-notification-areas) Notification area (aka systray) icons)
Notification area icons are currently implemented on X11 and Windows. On X11, it defaults to using `libnotify` to show bubbles, if available, and will do a custom bubble window if not. You can `version=without_libnotify` to avoid this run-time dependency, if you like.
See the [NotificationAreaIcon] class.
$(H3 $(ID topic-input-handling) Input handling)
There are event handlers for low-level keyboard and mouse events, and higher level handlers for character events.
See [SimpleWindow.handleCharEvent], [SimpleWindow.handleKeyEvent], [SimpleWindow.handleMouseEvent].
$(H3 $(ID topic-2d-drawing) 2d Drawing)
To draw on your window, use the [SimpleWindow.draw] method. It returns a [ScreenPainter] structure with drawing methods.
Important: `ScreenPainter` double-buffers and will not actually update the window until its destructor is run. Always ensure the painter instance goes out-of-scope before proceeding. You can do this by calling it inside an event handler, a timer callback, or an small scope inside main. For example:
---
// dmd example.d simpledisplay.d color.d
import arsd.simpledisplay;
void main() {
auto window = new SimpleWindow(200, 200);
{ // introduce sub-scope
auto painter = window.draw(); // begin drawing
/* draw here */
painter.outlineColor = Color.red;
painter.fillColor = Color.black;
painter.drawRectangle(Point(0, 0), 200, 200);
} // end scope, calling `painter`'s destructor, drawing to the screen.
window.eventLoop(0); // handle events
}
---
Painting is done based on two color properties, a pen and a brush.
At this time, the 2d drawing does not support alpha blending, except for the [Sprite] class. If you need that, use a 2d OpenGL context instead.
FIXME Add example of 2d opengl drawing here.
$(H3 $(ID topic-3d-drawing) 3d Drawing (or 2d with OpenGL))
simpledisplay can create OpenGL contexts on your window. It works quite differently than 2d drawing.
Note that it is still possible to draw 2d on top of an OpenGL window, using the `draw` method, though I don't recommend it.
To start, you create a [SimpleWindow] with OpenGL enabled by passing the argument [OpenGlOptions.yes] to the constructor.
Next, you set [SimpleWindow.redrawOpenGlScene|window.redrawOpenGlScene] to a delegate which draws your frame.
To force a redraw of the scene, call [SimpleWindow.redrawOpenGlSceneNow|window.redrawOpenGlSceneNow()] or to queue a redraw after processing the next batch of pending events, use [SimpleWindow.redrawOpenGlSceneSoon|window.redrawOpenGlSceneSoon].
simpledisplay supports both old-style `glBegin` and newer-style shader-based code all through its built-in bindings. See the next section of the docs to see a shader-based program.
This example program will draw a rectangle on your window using old-style OpenGL with a pulsating color:
---
import arsd.simpledisplay;
void main() {
auto window = new SimpleWindow(800, 600, "opengl 1", OpenGlOptions.yes, Resizability.allowResizing);
float otherColor = 0.0;
float colorDelta = 0.05;
window.redrawOpenGlScene = delegate() {
glLoadIdentity();
glBegin(GL_QUADS);
glColor3f(1.0, otherColor, 0);
glVertex3f(-0.8, -0.8, 0);
glColor3f(1.0, otherColor, 1.0);
glVertex3f(0.8, -0.8, 0);
glColor3f(0, 1.0, otherColor);
glVertex3f(0.8, 0.8, 0);
glColor3f(otherColor, 0, 1.0);
glVertex3f(-0.8, 0.8, 0);
glEnd();
};
window.eventLoop(50, () {
otherColor += colorDelta;
if(otherColor > 1.0) {
otherColor = 1.0;
colorDelta = -0.05;
}
if(otherColor < 0) {
otherColor = 0;
colorDelta = 0.05;
}
// at the end of the timer, we have to request a redraw
// or we won't see the changes.
window.redrawOpenGlSceneSoon();
});
}
---
My [arsd.game] module has some helpers for using old-style opengl to make 2D windows too. See: [arsd.game.create2dWindow].
$(H3 $(ID topic-modern-opengl) Modern OpenGL)
simpledisplay's opengl support, by default, is for "legacy" opengl. To use "modern" functions, you must opt-into them with a little more setup. But the library provides helpers for this too.
This example program shows how you can set up a shader to draw a rectangle:
---
module opengl3test;
import arsd.simpledisplay;
// based on https://learnopengl.com/Getting-started/Hello-Triangle
void main() {
// First thing we do, before creating the window, is declare what version we want.
setOpenGLContextVersion(3, 3);
// turning off legacy compat is required to use version 3.3 and newer
openGLContextCompatible = false;
uint VAO;
OpenGlShader shader;
// then we can create the window.
auto window = new SimpleWindow(800, 600, "opengl 3", OpenGlOptions.yes, Resizability.allowResizing);
// additional setup needs to be done when it is visible, simpledisplay offers a property
// for exactly that:
window.visibleForTheFirstTime = delegate() {
// now with the window loaded, we can start loading the modern opengl functions.
// you MUST set the context first.
window.setAsCurrentOpenGlContext;
// then load the remainder of the library
gl3.loadDynamicLibrary();
// now you can create the shaders, etc.
shader = new OpenGlShader(
OpenGlShader.Source(GL_VERTEX_SHADER, `
#version 330 core
layout (location = 0) in vec3 aPos;
void main() {
gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);
}
`),
OpenGlShader.Source(GL_FRAGMENT_SHADER, `
#version 330 core
out vec4 FragColor;
uniform vec4 mycolor;
void main() {
FragColor = mycolor;
}
`),
);
// and do whatever other setup you want.
float[] vertices = [
0.5f, 0.5f, 0.0f, // top right
0.5f, -0.5f, 0.0f, // bottom right
-0.5f, -0.5f, 0.0f, // bottom left
-0.5f, 0.5f, 0.0f // top left
];
uint[] indices = [ // note that we start from 0!
0, 1, 3, // first Triangle
1, 2, 3 // second Triangle
];
uint VBO, EBO;
glGenVertexArrays(1, &VAO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
glBindVertexArray(VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferDataSlice(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferDataSlice(GL_ELEMENT_ARRAY_BUFFER, indices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * float.sizeof, null);
glEnableVertexAttribArray(0);
// the library will set the initial viewport and trigger our first draw,
// so these next two lines are NOT needed. they are just here as comments
// to show what would happen next.
// glViewport(0, 0, window.width, window.height);
// window.redrawOpenGlSceneNow();
};
// this delegate is called any time the window needs to be redrawn or if you call `window.redrawOpenGlSceneNow;`
// it is our render method.
window.redrawOpenGlScene = delegate() {
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(shader.shaderProgram);
// the shader helper class has methods to set uniforms too
shader.uniforms.mycolor.opAssign(1.0, 1.0, 0, 1.0);
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, null);
};
window.eventLoop(0);
}
---
This program only draws the image once because that's all that is necessary, since it is static. If you want to do animation, you might set a pulse timer (which would be a fixed max fps, not necessarily consistent) or use a render loop in a separate thread.
$(H3 $(ID topic-images) Displaying images)
You can also load PNG images using [arsd.png].
---
// dmd example.d simpledisplay.d color.d png.d
import arsd.simpledisplay;
import arsd.png;
void main() {
auto image = Image.fromMemoryImage(readPng("image.png"));
displayImage(image);
}
---
Compile with `dmd example.d simpledisplay.d png.d`.
If you find an image file which is a valid png that [arsd.png] fails to load, please let me know. In the mean time of fixing the bug, you can probably convert the file into an easier-to-load format. Be sure to turn OFF png interlacing, as that isn't supported. Other things to try would be making the image smaller, or trying 24 bit truecolor mode with an alpha channel.
$(H3 $(ID topic-sprites) Sprites)
The [Sprite] class is used to make images on the display server for fast blitting to screen. This is especially important to use to support fast drawing of repeated images on a remote X11 link.
[Sprite] is also the only facility that currently supports alpha blending without using OpenGL .
$(H3 $(ID topic-clipboard) Clipboard)
The free functions [getClipboardText] and [setClipboardText] consist of simpledisplay's cross-platform clipboard support at this time.
It also has helpers for handling X-specific events.
$(H3 $(ID topic-dnd) Drag and Drop)
See [enableDragAndDrop] and [draggable].
$(H3 $(ID topic-timers) Timers)
There are two timers in simpledisplay: one is the pulse timeout you can set on the call to `window.eventLoop`, and the other is a customizable class, [Timer].
The pulse timeout is used by setting a non-zero interval as the first argument to `eventLoop` function and adding a zero-argument delegate to handle the pulse.
---
import arsd.simpledisplay;
void main() {
auto window = new SimpleWindow(400, 400);
// every 100 ms, it will draw a random line
// on the window.
window.eventLoop(100, {
auto painter = window.draw();
import std.random;
// random color
painter.outlineColor = Color(uniform(0, 256), uniform(0, 256), uniform(0, 256));
// random line
painter.drawLine(
Point(uniform(0, window.width), uniform(0, window.height)),
Point(uniform(0, window.width), uniform(0, window.height)));
});
}
---
The `Timer` class works similarly, but is created separately from the event loop. (It still fires through the event loop, though.) You may make as many instances of `Timer` as you wish.
The pulse timer and instances of the [Timer] class may be combined at will.
---
import arsd.simpledisplay;
void main() {
auto window = new SimpleWindow(400, 400);
auto timer = new Timer(1000, delegate {
auto painter = window.draw();
painter.clear();
});
window.eventLoop(0);
}
---
Timers are currently only implemented on Windows, using `SetTimer` and Linux, using `timerfd_create`. These deliver timeout messages through your application event loop.
$(H3 $(ID topic-os-helpers) OS-specific helpers)
simpledisplay carries a lot of code to help implement itself without extra dependencies, and much of this code is available for you too, so you may extend the functionality yourself.
See also: `xwindows.d` from my github.
$(H3 $(ID topic-os-extension) Extending with OS-specific functionality)
`handleNativeEvent` and `handleNativeGlobalEvent`.
$(H3 $(ID topic-integration) Integration with other libraries)
Integration with a third-party event loop is possible.
On Linux, you might want to support both terminal input and GUI input. You can do this by using simpledisplay together with eventloop.d and terminal.d.
$(H3 $(ID topic-guis) GUI widgets)
simpledisplay does not provide GUI widgets such as text areas, buttons, checkboxes, etc. It only gives basic windows, the ability to draw on it, receive input from it, and access native information for extension. You may write your own gui widgets with these, but you don't have to because I already did for you!
Download `minigui.d` from my github repository and add it to your project. minigui builds these things on top of simpledisplay and offers its own Window class (and subclasses) to use that wrap SimpleWindow, adding a new event and drawing model that is hookable by subwidgets, represented by their own classes.
Migrating to minigui from simpledisplay is often easy though, because they both use the same ScreenPainter API, and the same simpledisplay events are available, if you want them. (Though you may like using the minigui model, especially if you are familiar with writing web apps in the browser with Javascript.)
minigui still needs a lot of work to be finished at this time, but it already offers a number of useful classes.
$(H2 Platform-specific tips and tricks)
X_tips:
On X11, if you set an environment variable, `ARSD_SCALING_FACTOR`, you can control the per-monitor DPI scaling returned to the application. The format is `ARSD_SCALING_FACTOR=2;1`, for example, to set 2x scaling on your first monitor and 1x scaling on your second monitor. Support for this was added on March 22, 2022, the dub 10.7 release.
Windows_tips:
You can add icons or manifest files to your exe using a resource file.
To create a Windows .ico file, use the gimp or something. I'll write a helper
program later.
Create `yourapp.rc`:
```rc
1 ICON filename.ico
CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST "YourApp.exe.manifest"
```
And `yourapp.exe.manifest`:
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
version="1.0.0.0"
processorArchitecture="*"
name="CompanyName.ProductName.YourApplication"
type="win32"
/>
<description>Your application description here.</description>
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware> <!-- old style -->
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness> <!-- new style -->
<!-- Un-comment the line below to enable GDI-scaling in this project. This will enable text -->
<!-- to render crisply in DPI-unaware contexts -->
<!--<gdiScaling xmlns="http://schemas.microsoft.com/SMI/2017/WindowsSettings">true</gdiScaling>-->
</windowsSettings>
</application>
</assembly>
```
You can also just distribute yourapp.exe.manifest as a separate file alongside yourapp.exe, or link it in to the exe with linker command lines `/manifest:embed` and `/manifestinput:yourfile.exe.manifest`.
Doing this lets you opt into various new things since Windows XP.
See: https://docs.microsoft.com/en-us/windows/win32/SbsCs/application-manifests
$(H2 Tips)
$(H3 Name conflicts)
simpledisplay has a lot of symbols and more are liable to be added without notice, since it contains its own bindings as needed to accomplish its goals. Some of these may conflict with other bindings you use. If so, you can use a static import in D, possibly combined with a selective import:
---
static import sdpy = arsd.simpledisplay;
import arsd.simpledisplay : SimpleWindow;
void main() {
auto window = new SimpleWindow();
sdpy.EventLoop.get.run();
}
---
$(H2 $(ID developer-notes) Developer notes)
I don't have a Mac, so that code isn't maintained. I would like to have a Cocoa
implementation though.
The NativeSimpleWindowImplementation and NativeScreenPainterImplementation both
suck. If I was rewriting it, I wouldn't do it that way again.
This file must not have any more required dependencies. If you need bindings, add
them right to this file. Once it gets into druntime and is there for a while, remove
bindings from here to avoid conflicts (or put them in an appropriate version block
so it continues to just work on old dmd), but wait a couple releases before making the
transition so this module remains usable with older versions of dmd.
You may have optional dependencies if needed by putting them in version blocks or
template functions. You may also extend the module with other modules with UFCS without
actually editing this - that is nice to do if you can.
Try to make functions work the same way across operating systems. I typically make
it thinly wrap Windows, then emulate that on Linux.
A goal of this is to keep a gui hello world to less than 250 KB. This means avoiding
Phobos! So try to avoid it.
See more comments throughout the source.
I realize this file is fairly large, but over half that is just bindings at the bottom
or documentation at the top. Some of the classes are a bit big too, but hopefully easy
to understand. I suggest you jump around the source by looking for a particular
declaration you're interested in, like `class SimpleWindow` using your editor's search
function, then look at one piece at a time.
Authors: Adam D. Ruppe with the help of others. If you need help, please email me with
destructionator@gmail.com or find me on IRC. Our channel is #d on Freenode and you can
ping me, adam_d_ruppe, and I'll usually see it if I'm around.
I live in the eastern United States, so I will most likely not be around at night in
that US east timezone.
License: Copyright Adam D. Ruppe, 2011-2021. Released under the Boost Software License.
Building documentation: use my adrdox generator, `dub run adrdox`.
Examples:
$(DIV $(ID Event-example))
$(H3 $(ID event-example) Event example)
This program creates a window and draws events inside them as they
happen, scrolling the text in the window as needed. Run this program
and experiment to get a feel for where basic input events take place
in the library.
---
// dmd example.d simpledisplay.d color.d
import arsd.simpledisplay;
import std.conv;
void main() {
auto window = new SimpleWindow(Size(500, 500), "Event example - simpledisplay.d");
int y = 0;
void addLine(string text) {
auto painter = window.draw();
if(y + painter.fontHeight >= window.height) {
painter.scrollArea(Point(0, 0), window.width, window.height, 0, painter.fontHeight);
y -= painter.fontHeight;
}
painter.outlineColor = Color.red;
painter.fillColor = Color.black;
painter.drawRectangle(Point(0, y), window.width, painter.fontHeight);
painter.outlineColor = Color.white;
painter.drawText(Point(10, y), text);
y += painter.fontHeight;
}
window.eventLoop(1000,
() {
addLine("Timer went off!");
},
(KeyEvent event) {
addLine(to!string(event));
},
(MouseEvent event) {
addLine(to!string(event));
},
(dchar ch) {
addLine(to!string(ch));
}
);
}
---
If you are interested in more game writing with D, check out my gamehelpers.d which builds upon simpledisplay, and its other stand-alone support modules, simpleaudio.d and joystick.d, too.
$(COMMENT
This program displays a pie chart. Clicking on a color will increase its share of the pie.
---
---
)
+/
module arsd.simpledisplay;
// FIXME: tetris demo
// FIXME: space invaders demo
// FIXME: asteroids demo
/++ $(ID Pong-example)
$(H3 Pong)
This program creates a little Pong-like game. Player one is controlled
with the keyboard. Player two is controlled with the mouse. It demos
the pulse timer, event handling, and some basic drawing.
+/
version(demos)
unittest {
// dmd example.d simpledisplay.d color.d
import arsd.simpledisplay;
enum paddleMovementSpeed = 8;
enum paddleHeight = 48;
void main() {
auto window = new SimpleWindow(600, 400, "Pong game!");
int playerOnePosition, playerTwoPosition;
int playerOneMovement, playerTwoMovement;
int playerOneScore, playerTwoScore;
int ballX, ballY;
int ballDx, ballDy;
void serve() {
import std.random;
ballX = window.width / 2;
ballY = window.height / 2;
ballDx = uniform(-4, 4) * 3;
ballDy = uniform(-4, 4) * 3;
if(ballDx == 0)
ballDx = uniform(0, 2) == 0 ? 3 : -3;
}
serve();
window.eventLoop(50, // set a 50 ms timer pulls
// This runs once per timer pulse
delegate () {
auto painter = window.draw();
painter.clear();
// Update everyone's motion
playerOnePosition += playerOneMovement;
playerTwoPosition += playerTwoMovement;
ballX += ballDx;
ballY += ballDy;
// Bounce off the top and bottom edges of the window
if(ballY + 7 >= window.height)
ballDy = -ballDy;
if(ballY - 8 <= 0)
ballDy = -ballDy;
// Bounce off the paddle, if it is in position
if(ballX - 8 <= 16) {
if(ballY + 7 > playerOnePosition && ballY - 8 < playerOnePosition + paddleHeight) {
ballDx = -ballDx + 1; // add some speed to keep it interesting
ballDy += playerOneMovement; // and y movement based on your controls too
ballX = 24; // move it past the paddle so it doesn't wiggle inside
} else {
// Missed it
playerTwoScore ++;
serve();
}
}
if(ballX + 7 >= window.width - 16) { // do the same thing but for player 1
if(ballY + 7 > playerTwoPosition && ballY - 8 < playerTwoPosition + paddleHeight) {
ballDx = -ballDx - 1;
ballDy += playerTwoMovement;
ballX = window.width - 24;
} else {
// Missed it
playerOneScore ++;
serve();
}
}
// Draw the paddles
painter.outlineColor = Color.black;
painter.drawLine(Point(16, playerOnePosition), Point(16, playerOnePosition + paddleHeight));
painter.drawLine(Point(window.width - 16, playerTwoPosition), Point(window.width - 16, playerTwoPosition + paddleHeight));
// Draw the ball
painter.fillColor = Color.red;
painter.outlineColor = Color.yellow;
painter.drawEllipse(Point(ballX - 8, ballY - 8), Point(ballX + 7, ballY + 7));
// Draw the score
painter.outlineColor = Color.blue;
import std.conv;
painter.drawText(Point(64, 4), to!string(playerOneScore));
painter.drawText(Point(window.width - 64, 4), to!string(playerTwoScore));
},
delegate (KeyEvent event) {
// Player 1's controls are the arrow keys on the keyboard
if(event.key == Key.Down)
playerOneMovement = event.pressed ? paddleMovementSpeed : 0;
if(event.key == Key.Up)
playerOneMovement = event.pressed ? -paddleMovementSpeed : 0;
},
delegate (MouseEvent event) {
// Player 2's controls are mouse movement while the left button is held down
if(event.type == MouseEventType.motion && (event.modifierState & ModifierState.leftButtonDown)) {
if(event.dy > 0)
playerTwoMovement = paddleMovementSpeed;
else if(event.dy < 0)
playerTwoMovement = -paddleMovementSpeed;
} else {
playerTwoMovement = 0;
}
}
);
}
}
/++ $(H3 $(ID example-minesweeper) Minesweeper)
This minesweeper demo shows how we can implement another classic
game with simpledisplay and shows some mouse input and basic output
code.
+/
version(demos)
unittest {
import arsd.simpledisplay;
enum GameSquare {
mine = 0,
clear,
m1, m2, m3, m4, m5, m6, m7, m8
}
enum UserSquare {
unknown,
revealed,
flagged,
questioned
}
enum GameState {
inProgress,
lose,
win
}
GameSquare[] board;
UserSquare[] userState;
GameState gameState;
int boardWidth;
int boardHeight;
bool isMine(int x, int y) {
if(x < 0 || y < 0 || x >= boardWidth || y >= boardHeight)
return false;
return board[y * boardWidth + x] == GameSquare.mine;
}
GameState reveal(int x, int y) {
if(board[y * boardWidth + x] == GameSquare.clear) {
floodFill(userState, boardWidth, boardHeight,
UserSquare.unknown, UserSquare.revealed,
x, y,
(x, y) {
if(board[y * boardWidth + x] == GameSquare.clear)
return true;
else {
userState[y * boardWidth + x] = UserSquare.revealed;
return false;
}
});
} else {
userState[y * boardWidth + x] = UserSquare.revealed;
if(isMine(x, y))
return GameState.lose;
}
foreach(state; userState) {
if(state == UserSquare.unknown || state == UserSquare.questioned)
return GameState.inProgress;
}
return GameState.win;
}
void initializeBoard(int width, int height, int numberOfMines) {
boardWidth = width;
boardHeight = height;
board.length = width * height;
userState.length = width * height;
userState[] = UserSquare.unknown;
import std.algorithm, std.random, std.range;
board[] = GameSquare.clear;
foreach(minePosition; randomSample(iota(0, board.length), numberOfMines))
board[minePosition] = GameSquare.mine;
int x;
int y;
foreach(idx, ref square; board) {
if(square == GameSquare.clear) {
int danger = 0;
danger += isMine(x-1, y-1)?1:0;
danger += isMine(x-1, y)?1:0;
danger += isMine(x-1, y+1)?1:0;
danger += isMine(x, y-1)?1:0;
danger += isMine(x, y+1)?1:0;
danger += isMine(x+1, y-1)?1:0;
danger += isMine(x+1, y)?1:0;
danger += isMine(x+1, y+1)?1:0;
square = cast(GameSquare) (danger + 1);
}
x++;
if(x == width) {
x = 0;
y++;
}
}
}
void redraw(SimpleWindow window) {
import std.conv;
auto painter = window.draw();
painter.clear();
final switch(gameState) with(GameState) {
case inProgress:
break;
case win:
painter.fillColor = Color.green;
painter.drawRectangle(Point(0, 0), window.width, window.height);
return;
case lose:
painter.fillColor = Color.red;
painter.drawRectangle(Point(0, 0), window.width, window.height);
return;
}
int x = 0;
int y = 0;
foreach(idx, square; board) {
auto state = userState[idx];
final switch(state) with(UserSquare) {
case unknown:
painter.outlineColor = Color.black;
painter.fillColor = Color(128,128,128);
painter.drawRectangle(
Point(x * 20, y * 20),
20, 20
);
break;
case revealed:
if(square == GameSquare.clear) {
painter.outlineColor = Color.white;
painter.fillColor = Color.white;
painter.drawRectangle(
Point(x * 20, y * 20),
20, 20
);
} else {
painter.outlineColor = Color.black;
painter.fillColor = Color.white;
painter.drawText(
Point(x * 20, y * 20),
to!string(square)[1..2],
Point(x * 20 + 20, y * 20 + 20),
TextAlignment.Center | TextAlignment.VerticalCenter);
}
break;
case flagged:
painter.outlineColor = Color.black;
painter.fillColor = Color.red;
painter.drawRectangle(
Point(x * 20, y * 20),
20, 20
);
break;
case questioned:
painter.outlineColor = Color.black;
painter.fillColor = Color.yellow;
painter.drawRectangle(
Point(x * 20, y * 20),
20, 20
);
break;
}
x++;
if(x == boardWidth) {
x = 0;
y++;
}
}
}
void main() {
auto window = new SimpleWindow(200, 200);
initializeBoard(10, 10, 10);
redraw(window);
window.eventLoop(0,
delegate (MouseEvent me) {
if(me.type != MouseEventType.buttonPressed)
return;
auto x = me.x / 20;
auto y = me.y / 20;
if(x >= 0 && x < boardWidth && y >= 0 && y < boardHeight) {
if(me.button == MouseButton.left) {
gameState = reveal(x, y);
} else {
userState[y*boardWidth+x] = UserSquare.flagged;
}
redraw(window);
}
}
);
}
}
/*
version(OSX) {
version=without_opengl;
version=allow_unimplemented_features;
version=OSXCocoa;
pragma(linkerDirective, "-framework Cocoa");
}
*/
version(without_opengl) {
enum SdpyIsUsingIVGLBinds = false;
} else /*version(Posix)*/ {
static if (__traits(compiles, (){import iv.glbinds;})) {
enum SdpyIsUsingIVGLBinds = true;
public import iv.glbinds;
//pragma(msg, "SDPY: using iv.glbinds");
} else {
enum SdpyIsUsingIVGLBinds = false;
}
//} else {
// enum SdpyIsUsingIVGLBinds = false;
}
version(Windows) {
//import core.sys.windows.windows;
import core.sys.windows.winnls;
import core.sys.windows.windef;
import core.sys.windows.basetyps;
import core.sys.windows.winbase;
import core.sys.windows.winuser;
import core.sys.windows.shellapi;
import core.sys.windows.wingdi;
static import gdi = core.sys.windows.wingdi; // so i
pragma(lib, "gdi32");
pragma(lib, "user32");
// for AlphaBlend... a breaking change....
version(CRuntime_DigitalMars) { } else
pragma(lib, "msimg32");
} else version (linux) {
//k8: this is hack for rdmd. sorry.
static import core.sys.linux.epoll;
static import core.sys.linux.timerfd;
}
// FIXME: icons on Windows don't look quite right, I think the transparency mask is off.
// http://wiki.dlang.org/Simpledisplay.d
// see : http://www.sbin.org/doc/Xlib/chapt_09.html section on Keyboard Preferences re: scroll lock led
// Cool stuff: I want right alt and scroll lock to do different stuff for personal use. maybe even right ctrl
// but can i control the scroll lock led
// Note: if you are using Image on X, you might want to do:
/*
static if(UsingSimpledisplayX11) {
if(!Image.impl.xshmAvailable) {
// the images will use the slower XPutImage, you might
// want to consider an alternative method to get better speed
}
}
If the shared memory extension is available though, simpledisplay uses it
for a significant speed boost whenever you draw large Images.
*/
// CHANGE FROM LAST VERSION: the window background is no longer fixed, so you might want to fill the screen with a particular color before drawing.
// WARNING: if you are using with_eventloop, don't forget to call XFlush(XDisplayConnection.get()); before calling loop()!
/*
Biggest FIXME:
make sure the key event numbers match between X and Windows OR provide symbolic constants on each system
clean up opengl contexts when their windows close
fix resizing the bitmaps/pixmaps
*/
// BTW on Windows:
// -L/SUBSYSTEM:WINDOWS:5.0
// to dmd will make a nice windows binary w/o a console if you want that.
/*
Stuff to add:
use multibyte functions everywhere we can
OpenGL windows
more event stuff
extremely basic windows w/ no decoration for tooltips, splash screens, etc.
resizeEvent
and make the windows non-resizable by default,
or perhaps stretched (if I can find something in X like StretchBlt)
take a screenshot function!
Pens and brushes?
Maybe a global event loop?
Mouse deltas
Key items
*/
/*
From MSDN:
You can also use the GET_X_LPARAM or GET_Y_LPARAM macro to extract the x- or y-coordinate.
Important Do not use the LOWORD or HIWORD macros to extract the x- and y- coordinates of the cursor position because these macros return incorrect results on systems with multiple monitors. Systems with multiple monitors can have negative x- and y- coordinates, and LOWORD and HIWORD treat the coordinates as unsigned quantities.
*/
version(linux) {
version = X11;
version(without_libnotify) {
// we cool
}
else
version = libnotify;
}
version(libnotify) {
pragma(lib, "dl");
import core.sys.posix.dlfcn;
void delegate()[int] libnotify_action_delegates;
int libnotify_action_delegates_count;
extern(C) static void libnotify_action_callback_sdpy(void* notification, char* action, void* user_data) {
auto idx = cast(int) user_data;
if(auto dgptr = idx in libnotify_action_delegates) {
(*dgptr)();
libnotify_action_delegates.remove(idx);
}
}
struct C_DynamicLibrary {
void* handle;
this(string name) {
handle = dlopen((name ~ "\0").ptr, RTLD_NOW);
if(handle is null)
throw new Exception("dlopen");
}
void close() {
dlclose(handle);
}
~this() {
// close
}
// FIXME: this looks up by name every time....
template call(string func, Ret, Args...) {
extern(C) Ret function(Args) fptr;
typeof(fptr) call() {
fptr = cast(typeof(fptr)) dlsym(handle, func);
return fptr;
}
}
}
C_DynamicLibrary* libnotify;
}
version(OSX) {
version(OSXCocoa) {}
else { version = X11; }
}
//version = OSXCocoa; // this was written by KennyTM
version(FreeBSD)
version = X11;
version(Solaris)
version = X11;
version(X11) {
version(without_xft) {}
else version=with_xft;
}
void featureNotImplemented()() {
version(allow_unimplemented_features)
throw new NotYetImplementedException();
else
static assert(0);
}
// these are so the static asserts don't trigger unless you want to
// add support to it for an OS
version(Windows)
version = with_timer;
version(linux)
version = with_timer;
version(with_timer)
enum bool SimpledisplayTimerAvailable = true;
else
enum bool SimpledisplayTimerAvailable = false;
/// If you have to get down and dirty with implementation details, this helps figure out if Windows is available you can `static if(UsingSimpledisplayWindows) ...` more reliably than `version()` because `version` is module-local.
version(Windows)
enum bool UsingSimpledisplayWindows = true;
else
enum bool UsingSimpledisplayWindows = false;
/// If you have to get down and dirty with implementation details, this helps figure out if X is available you can `static if(UsingSimpledisplayX11) ...` more reliably than `version()` because `version` is module-local.
version(X11)
enum bool UsingSimpledisplayX11 = true;
else
enum bool UsingSimpledisplayX11 = false;
/// If you have to get down and dirty with implementation details, this helps figure out if Cocoa is available you can `static if(UsingSimpledisplayCocoa) ...` more reliably than `version()` because `version` is module-local.
version(OSXCocoa)
enum bool UsingSimpledisplayCocoa = true;
else
enum bool UsingSimpledisplayCocoa = false;
/// Does this platform support multiple windows? If not, trying to create another will cause it to throw an exception.
version(Windows)
enum multipleWindowsSupported = true;
else version(X11)
enum multipleWindowsSupported = true;
else version(OSXCocoa)
enum multipleWindowsSupported = true;
else
static assert(0);
version(without_opengl)
enum bool OpenGlEnabled = false;
else
enum bool OpenGlEnabled = true;
/++
Adds the necessary pragmas to your application to use the Windows gui subsystem.
If you mix this in above your `main` function, you no longer need to use the linker
flags explicitly. It does the necessary version blocks for various compilers and runtimes.
It does nothing if not compiling for Windows, so you need not version it out yourself.
Please note that Windows gui subsystem applications must NOT use std.stdio's stdout and
stderr writeln. It will fail and throw an exception.
This will NOT work with plain `dmd` on Windows; you must use `dmd -m32mscoff` or `dmd -m64`.
History:
Added November 24, 2021 (dub v10.4)
+/
mixin template EnableWindowsSubsystem() {
version(Windows)
version(CRuntime_Microsoft) {
pragma(linkerDirective, "/subsystem:windows");
version(LDC)
pragma(linkerDirective, "/entry:wmainCRTStartup");
else
pragma(linkerDirective, "/entry:mainCRTStartup");
}
}
/++
After selecting a type from [WindowTypes], you may further customize
its behavior by setting one or more of these flags.
The different window types have different meanings of `normal`. If the
window type already is a good match for what you want to do, you should
just use [WindowFlags.normal], the default, which will do the right thing
for your users.
The window flags will not always be honored by the operating system
and window managers; they are hints, not commands.
+/
enum WindowFlags : int {
normal = 0, ///
skipTaskbar = 1, ///
alwaysOnTop = 2, ///
alwaysOnBottom = 4, ///
cannotBeActivated = 8, ///
alwaysRequestMouseMotionEvents = 16, /// By default, simpledisplay will attempt to optimize mouse motion event reporting when it detects a remote connection, causing them to only be issued if input is grabbed (see: [SimpleWindow.grabInput]). This means doing hover effects and mouse game control on a remote X connection may not work right. Include this flag to override this optimization and always request the motion events. However btw, if you are doing mouse game control, you probably want to grab input anyway, and hover events are usually expendable! So think before you use this flag.
extraComposite = 32, /// On windows this will make this a layered windows (not supported for child windows before windows 8) to support transparency and improve animation performance.
/++
Sets the window as a short-lived child of its parent, but unlike an ordinary child,
it is still a top-level window. This should NOT be set separately for most window types.
A transient window will not keep the application open if its main window closes.
$(PITFALL This may not be correctly implemented and its behavior is subject to change.)
From the ICCM:
$(BLOCKQUOTE
It is important not to confuse WM_TRANSIENT_FOR with override-redirect. WM_TRANSIENT_FOR should be used in those cases where the pointer is not grabbed while the window is mapped (in other words, if other windows are allowed to be active while the transient is up). If other windows must be prevented from processing input (for example, when implementing pop-up menus), use override-redirect and grab the pointer while the window is mapped.
$(CITE https://tronche.com/gui/x/icccm/sec-4.html)
)
So if you are using a window type that already describes this like [WindowTypes.dropdownMenu] etc., you should not use this flag.
History:
Added February 23, 2021 but not yet stabilized.
+/
transient = 64,
/++
This indicates that the window manages its own platform-specific child window input focus. You must use a delegate, [SimpleWindow.setRequestedInputFocus], to set the input when requested. This delegate returns the handle to the window that should receive the focus.
This is currently only used for the WM_TAKE_FOCUS protocol on X11 at this time.
History:
Added April 1, 2022
+/
managesChildWindowFocus = 128,
dontAutoShow = 0x1000_0000, /// Don't automatically show window after creation; you will have to call `show()` manually.
}
/++
When creating a window, you can pass a type to SimpleWindow's constructor,
then further customize the window by changing `WindowFlags`.
You should mostly only need [normal], [undecorated], and [eventOnly] for normal
use. The others are there to build a foundation for a higher level GUI toolkit,
but are themselves not as high level as you might think from their names.
This list is based on the EMWH spec for X11.
http://standards.freedesktop.org/wm-spec/1.4/ar01s05.html#idm139704063786896
+/
enum WindowTypes : int {
/// An ordinary application window.
normal,
/// A generic window without a title bar or border. You can draw on the entire area of the screen it takes up and use it as you wish. Remember that users don't really expect these though, so don't use it where a window of any other type is appropriate.
undecorated,
/// A window that doesn't actually display on screen. You can use it for cases where you need a dummy window handle to communicate with or something.
eventOnly,
/// A drop down menu, such as from a menu bar
dropdownMenu,
/// A popup menu, such as from a right click
popupMenu,
/// A popup bubble notification
notification,
/*
menu, /// a tearable menu bar
splashScreen, /// a loading splash screen for your application
tooltip, /// A tiny window showing temporary help text or something.
comboBoxDropdown,
dialog,
toolbar
*/
/// a child nested inside the parent. You must pass a parent window to the ctor
nestedChild,
/++
The type you get when you pass in an existing browser handle, which means most
of simpledisplay's fancy things will not be done since they were never set up.
Using this to the main SimpleWindow constructor explicitly will trigger an assertion
failure; you should use the existing handle constructor.
History:
Added November 17, 2022 (previously it would have type `normal`)
+/
minimallyWrapped
}
private __gshared ushort sdpyOpenGLContextVersion = 0; // default: use legacy call
private __gshared bool sdpyOpenGLContextCompatible = true; // default: allow "deprecated" features
private __gshared char* sdpyWindowClassStr = null;
private __gshared bool sdpyOpenGLContextAllowFallback = false;
/**
Set OpenGL context version to use. This has no effect on non-OpenGL windows.
You may want to change context version if you want to use advanced shaders or
other modern OpenGL techinques. This setting doesn't affect already created
windows. You may use version 2.1 as your default, which should be supported
by any box since 2006, so seems to be a reasonable choice.
Note that by default version is set to `0`, which forces SimpleDisplay to use
old context creation code without any version specified. This is the safest
way to init OpenGL, but it may not give you access to advanced features.
See available OpenGL versions here: https://en.wikipedia.org/wiki/OpenGL
*/
void setOpenGLContextVersion() (ubyte hi, ubyte lo) { sdpyOpenGLContextVersion = cast(ushort)(hi<<8|lo); }
/**
Set OpenGL context mode. Modern (3.0+) OpenGL versions deprecated old fixed
pipeline functions, and without "compatible" mode you won't be able to use
your old non-shader-based code with such contexts. By default SimpleDisplay
creates compatible context, so you can gradually upgrade your OpenGL code if
you want to (or leave it as is, as it should "just work").
*/
@property void openGLContextCompatible() (bool v) { sdpyOpenGLContextCompatible = v; }
/**
Set to `true` to allow creating OpenGL context with lower version than requested
instead of throwing. If fallback was activated (or legacy OpenGL was requested),
`openGLContextFallbackActivated()` will return `true`.
*/
@property void openGLContextAllowFallback() (bool v) { sdpyOpenGLContextAllowFallback = v; }
/**
After creating OpenGL window, you can check this to see if you got only "legacy" OpenGL context.
*/
@property bool openGLContextFallbackActivated() () { return (sdpyOpenGLContextVersion == 0); }
/**
Set window class name for all following `new SimpleWindow()` calls.
WARNING! For Windows, you should set your class name before creating any
window, and NEVER change it after that!
*/
void sdpyWindowClass (const(char)[] v) {
import core.stdc.stdlib : realloc;
if (v.length == 0) v = "SimpleDisplayWindow";
sdpyWindowClassStr = cast(char*)realloc(sdpyWindowClassStr, v.length+1);
if (sdpyWindowClassStr is null) return; // oops
sdpyWindowClassStr[0..v.length+1] = 0;
sdpyWindowClassStr[0..v.length] = v[];
}
/**
Get current window class name.
*/
string sdpyWindowClass () {
if (sdpyWindowClassStr is null) return null;
foreach (immutable idx; 0..size_t.max-1) {
if (sdpyWindowClassStr[idx] == 0) return sdpyWindowClassStr[0..idx].idup;
}
return null;
}
/++
Returns the logical DPI of the default monitor. [0] is width, [1] is height (they are usually the same though). You may wish to round the numbers off. This isn't necessarily related to the physical side of the screen; it is associated with a user-defined scaling factor.
If you want per-monitor dpi values, check [SimpleWindow.actualDpi], but you can fall back to this if it returns 0.
+/
float[2] getDpi() {
float[2] dpi;
version(Windows) {
HDC screen = GetDC(null);
dpi[0] = GetDeviceCaps(screen, LOGPIXELSX);
dpi[1] = GetDeviceCaps(screen, LOGPIXELSY);
} else version(X11) {
auto display = XDisplayConnection.get;
auto screen = DefaultScreen(display);
void fallback() {
/+
// 25.4 millimeters in an inch...
dpi[0] = cast(float) DisplayWidth(display, screen) / DisplayWidthMM(display, screen) * 25.4;
dpi[1] = cast(float) DisplayHeight(display, screen) / DisplayHeightMM(display, screen) * 25.4;
+/
// the physical size isn't actually as important as the logical size since this is
// all about scaling really
dpi[0] = 96;
dpi[1] = 96;
}
auto xft = getXftDpi();
if(xft is float.init)
fallback();
else {
dpi[0] = xft;
dpi[1] = xft;
}
}
return dpi;
}
version(X11)
float getXftDpi() {
auto display = XDisplayConnection.get;
char* resourceString = XResourceManagerString(display);
XrmInitialize();
if (resourceString) {
auto db = XrmGetStringDatabase(resourceString);
XrmValue value;
char* type;
if (XrmGetResource(db, "Xft.dpi", "String", &type, &value) == true) {
if (value.addr) {
import core.stdc.stdlib;
return atof(cast(char*) value.addr);
}
}
}
return float.init;
}
/++
Implementation used by [SimpleWindow.takeScreenshot].
Params:
handle = the native window handle. If `NativeWindowHandle.init`, it will attempt to get the whole screen.
width = the width of the image you wish to capture. If 0, it will attempt to capture the full width of the target.
height = the height of the image you wish to capture. If 0, it will attempt to capture the full height of the target.
x = the x-offset of the image to capture, from the left.
y = the y-offset of the image to capture, from the top.
History:
Added on March 14, 2021
Documented public on September 23, 2021 with full support for null params (dub 10.3)
+/
TrueColorImage trueColorImageFromNativeHandle(NativeWindowHandle handle, int width = 0, int height = 0, int x = 0, int y = 0) {
TrueColorImage got;
version(X11) {
auto display = XDisplayConnection.get;
if(handle == 0)
handle = RootWindow(display, DefaultScreen(display));
if(width == 0 || height == 0) {
Window root;
int xpos, ypos;
uint widthret, heightret, borderret, depthret;
XGetGeometry(display, handle, &root, &xpos, &ypos, &widthret, &heightret, &borderret, &depthret);
if(width == 0)
width = widthret;
if(height == 0)
height = heightret;
}
auto image = XGetImage(display, handle, x, y, width, height, (cast(c_ulong) ~0) /*AllPlanes*/, ImageFormat.ZPixmap);
// https://github.com/adamdruppe/arsd/issues/98
auto i = new Image(image);
got = i.toTrueColorImage();
XDestroyImage(image);
} else version(Windows) {
auto hdc = GetDC(handle);
scope(exit) ReleaseDC(handle, hdc);
if(width == 0 || height == 0) {
BITMAP bmHeader;
auto bm = GetCurrentObject(hdc, OBJ_BITMAP);
GetObject(bm, BITMAP.sizeof, &bmHeader);
if(width == 0)
width = bmHeader.bmWidth;
if(height == 0)
height = bmHeader.bmHeight;
}
auto i = new Image(width, height);
HDC hdcMem = CreateCompatibleDC(hdc);
HBITMAP hbmOld = SelectObject(hdcMem, i.handle);
BitBlt(hdcMem, x, y, width, height, hdc, 0, 0, SRCCOPY);
SelectObject(hdcMem, hbmOld);
DeleteDC(hdcMem);
got = i.toTrueColorImage();
} else featureNotImplemented();
return got;
}
version(Windows) extern(Windows) private alias SetProcessDpiAwarenessContext_t = BOOL function(HANDLE);
version(Windows) extern(Windows) private __gshared UINT function(HWND) GetDpiForWindow;
version(Windows) extern(Windows) private __gshared BOOL function(UINT, UINT, PVOID, UINT, UINT) SystemParametersInfoForDpi;
version(Windows)
shared static this() {
auto lib = LoadLibrary("User32.dll");
if(lib is null)
return;
//scope(exit)
//FreeLibrary(lib);
SetProcessDpiAwarenessContext_t SetProcessDpiAwarenessContext = cast(SetProcessDpiAwarenessContext_t) GetProcAddress(lib, "SetProcessDpiAwarenessContext");
if(SetProcessDpiAwarenessContext is null)
return;
enum DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = cast(HANDLE) -4;
if(!SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)) {
//writeln(GetLastError());
}
GetDpiForWindow = cast(typeof(GetDpiForWindow)) GetProcAddress(lib, "GetDpiForWindow");
SystemParametersInfoForDpi = cast(typeof(SystemParametersInfoForDpi)) GetProcAddress(lib, "SystemParametersInfoForDpi");
}
/++
Blocking mode for event loop calls associated with a window instance.
History:
Added December 8, 2021 (dub v10.5). Prior to that, all calls to
`window.eventLoop` were the same as calls to `EventLoop.get.run`; that
is, all would block until the application quit.
That behavior can still be achieved here with `untilApplicationQuits`,
or explicitly calling the top-level `EventLoop.get.run` function.
+/
enum BlockingMode {
/++
The event loop call will block until the whole application is ready
to quit if it is the only one running, but if it is nested inside
another one, it will only block until the window you're calling it on
closes.
+/
automatic = 0x00,
/++
The event loop call will only return when the whole application
is ready to quit. This usually means all windows have been closed.
This is appropriate for your main application event loop.
+/
untilApplicationQuits = 0x01,
/++
The event loop will return when the window you're calling it on
closes. If there are other windows still open, they may be destroyed
unless you have another event loop running later.
This might be appropriate for a modal dialog box loop. Remember that
other windows are still processing input though, so you can end up
with a lengthy call stack if this happens in a loop, similar to a
recursive function (well, it literally is a recursive function, just
not an obvious looking one).
+/
untilWindowCloses = 0x02,
/++
If an event loop is already running, this call will immediately
return, allowing the existing loop to handle it. If not, this call
will block until the condition you bitwise-or into the flag.
The default is to block until the application quits, same as with
the `automatic` setting (since if it were nested, which triggers until
window closes in automatic, this flag would instead not block at all),
but if you used `BlockingMode.onlyIfNotNested | BlockingMode.untilWindowCloses`,
it will only nest until the window closes. You might want that if you are
going to open two windows simultaneously and want closing just one of them
to trigger the event loop return.
+/
onlyIfNotNested = 0x10,
}
/++
The flagship window class.
SimpleWindow tries to make ordinary windows very easy to create and use without locking you
out of more advanced or complex features of the underlying windowing system.
For many applications, you can simply call `new SimpleWindow(some_width, some_height, "some title")`
and get a suitable window to work with.
From there, you can opt into additional features, like custom resizability and OpenGL support
with the next two constructor arguments. Or, if you need even more, you can set a window type
and customization flags with the final two constructor arguments.
If none of that works for you, you can also create a window using native function calls, then
wrap the window in a SimpleWindow instance by calling `new SimpleWindow(native_handle)`. Remember,
though, if you do this, managing the window is still your own responsibility! Notably, you
will need to destroy it yourself.
+/
class SimpleWindow : CapableOfHandlingNativeEvent, CapableOfBeingDrawnUpon {
/++
Copies the window's current state into a [TrueColorImage].
Be warned: this can be a very slow operation
History:
Actually implemented on March 14, 2021
+/
TrueColorImage takeScreenshot() {
version(Windows)
return trueColorImageFromNativeHandle(impl.hwnd, _width, _height);
else version(OSXCocoa)
throw new NotYetImplementedException();
else
return trueColorImageFromNativeHandle(impl.window, _width, _height);
}
/++
Returns the actual logical DPI for the window on its current display monitor. If the window
straddles monitors, it will return the value of one or the other in a platform-defined manner.
Please note this function may return zero if it doesn't know the answer!
On Windows, it returns the dpi per monitor if the operating system supports it (Windows 10),
or a system dpi value if not, which will live-update if the OS supports it (Windows 8 and up).
On X, it reads the xrandr extension to determine monitor positions and sizes. On some systems,
this is not provided, meaning it will return 0. Otherwise, it will determine which monitor the
window primarily resides on by checking the center point of the window against the monitor map.
Returns:
0 if unknown. Otherwise, a rounded value of dots per inch reported by the monitor. It
assumes the X and Y dpi are the same.
History:
Added November 26, 2021 (dub v10.4)
It said "physical dpi" in the description prior to July 29, 2022, but the behavior was
always a logical value on Windows and usually one on Linux too, so now the docs reflect
that.
Bugs:
Probably plenty. I haven't done a lot of tests on this. I know it doesn't automatically
just work on linux; you need to set ARSD_SCALING_FACTOR as an environment variable to
set it. Set ARSD_SCALING_FACTOR=1;1.5 for example to set it to 1x on the primary monitor
and 1.5 on the secondary monitor.
The local dpi is not necessarily related to the physical dpi of the monitor. The name
is a historical misnomer - the real thing of interest is the scale factor and due to
compatibility concerns the scale would modify dpi values to trick applications. But since
that's the terminology common out there, I used it too.
See_Also:
[getDpi] gives the value provided for the default monitor. Not necessarily the same
as this since the window many be on a different monitor, but it is a reasonable fallback
to use if `actualDpi` returns 0.
[onDpiChanged] is changed when `actualDpi` has changed.
+/
int actualDpi() {
if(!actualDpiLoadAttempted) {
// FIXME: do the actual monitor we are on
// and on X this is a good chance to load the monitor map.
version(Windows) {
if(GetDpiForWindow)
actualDpi_ = GetDpiForWindow(impl.hwnd);
} else version(X11) {
if(!xRandrInfoLoadAttemped) {
xRandrInfoLoadAttemped = true;
if(!XRandrLibrary.attempted) {
XRandrLibrary.loadDynamicLibrary();
}
if(XRandrLibrary.loadSuccessful) {
auto display = XDisplayConnection.get;
int scratch;
int major, minor;
if(!XRRQueryExtension(display, &xrrEventBase, &scratch))
goto fallback;
XRRQueryVersion(display, &major, &minor);
if(major <= 1 && minor < 5)
goto fallback;
int count;
XRRMonitorInfo *monitors = XRRGetMonitors(display, RootWindow(display, DefaultScreen(display)), true, &count);
if(monitors is null)
goto fallback;
scope(exit) XRRFreeMonitors(monitors);
MonitorInfo.info = MonitorInfo.info[0 .. 0];
MonitorInfo.info.assumeSafeAppend();
foreach(idx, monitor; monitors[0 .. count]) {
MonitorInfo.info ~= MonitorInfo(
Rectangle(Point(monitor.x, monitor.y), Size(monitor.width, monitor.height)),
Size(monitor.mwidth, monitor.mheight),
cast(int) (customScalingFactorForMonitor(cast(int) idx) * getDpi()[0])
);
/+
if(monitor.mwidth == 0 || monitor.mheight == 0)
// unknown physical size, just guess 96 to avoid divide by zero
MonitorInfo.info ~= MonitorInfo(
Rectangle(Point(monitor.x, monitor.y), Size(monitor.width, monitor.height)),
Size(monitor.mwidth, monitor.mheight),
96
);
else
// and actual thing
MonitorInfo.info ~= MonitorInfo(
Rectangle(Point(monitor.x, monitor.y), Size(monitor.width, monitor.height)),
Size(monitor.mwidth, monitor.mheight),
minInternal(
// millimeter to int then rounding up.
cast(int)(monitor.width * 25.4 / monitor.mwidth + 0.5),
cast(int)(monitor.height * 25.4 / monitor.mheight + 0.5)
)
);
+/
}
// import std.stdio; writeln("Here", MonitorInfo.info);
}
}
if(XRandrLibrary.loadSuccessful) {
updateActualDpi(true);
//import std.stdio; writeln("updated");
if(!requestedInput) {
// this is what requests live updates should the configuration change
// each time you select input, it sends an initial event, so very important
// to not get into a loop of selecting input, getting event, updating data,
// and reselecting input...
requestedInput = true;
XRRSelectInput(display, impl.window, RRScreenChangeNotifyMask);
//import std.stdio; writeln("requested input");
}
} else {
fallback:
// make sure we disable events that aren't coming
xrrEventBase = -1;
// best guess... respect the custom scaling user command to some extent at least though
actualDpi_ = cast(int) (getDpi()[0] * customScalingFactorForMonitor(0));
}
}
actualDpiLoadAttempted = true;
}
return actualDpi_;
}
private int actualDpi_;
private bool actualDpiLoadAttempted;
version(X11) private {
bool requestedInput;
static bool xRandrInfoLoadAttemped;
struct MonitorInfo {
Rectangle position;
Size size;
int dpi;
static MonitorInfo[] info;
}
bool screenPositionKnown;
int screenPositionX;
int screenPositionY;
void updateActualDpi(bool loadingNow = false) {
if(!loadingNow && !actualDpiLoadAttempted)
actualDpi(); // just to make it do the load
foreach(idx, m; MonitorInfo.info) {
if(m.position.contains(Point(screenPositionX + this.width / 2, screenPositionY + this.height / 2))) {
bool changed = actualDpi_ && actualDpi_ != m.dpi;
actualDpi_ = m.dpi;
//import std.stdio; writeln("monitor ", idx);
if(changed && onDpiChanged)
onDpiChanged();
break;
}
}
}
}
/++
Sent when the window is moved to a new DPI context, for example, when it is dragged between monitors
or if the window is moved to a new remote connection or a monitor is hot-swapped.
History:
Added November 26, 2021 (dub v10.4)
See_Also:
[actualDpi]
+/
void delegate() onDpiChanged;
version(X11) {
void recreateAfterDisconnect() {
if(!stateDiscarded) return;
if(_parent !is null && _parent.stateDiscarded)
_parent.recreateAfterDisconnect();
bool wasHidden = hidden;
activeScreenPainter = null; // should already be done but just to confirm
actualDpi_ = 0;
actualDpiLoadAttempted = false;
xRandrInfoLoadAttemped = false;
impl.createWindow(_width, _height, _title, openglMode, _parent);
if(auto dh = dropHandler) {
dropHandler = null;
enableDragAndDrop(this, dh);
}
if(recreateAdditionalConnectionState)
recreateAdditionalConnectionState();
hidden = wasHidden;
stateDiscarded = false;
}
bool stateDiscarded;
void discardConnectionState() {
if(XDisplayConnection.display)
impl.dispose(); // if display is already null, it is hopeless to try to destroy stuff on it anyway
if(discardAdditionalConnectionState)
discardAdditionalConnectionState();
stateDiscarded = true;
}
void delegate() discardAdditionalConnectionState;
void delegate() recreateAdditionalConnectionState;
}
private DropHandler dropHandler;
SimpleWindow _parent;
bool beingOpenKeepsAppOpen = true;
/++
This creates a window with the given options. The window will be visible and able to receive input as soon as you start your event loop. You may draw on it immediately after creating the window, without needing to wait for the event loop to start if you want.
The constructor tries to have sane default arguments, so for many cases, you only need to provide a few of them.
Params:
width = the width of the window's client area, in pixels
height = the height of the window's client area, in pixels
title = the title of the window (seen in the title bar, taskbar, etc.). You can change it after construction with the [SimpleWindow.title] property.
opengl = [OpenGlOptions] are yes and no. If yes, it creates an OpenGL context on the window.
resizable = [Resizability] has three options:
$(P `allowResizing`, which allows the window to be resized by the user. The `windowResized` delegate will be called when the size is changed.)
$(P `fixedSize` will not allow the user to resize the window.)
$(P `automaticallyScaleIfPossible` will allow the user to resize, but will still present the original size to the API user. The contents you draw will be scaled to the size the user chose. If this scaling is not efficient, the window will be fixed size. The `windowResized` event handler will never be called. This is the default.)
windowType = The type of window you want to make.
customizationFlags = A way to make a window without a border, always on top, skip taskbar, and more. Do not use this if one of the pre-defined [WindowTypes], given in the `windowType` argument, is a good match for what you need.
parent = the parent window, if applicable. This makes the child window nested inside the parent unless you set [WindowFlags.transient], which makes it a top-level window merely owned by the "parent".
+/
this(int width = 640, int height = 480, string title = null, OpenGlOptions opengl = OpenGlOptions.no, Resizability resizable = Resizability.automaticallyScaleIfPossible, WindowTypes windowType = WindowTypes.normal, int customizationFlags = WindowFlags.normal, SimpleWindow parent = null) {
claimGuiThread();
version(sdpy_thread_checks) assert(thisIsGuiThread);
this._width = this._virtualWidth = width;
this._height = this._virtualHeight = height;
this.openglMode = opengl;
version(X11) {
// auto scale not implemented except with opengl and even there it is kinda weird
if(resizable == Resizability.automaticallyScaleIfPossible && opengl == OpenGlOptions.no)
resizable = Resizability.fixedSize;
}
this.resizability = resizable;
this.windowType = windowType;
this.customizationFlags = customizationFlags;
this._title = (title is null ? "D Application" : title);
this._parent = parent;
impl.createWindow(width, height, this._title, opengl, parent);
if(windowType == WindowTypes.dropdownMenu || windowType == WindowTypes.popupMenu || windowType == WindowTypes.nestedChild || (customizationFlags & WindowFlags.transient))
beingOpenKeepsAppOpen = false;
}
/// ditto
this(int width, int height, string title, Resizability resizable, OpenGlOptions opengl = OpenGlOptions.no, WindowTypes windowType = WindowTypes.normal, int customizationFlags = WindowFlags.normal, SimpleWindow parent = null) {
this(width, height, title, opengl, resizable, windowType, customizationFlags, parent);
}
/// Same as above, except using the `Size` struct instead of separate width and height.
this(Size size, string title = null, OpenGlOptions opengl = OpenGlOptions.no, Resizability resizable = Resizability.automaticallyScaleIfPossible) {
this(size.width, size.height, title, opengl, resizable);
}
/// ditto
this(Size size, string title, Resizability resizable, OpenGlOptions opengl = OpenGlOptions.no) {
this(size, title, opengl, resizable);
}
/++
Creates a window based on the given [Image]. It's client area
width and height is equal to the image. (A window's client area
is the drawable space inside; it excludes the title bar, etc.)
Windows based on images will not be resizable and do not use OpenGL.
It will draw the image in upon creation, but this will be overwritten
upon any draws, including the initial window visible event.
You probably do not want to use this and it may be removed from
the library eventually, or I might change it to be a "permanent"
background image; one that is automatically drawn on it before any
other drawing event. idk.
+/
this(Image image, string title = null) {
this(image.width, image.height, title);
this.image = image;
}
/++
Wraps a native window handle with very little additional processing - notably no destruction
this is incomplete so don't use it for much right now. The purpose of this is to make native
windows created through the low level API (so you can use platform-specific options and
other details SimpleWindow does not expose) available to the event loop wrappers.
+/
this(NativeWindowHandle nativeWindow) {
windowType = WindowTypes.minimallyWrapped;
version(Windows)
impl.hwnd = nativeWindow;
else version(X11) {
impl.window = nativeWindow;
if(nativeWindow)
display = XDisplayConnection.get(); // get initial display to not segfault
} else version(OSXCocoa)
throw new NotYetImplementedException();
else featureNotImplemented();
// FIXME: set the size correctly
_width = 1;
_height = 1;
if(nativeWindow)
nativeMapping[nativeWindow] = this;
beingOpenKeepsAppOpen = false;
if(nativeWindow)
CapableOfHandlingNativeEvent.nativeHandleMapping[nativeWindow] = this;
_suppressDestruction = true; // so it doesn't try to close
}
/++
Used iff [WindowFlags.managesChildWindowFocus] is set when the window is created.
The delegate will be called when the window manager asks you to take focus.
This is currently only used for the WM_TAKE_FOCUS protocol on X11 at this time.
History:
Added April 1, 2022 (dub v10.8)
+/
SimpleWindow delegate() setRequestedInputFocus;
/// Experimental, do not use yet
/++
Grabs exclusive input from the user until you release it with
[releaseInputGrab].
Note: it is extremely rude to do this without good reason.
Reasons may include doing some kind of mouse drag operation
or popping up a temporary menu that should get events and will
be dismissed at ease by the user clicking away.
Params:
keyboard = do you want to grab keyboard input?
mouse = grab mouse input?
confine = confine the mouse cursor to inside this window?
History:
Prior to March 11, 2021, grabbing the keyboard would always also
set the X input focus. Now, it only focuses if it is a non-transient
window and otherwise manages the input direction internally.
This means spurious focus/blur events will no longer be sent and the
application will not steal focus from other applications (which the
window manager may have rejected anyway).
+/
void grabInput(bool keyboard = true, bool mouse = true, bool confine = false) {
static if(UsingSimpledisplayX11) {
XSync(XDisplayConnection.get, 0);
if(keyboard) {
if(isTransient && _parent) {
/*
FIXME:
setting the keyboard focus is not actually that helpful, what I more likely want
is the events from the parent window to be sent over here if we're transient.
*/
_parent.inputProxy = this;
} else {
SimpleWindow setTo;
if(setRequestedInputFocus !is null)
setTo = setRequestedInputFocus();
if(setTo is null)
setTo = this;
XSetInputFocus(XDisplayConnection.get, setTo.impl.window, RevertToParent, CurrentTime);
}
}
if(mouse) {
if(auto res = XGrabPointer(XDisplayConnection.get, this.impl.window, false /* owner_events */,
EventMask.PointerMotionMask // FIXME: not efficient
| EventMask.ButtonPressMask
| EventMask.ButtonReleaseMask
/* event mask */, GrabMode.GrabModeAsync, GrabMode.GrabModeAsync, confine ? this.impl.window : None, None, CurrentTime)
)
{
XSync(XDisplayConnection.get, 0);
import core.stdc.stdio;
printf("Grab input failed %d\n", res);
//throw new Exception("Grab input failed");
} else {
// cool
}
}
} else version(Windows) {
// FIXME: keyboard?
SetCapture(impl.hwnd);
if(confine) {
RECT rcClip;
//RECT rcOldClip;
//GetClipCursor(&rcOldClip);
GetWindowRect(hwnd, &rcClip);
ClipCursor(&rcClip);
}
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
private Point imePopupLocation = Point(0, 0);
/++
Sets the location for the IME (input method editor) to pop up when the user activates it.
Bugs:
Not implemented outside X11.
+/
void setIMEPopupLocation(Point location) {
static if(UsingSimpledisplayX11) {
imePopupLocation = location;
updateIMEPopupLocation();
} else {
// this is non-fatal at this point... but still wanna find it when i search for NotYetImplementedException at least
// throw new NotYetImplementedException();
}
}
/// ditto
void setIMEPopupLocation(int x, int y) {
return setIMEPopupLocation(Point(x, y));
}
// we need to remind XIM of where we wanted to place the IME whenever the window moves
// so this function gets called in setIMEPopupLocation as well as whenever the window
// receives a ConfigureNotify event
private void updateIMEPopupLocation() {
static if(UsingSimpledisplayX11) {
if (xic is null) {
return;
}
XPoint nspot;
nspot.x = cast(short) imePopupLocation.x;
nspot.y = cast(short) imePopupLocation.y;
XVaNestedList preeditAttr = XVaCreateNestedList(0, /*XNSpotLocation*/"spotLocation".ptr, &nspot, null);
XSetICValues(xic, /*XNPreeditAttributes*/"preeditAttributes".ptr, preeditAttr, null);
XFree(preeditAttr);
}
}
private bool imeFocused = true;
/++
Tells the IME whether or not an input field is currently focused in the window.
Bugs:
Not implemented outside X11.
+/
void setIMEFocused(bool value) {
imeFocused = value;
updateIMEFocused();
}
// used to focus/unfocus the IC if necessary when the window gains/loses focus
private void updateIMEFocused() {
static if(UsingSimpledisplayX11) {
if (xic is null) {
return;
}
if (focused && imeFocused) {
XSetICFocus(xic);
} else {
XUnsetICFocus(xic);
}
}
}
/++
Returns the native window.
History:
Added November 5, 2021 (dub v10.4). Prior to that, you'd have
to access it through the `impl` member (which is semi-supported
but platform specific and here it is simple enough to offer an accessor).
Bugs:
Not implemented outside Windows or X11.
+/
NativeWindowHandle nativeWindowHandle() {
version(X11)
return impl.window;
else version(Windows)
return impl.hwnd;
else
throw new NotYetImplementedException();
}
private bool isTransient() {
with(WindowTypes)
final switch(windowType) {
case normal, undecorated, eventOnly:
case nestedChild, minimallyWrapped:
return (customizationFlags & WindowFlags.transient) ? true : false;
case dropdownMenu, popupMenu, notification:
return true;
}
}
private SimpleWindow inputProxy;
/++
Releases the grab acquired by [grabInput].
+/
void releaseInputGrab() {
static if(UsingSimpledisplayX11) {
XUngrabPointer(XDisplayConnection.get, CurrentTime);
if(_parent)
_parent.inputProxy = null;
} else version(Windows) {
ReleaseCapture();
ClipCursor(null);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
/++
Sets the input focus to this window.
You shouldn't call this very often - please let the user control the input focus.
+/
void focus() {
static if(UsingSimpledisplayX11) {
SimpleWindow setTo;
if(setRequestedInputFocus !is null)
setTo = setRequestedInputFocus();
if(setTo is null)
setTo = this;
XSetInputFocus(XDisplayConnection.get, setTo.impl.window, RevertToParent, CurrentTime);
} else version(Windows) {
SetFocus(this.impl.hwnd);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
/++
Requests attention from the user for this window.
The typical result of this function is to change the color
of the taskbar icon, though it may be tweaked on specific
platforms.
It is meant to unobtrusively tell the user that something
relevant to them happened in the background and they should
check the window when they get a chance. Upon receiving the
keyboard focus, the window will automatically return to its
natural state.
If the window already has the keyboard focus, this function
may do nothing, because the user is presumed to already be
giving the window attention.
Implementation_note:
`requestAttention` uses the _NET_WM_STATE_DEMANDS_ATTENTION
atom on X11 and the FlashWindow function on Windows.
+/
void requestAttention() {
if(_focused)
return;
version(Windows) {
FLASHWINFO info;
info.cbSize = info.sizeof;
info.hwnd = impl.hwnd;
info.dwFlags = FLASHW_TRAY;
info.uCount = 1;
FlashWindowEx(&info);
} else version(X11) {
demandingAttention = true;
demandAttention(this, true);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
private bool _focused;
version(X11) private bool demandingAttention;
/// This will be called when WM wants to close your window (i.e. user clicked "close" icon, for example).
/// You'll have to call `close()` manually if you set this delegate.
void delegate () closeQuery;
/// This will be called when window visibility was changed.
void delegate (bool becomesVisible) visibilityChanged;
/// This will be called when window becomes visible for the first time.
/// You can do OpenGL initialization here. Note that in X11 you can't call
/// [setAsCurrentOpenGlContext] right after window creation, or X11 may
/// fail to send reparent and map events (hit that with proprietary NVidia drivers).
/// So you need to wait until this is called and call setAsCurrentOpenGlContext in there, then do the OpenGL initialization.
private bool _visibleForTheFirstTimeCalled;
void delegate () visibleForTheFirstTime;
/// Returns true if the window has been closed.
final @property bool closed() { return _closed; }
private final @property bool notClosed() { return !_closed; }
/// Returns true if the window is focused.
final @property bool focused() { return _focused; }
private bool _visible;
/// Returns true if the window is visible (mapped).
final @property bool visible() { return _visible; }
/// Closes the window. If there are no more open windows, the event loop will terminate.
void close() {
if (!_closed) {
runInGuiThread( {
if(_closed) return; // another thread got to it first. this isn't a big deal, it just means our message was queued
if (onClosing !is null) onClosing();
impl.closeWindow();
_closed = true;
} );
}
}
/++
`close` is one of the few methods that can be called from other threads. This `shared` overload reflects that.
History:
Overload added on March 7, 2021.
+/
void close() shared {
(cast() this).close();
}
/++
+/
void maximize() {
version(Windows)
ShowWindow(impl.hwnd, SW_MAXIMIZE);
else version(X11) {
setNetWmStateAtom(this.impl.window, GetAtom!("_NET_WM_STATE_MAXIMIZED_VERT", false)(XDisplayConnection.get), true, GetAtom!("_NET_WM_STATE_MAXIMIZED_HORZ", false)(XDisplayConnection.get));
// also note _NET_WM_STATE_FULLSCREEN
}
}
private bool _fullscreen;
version(Windows)
private WINDOWPLACEMENT g_wpPrev;
/// not fully implemented but planned for a future release
void fullscreen(bool yes) {
version(Windows) {
g_wpPrev.length = WINDOWPLACEMENT.sizeof;
DWORD dwStyle = GetWindowLong(hwnd, GWL_STYLE);
if (dwStyle & WS_OVERLAPPEDWINDOW) {
MONITORINFO mi;
mi.cbSize = MONITORINFO.sizeof;
if (GetWindowPlacement(hwnd, &g_wpPrev) &&
GetMonitorInfo(MonitorFromWindow(hwnd,
MONITOR_DEFAULTTOPRIMARY), &mi)) {
SetWindowLong(hwnd, GWL_STYLE,
dwStyle & ~WS_OVERLAPPEDWINDOW);
SetWindowPos(hwnd, HWND_TOP,
mi.rcMonitor.left, mi.rcMonitor.top,
mi.rcMonitor.right - mi.rcMonitor.left,
mi.rcMonitor.bottom - mi.rcMonitor.top,
SWP_NOOWNERZORDER | SWP_FRAMECHANGED);
}
} else {
SetWindowLong(hwnd, GWL_STYLE,
dwStyle | WS_OVERLAPPEDWINDOW);
SetWindowPlacement(hwnd, &g_wpPrev);
SetWindowPos(hwnd, null, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
SWP_NOOWNERZORDER | SWP_FRAMECHANGED);
}
} else version(X11) {
setNetWmStateAtom(this.impl.window, GetAtom!("_NET_WM_STATE_FULLSCREEN", false)(XDisplayConnection.get), yes);
}
_fullscreen = yes;
}
bool fullscreen() {
return _fullscreen;
}
/++
Note: only implemented on Windows. No-op on other platforms. You may want to use [hide] instead.
+/
void minimize() {
version(Windows)
ShowWindow(impl.hwnd, SW_MINIMIZE);
//else version(X11)
//setNetWmStateAtom(this, GetAtom!("_NET_WM_STATE_MINIMIZED", false)(XDisplayConnection.get), true);
}
/// Alias for `hidden = false`
void show() {
hidden = false;
}
/// Alias for `hidden = true`
void hide() {
hidden = true;
}
/// Hide cursor when it enters the window.
void hideCursor() {
version(OSXCocoa) throw new NotYetImplementedException(); else
if (!_closed) impl.hideCursor();
}
/// Don't hide cursor when it enters the window.
void showCursor() {
version(OSXCocoa) throw new NotYetImplementedException(); else
if (!_closed) impl.showCursor();
}
/** "Warp" mouse pointer to coordinates relative to window top-left corner. Return "success" flag.
*
* Please remember that the cursor is a shared resource that should usually be left to the user's
* control. Try to think for other approaches before using this function.
*
* Note: "warping" pointer will not send any synthesised mouse events, so you probably doesn't want
* to use it to move mouse pointer to some active GUI area, for example, as your window won't
* receive "mouse moved here" event.
*/
bool warpMouse (int x, int y) {
version(X11) {
if (!_closed) { impl.warpMouse(x, y); return true; }
} else version(Windows) {
if (!_closed) {
POINT point;
point.x = x;
point.y = y;
if(ClientToScreen(impl.hwnd, &point)) {
SetCursorPos(point.x, point.y);
return true;
}
}
}
return false;
}
/// Send dummy window event to ping event loop. Required to process NotificationIcon on X11, for example.
void sendDummyEvent () {
version(X11) {
if (!_closed) { impl.sendDummyEvent(); }
}
}
/// Set window minimal size.
void setMinSize (int minwidth, int minheight) {
version(OSXCocoa) throw new NotYetImplementedException(); else
if (!_closed) impl.setMinSize(minwidth, minheight);
}
/// Set window maximal size.
void setMaxSize (int maxwidth, int maxheight) {
version(OSXCocoa) throw new NotYetImplementedException(); else
if (!_closed) impl.setMaxSize(maxwidth, maxheight);
}
/// Set window resize step (window size will be changed with the given granularity on supported platforms).
/// Currently only supported on X11.
void setResizeGranularity (int granx, int grany) {
version(OSXCocoa) throw new NotYetImplementedException(); else
if (!_closed) impl.setResizeGranularity(granx, grany);
}
/// Move window.
void move(int x, int y) {
version(OSXCocoa) throw new NotYetImplementedException(); else
if (!_closed) impl.move(x, y);
}
/// ditto
void move(Point p) {
version(OSXCocoa) throw new NotYetImplementedException(); else
if (!_closed) impl.move(p.x, p.y);
}
/++
Resize window.
Note that the width and height of the window are NOT instantly
updated - it waits for the window manager to approve the resize
request, which means you must return to the event loop before the
width and height are actually changed.
+/
void resize(int w, int h) {
if(!_closed && _fullscreen) fullscreen = false;
version(OSXCocoa) throw new NotYetImplementedException(); else
if (!_closed) impl.resize(w, h);
}
/// Move and resize window (this can be faster and more visually pleasant than doing it separately).
void moveResize (int x, int y, int w, int h) {
if(!_closed && _fullscreen) fullscreen = false;
version(OSXCocoa) throw new NotYetImplementedException(); else
if (!_closed) impl.moveResize(x, y, w, h);
}
private bool _hidden;
/// Returns true if the window is hidden.
final @property bool hidden() {
return _hidden;
}
/// Shows or hides the window based on the bool argument.
final @property void hidden(bool b) {
_hidden = b;
version(Windows) {
ShowWindow(impl.hwnd, b ? SW_HIDE : SW_SHOW);
} else version(X11) {
if(b)
//XUnmapWindow(impl.display, impl.window);
XWithdrawWindow(impl.display, impl.window, DefaultScreen(impl.display));
else
XMapWindow(impl.display, impl.window);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
/// Sets the window opacity. On X11 this requires a compositor to be running. On windows the WindowFlags.extraComposite must be set at window creation.
void opacity(double opacity) @property
in {
assert(opacity >= 0 && opacity <= 1);
} do {
version (Windows) {
impl.setOpacity(cast(ubyte)(255 * opacity));
} else version (X11) {
impl.setOpacity(cast(uint)(uint.max * opacity));
} else throw new NotYetImplementedException();
}
/++
Sets your event handlers, without entering the event loop. Useful if you
have multiple windows - set the handlers on each window, then only do
[eventLoop] on your main window or call `EventLoop.get.run();`.
This assigns the given handlers to [handleKeyEvent], [handleCharEvent],
[handlePulse], and [handleMouseEvent] automatically based on the provide
delegate signatures.
+/
void setEventHandlers(T...)(T eventHandlers) {
// FIXME: add more events
foreach(handler; eventHandlers) {
static if(__traits(compiles, handleKeyEvent = handler)) {
handleKeyEvent = handler;
} else static if(__traits(compiles, handleCharEvent = handler)) {
handleCharEvent = handler;
} else static if(__traits(compiles, handlePulse = handler)) {
handlePulse = handler;
} else static if(__traits(compiles, handleMouseEvent = handler)) {
handleMouseEvent = handler;
} else static assert(0, "I can't use this event handler " ~ typeof(handler).stringof ~ "\nHave you tried using the delegate keyword?");
}
}
/++
The event loop automatically returns when the window is closed
pulseTimeout is given in milliseconds. If pulseTimeout == 0, no
pulse timer is created. The event loop will block until an event
arrives or the pulse timer goes off.
The given `eventHandlers` are passed to [setEventHandlers], which in turn
assigns them to [handleKeyEvent], [handleCharEvent], [handlePulse], and
[handleMouseEvent], based on the signature of delegates you provide.
Give one with no parameters to set a timer pulse handler. Give one that
takes [KeyEvent] for a key handler, [MouseEvent], for a mouse handler,
and one that takes `dchar` for a char event handler. You can use as many
or as few handlers as you need for your application.
History:
The overload without `pulseTimeout` was added on December 8, 2021.
On December 9, 2021, the default blocking mode (which is now configurable
because [eventLoopWithBlockingMode] was added) switched from
[BlockingMode.untilApplicationQuits] over to [BlockingMode.automatic]. This
should almost never be noticeable to you since the typical simpledisplay
paradigm has been (and I still recommend) to have one `eventLoop` call.
See_Also:
[eventLoopWithBlockingMode]
+/
final int eventLoop(T...)(
long pulseTimeout, /// set to zero if you don't want a pulse.
T eventHandlers) /// delegate list like std.concurrency.receive
{
return eventLoopWithBlockingMode(BlockingMode.automatic, pulseTimeout, eventHandlers);
}
/// ditto
final int eventLoop(T...)(T eventHandlers) if(T.length == 0 || is(T[0] == delegate))
{
return eventLoopWithBlockingMode(BlockingMode.automatic, 0, eventHandlers);
}
/++
This is the function [eventLoop] forwards to. It, in turn, forwards to `EventLoop.get.run`.
History:
Added December 8, 2021 (dub v10.5)
Previously, this implementation was right inside [eventLoop], but when I wanted
to add the new [BlockingMode] parameter, the compiler got in a trouble loop so I
just renamed it instead of adding as an overload. Besides, the new name makes it
easier to remember the order and avoids ambiguity between two int-like params anyway.
See_Also:
[SimpleWindow.eventLoop], [EventLoop]
Bugs:
The blocking mode is not implemented on OSX Cocoa nor on the (deprecated) arsd.eventloop.
+/
final int eventLoopWithBlockingMode(T...)(
BlockingMode blockingMode, /// when you want this function to block until
long pulseTimeout, /// set to zero if you don't want a pulse.
T eventHandlers) /// delegate list like std.concurrency.receive
{
setEventHandlers(eventHandlers);
version(with_eventloop) {
// delegates event loop to my other module
version(X11)
XFlush(display);
import arsd.eventloop;
auto handle = setInterval(handlePulse, cast(int) pulseTimeout);
scope(exit) clearInterval(handle);
loop();
return 0;
} else version(OSXCocoa) {
// FIXME
if (handlePulse !is null && pulseTimeout != 0) {
timer = scheduledTimer(pulseTimeout*1e-3,
view, sel_registerName("simpledisplay_pulse"),
null, true);
}
setNeedsDisplay(view, true);
run(NSApp);
return 0;
} else {
EventLoop el = EventLoop(pulseTimeout, handlePulse);
if((blockingMode & BlockingMode.onlyIfNotNested) && el.impl.refcount > 1)
return 0;
return el.run(
((blockingMode & 0x0f) == BlockingMode.untilApplicationQuits) ?
null :
&this.notClosed
);
}
}
/++
This lets you draw on the window (or its backing buffer) using basic
2D primitives.
Be sure to call this in a limited scope because your changes will not
actually appear on the window until ScreenPainter's destructor runs.
Returns: an instance of [ScreenPainter], which has the drawing methods
on it to draw on this window.
Params:
manualInvalidations = if you set this to true, you will need to
set the invalid rectangle on the painter yourself. If false, it
assumes the whole window has been redrawn each time you draw.
Only invalidated rectangles are blitted back to the window when
the destructor runs. Doing this yourself can reduce flickering
of child windows.
History:
The `manualInvalidations` parameter overload was added on
December 30, 2021 (dub v10.5)
+/
ScreenPainter draw() {
return draw(false);
}
/// ditto
ScreenPainter draw(bool manualInvalidations) {
return impl.getPainter(manualInvalidations);
}
// This is here to implement the interface we use for various native handlers.
NativeEventHandler getNativeEventHandler() { return handleNativeEvent; }
// maps native window handles to SimpleWindow instances, if there are any
// you shouldn't need this, but it is public in case you do in a native event handler or something
public __gshared SimpleWindow[NativeWindowHandle] nativeMapping;
// the size the user requested in the constructor, in automatic scale modes it always pretends to be this size
private int _virtualWidth;
private int _virtualHeight;
/// Width of the window's drawable client area, in pixels.
@scriptable
final @property int width() const pure nothrow @safe @nogc {
if(resizability == Resizability.automaticallyScaleIfPossible)
return _virtualWidth;
else
return _width;
}
/// Height of the window's drawable client area, in pixels.
@scriptable
final @property int height() const pure nothrow @safe @nogc {
if(resizability == Resizability.automaticallyScaleIfPossible)
return _virtualHeight;
else
return _height;
}
/++
Returns the actual size of the window, bypassing the logical
illusions of [Resizability.automaticallyScaleIfPossible].
History:
Added November 11, 2022 (dub v10.10)
+/
final @property Size actualWindowSize() const pure nothrow @safe @nogc {
return Size(_width, _height);
}
private int _width;
private int _height;
// HACK: making the best of some copy constructor woes with refcounting
private ScreenPainterImplementation* activeScreenPainter_;
protected ScreenPainterImplementation* activeScreenPainter() { return activeScreenPainter_; }
protected void activeScreenPainter(ScreenPainterImplementation* i) { activeScreenPainter_ = i; }
private OpenGlOptions openglMode;
private Resizability resizability;
private WindowTypes windowType;
private int customizationFlags;
/// `true` if OpenGL was initialized for this window.
@property bool isOpenGL () const pure nothrow @safe @nogc {
version(without_opengl)
return false;
else
return (openglMode == OpenGlOptions.yes);
}
@property Resizability resizingMode () const pure nothrow @safe @nogc { return resizability; } /// Original resizability.
@property WindowTypes type () const pure nothrow @safe @nogc { return windowType; } /// Original window type.
@property int customFlags () const pure nothrow @safe @nogc { return customizationFlags; } /// Original customization flags.
/// "Lock" this window handle, to do multithreaded synchronization. You probably won't need
/// to call this, as it's not recommended to share window between threads.
void mtLock () {
version(X11) {
XLockDisplay(this.display);
}
}
/// "Unlock" this window handle, to do multithreaded synchronization. You probably won't need
/// to call this, as it's not recommended to share window between threads.
void mtUnlock () {
version(X11) {
XUnlockDisplay(this.display);
}
}
/// Emit a beep to get user's attention.
void beep () {
version(X11) {
XBell(this.display, 100);
} else version(Windows) {
MessageBeep(0xFFFFFFFF);
}
}
version(without_opengl) {} else {
/// Put your code in here that you want to be drawn automatically when your window is uncovered. Set a handler here *before* entering your event loop any time you pass `OpenGlOptions.yes` to the constructor. Ideally, you will set this delegate immediately after constructing the `SimpleWindow`.
void delegate() redrawOpenGlScene;
/// This will allow you to change OpenGL vsync state.
final @property void vsync (bool wait) {
if (this._closed) return; // window may be closed, but timer is still firing; avoid GLXBadDrawable error
version(X11) {
setAsCurrentOpenGlContext();
glxSetVSync(display, impl.window, wait);
} else version(Windows) {
setAsCurrentOpenGlContext();
wglSetVSync(wait);
}
}
/// Set this to `false` if you don't need to do `glFinish()` after `swapOpenGlBuffers()`.
/// Note that at least NVidia proprietary driver may segfault if you will modify texture fast
/// enough without waiting 'em to finish their frame business.
bool useGLFinish = true;
// FIXME: it should schedule it for the end of the current iteration of the event loop...
/// call this to invoke your delegate. It automatically sets up the context and flips the buffer. If you need to redraw the scene in response to an event, call this.
void redrawOpenGlSceneNow() {
version(X11) if (!this._visible) return; // no need to do this if window is invisible
if (this._closed) return; // window may be closed, but timer is still firing; avoid GLXBadDrawable error
if(redrawOpenGlScene is null)
return;
this.mtLock();
scope(exit) this.mtUnlock();
this.setAsCurrentOpenGlContext();
redrawOpenGlScene();
this.swapOpenGlBuffers();
// at least nvidia proprietary crap segfaults on exit if you won't do this and will call glTexSubImage2D() too fast; no, `glFlush()` won't work.
if (useGLFinish) glFinish();
}
private bool redrawOpenGlSceneSoonSet = false;
private static class RedrawOpenGlSceneEvent {
SimpleWindow w;
this(SimpleWindow w) { this.w = w; }
}
private RedrawOpenGlSceneEvent redrawOpenGlSceneEvent;
/++
Queues an opengl redraw as soon as the other pending events are cleared.
+/
void redrawOpenGlSceneSoon() {
if(!redrawOpenGlSceneSoonSet) {
redrawOpenGlSceneEvent = new RedrawOpenGlSceneEvent(this);
this.addEventListener((RedrawOpenGlSceneEvent e) { e.w.redrawOpenGlSceneNow(); });
redrawOpenGlSceneSoonSet = true;
}
this.postEvent(redrawOpenGlSceneEvent, true);
}
/// Makes all gl* functions target this window until changed. This is only valid if you passed `OpenGlOptions.yes` to the constructor.
void setAsCurrentOpenGlContext() {
assert(openglMode == OpenGlOptions.yes);
version(X11) {
if(glXMakeCurrent(display, impl.window, impl.glc) == 0)
throw new Exception("glXMakeCurrent");
} else version(Windows) {
static if (SdpyIsUsingIVGLBinds) import iv.glbinds; // override druntime windows imports
if (!wglMakeCurrent(ghDC, ghRC))
throw new Exception("wglMakeCurrent " ~ toInternal!int(GetLastError())); // let windows users suffer too
}
}
/// Makes all gl* functions target this window until changed. This is only valid if you passed `OpenGlOptions.yes` to the constructor.
/// This doesn't throw, returning success flag instead.
bool setAsCurrentOpenGlContextNT() nothrow {
assert(openglMode == OpenGlOptions.yes);
version(X11) {
return (glXMakeCurrent(display, impl.window, impl.glc) != 0);
} else version(Windows) {
static if (SdpyIsUsingIVGLBinds) import iv.glbinds; // override druntime windows imports
return wglMakeCurrent(ghDC, ghRC) ? true : false;
}
}
/// Releases OpenGL context, so it can be reused in, for example, different thread. This is only valid if you passed `OpenGlOptions.yes` to the constructor.
/// This doesn't throw, returning success flag instead.
bool releaseCurrentOpenGlContext() nothrow {
assert(openglMode == OpenGlOptions.yes);
version(X11) {
return (glXMakeCurrent(display, 0, null) != 0);
} else version(Windows) {
static if (SdpyIsUsingIVGLBinds) import iv.glbinds; // override druntime windows imports
return wglMakeCurrent(ghDC, null) ? true : false;
}
}
/++
simpledisplay always uses double buffering, usually automatically. This
manually swaps the OpenGL buffers.
You should not need to call this yourself because simpledisplay will do it
for you after calling your `redrawOpenGlScene`.
Remember that this may throw an exception, which you can catch in a multithreaded
application to keep your thread from dying from an unhandled exception.
+/
void swapOpenGlBuffers() {
assert(openglMode == OpenGlOptions.yes);
version(X11) {
if (!this._visible) return; // no need to do this if window is invisible
if (this._closed) return; // window may be closed, but timer is still firing; avoid GLXBadDrawable error
glXSwapBuffers(display, impl.window);
} else version(Windows) {
SwapBuffers(ghDC);
}
}
}
/++
Set the window title, which is visible on the window manager title bar, operating system taskbar, etc.
---
auto window = new SimpleWindow(100, 100, "First title");
window.title = "A new title";
---
You may call this function at any time.
+/
@property void title(string title) {
_title = title;
version(OSXCocoa) throw new NotYetImplementedException(); else
impl.setTitle(title);
}
private string _title;
/// Gets the title
@property string title() {
if(_title is null)
_title = getRealTitle();
return _title;
}
/++
Get the title as set by the window manager.
May not match what you attempted to set.
+/
string getRealTitle() {
static if(is(typeof(impl.getTitle())))
return impl.getTitle();
else
return null;
}
// don't use this generally it is not yet really released
version(X11)
@property Image secret_icon() {
return secret_icon_inner;
}
private Image secret_icon_inner;
/// Set the icon that is seen in the title bar or taskbar, etc., for the user. If passed `null`, does nothing.
@property void icon(MemoryImage icon) {
if(icon is null)
return;
auto tci = icon.getAsTrueColorImage();
version(Windows) {
winIcon = new WindowsIcon(icon);
SendMessageA(impl.hwnd, 0x0080 /*WM_SETICON*/, 0 /*ICON_SMALL*/, cast(LPARAM) winIcon.hIcon); // there is also 1 == ICON_BIG
} else version(X11) {
secret_icon_inner = Image.fromMemoryImage(icon);
// FIXME: ensure this is correct
auto display = XDisplayConnection.get;
arch_ulong[] buffer;
buffer ~= icon.width;
buffer ~= icon.height;
foreach(c; tci.imageData.colors) {
arch_ulong b;
b |= c.a << 24;
b |= c.r << 16;
b |= c.g << 8;
b |= c.b;
buffer ~= b;
}
XChangeProperty(
display,
impl.window,
GetAtom!("_NET_WM_ICON", true)(display),
GetAtom!"CARDINAL"(display),
32 /* bits */,
0 /*PropModeReplace*/,
buffer.ptr,
cast(int) buffer.length);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
version(Windows)
private WindowsIcon winIcon;
bool _suppressDestruction;
~this() {
if(!thisIsGuiThread) return; // FIXME: leaks if multithreaded gc
if(_suppressDestruction)
return;
impl.dispose();
}
private bool _closed;
// the idea here is to draw something temporary on top of the main picture e.g. a blinking cursor
/*
ScreenPainter drawTransiently() {
return impl.getPainter();
}
*/
/// Draws an image on the window. This is meant to provide quick look
/// of a static image generated elsewhere.
@property void image(Image i) {
/+
version(Windows) {
BITMAP bm;
HDC hdc = GetDC(hwnd);
HDC hdcMem = CreateCompatibleDC(hdc);
HBITMAP hbmOld = SelectObject(hdcMem, i.handle);
GetObject(i.handle, bm.sizeof, &bm);
BitBlt(hdc, 0, 0, bm.bmWidth, bm.bmHeight, hdcMem, 0, 0, SRCCOPY);
SelectObject(hdcMem, hbmOld);
DeleteDC(hdcMem);
ReleaseDC(hwnd, hdc);
/*
RECT r;
r.right = i.width;
r.bottom = i.height;
InvalidateRect(hwnd, &r, false);
*/
} else
version(X11) {
if(!destroyed) {
if(i.usingXshm)
XShmPutImage(display, cast(Drawable) window, gc, i.handle, 0, 0, 0, 0, i.width, i.height, false);
else
XPutImage(display, cast(Drawable) window, gc, i.handle, 0, 0, 0, 0, i.width, i.height);
}
} else
version(OSXCocoa) {
draw().drawImage(Point(0, 0), i);
setNeedsDisplay(view, true);
} else static assert(0);
+/
auto painter = this.draw;
painter.drawImage(Point(0, 0), i);
}
/++
Changes the cursor for the window. If the cursor is hidden via [hideCursor], this has no effect.
---
window.cursor = GenericCursor.Help;
// now the window mouse cursor is set to a generic help
---
+/
@property void cursor(MouseCursor cursor) {
version(OSXCocoa)
featureNotImplemented();
else
if(this.impl.curHidden <= 0) {
static if(UsingSimpledisplayX11) {
auto ch = cursor.cursorHandle;
XDefineCursor(XDisplayConnection.get(), this.impl.window, ch);
} else version(Windows) {
auto ch = cursor.cursorHandle;
impl.currentCursor = ch;
SetCursor(ch); // redraw without waiting for mouse movement to update
} else featureNotImplemented();
}
}
/// What follows are the event handlers. These are set automatically
/// by the eventLoop function, but are still public so you can change
/// them later. wasPressed == true means key down. false == key up.
/// Handles a low-level keyboard event. Settable through setEventHandlers.
void delegate(KeyEvent ke) handleKeyEvent;
/// Handles a higher level keyboard event - c is the character just pressed. Settable through setEventHandlers.
void delegate(dchar c) handleCharEvent;
/// Handles a timer pulse. Settable through setEventHandlers.
void delegate() handlePulse;
/// Called when the focus changes, param is if we have it (true) or are losing it (false).
void delegate(bool) onFocusChange;
/** Called inside `close()` method. Our window is still alive, and we can free various resources.
* Sometimes it is easier to setup the delegate instead of subclassing. */
void delegate() onClosing;
/** Called when we received destroy notification. At this stage we cannot do much with our window
* (as it is already dead, and it's native handle cannot be used), but we still can do some
* last minute cleanup. */
void delegate() onDestroyed;
static if (UsingSimpledisplayX11)
/** Called when Expose event comes. See Xlib manual to understand the arguments.
* Return `false` if you want Simpledisplay to copy backbuffer, or `true` if you did it yourself.
* You will probably never need to setup this handler, it is for very low-level stuff.
*
* WARNING! Xlib is multithread-locked when this handles is called! */
bool delegate(int x, int y, int width, int height, int eventsLeft) handleExpose;
//version(Windows)
//bool delegate(WPARAM wParam, LPARAM lParam) handleWM_PAINT;
private {
int lastMouseX = int.min;
int lastMouseY = int.min;
void mdx(ref MouseEvent ev) {
if(lastMouseX == int.min || lastMouseY == int.min) {
ev.dx = 0;
ev.dy = 0;
} else {
ev.dx = ev.x - lastMouseX;
ev.dy = ev.y - lastMouseY;
}
lastMouseX = ev.x;
lastMouseY = ev.y;
}
}
/// Mouse event handler. Settable through setEventHandlers.
void delegate(MouseEvent) handleMouseEvent;
/// use to redraw child widgets if you use system apis to add stuff
void delegate() paintingFinished;
void delegate() paintingFinishedDg() {
return paintingFinished;
}
/// handle a resize, after it happens. You must construct the window with Resizability.allowResizing
/// for this to ever happen.
void delegate(int width, int height) windowResized;
/++
Platform specific - handle any native message this window gets.
Note: this is called *in addition to* other event handlers, unless you either:
1) On X11, return 0 indicating that you handled it. Any other return value is simply discarded.
2) On Windows, set the `mustReturn` parameter to 1 indicating you've done it and your return value should be forwarded to the operating system. If you do not set `mustReturn`, your return value will be discarded.
On Windows, your delegate takes the form of `int delegate(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam, out int mustReturn)`.
On X, it takes the form of `int delegate(XEvent)`.
History:
In ancient versions, this was `static`. If you want a global hook, use [handleNativeGlobalEvent] instead.
Prior to November 27, 2021, the `mustReturn` parameter was not present, and the Windows implementation would discard return values. There's still a deprecated shim with that signature, but since the return value is often important, you shouldn't use it.
+/
NativeEventHandler handleNativeEvent_;
@property NativeEventHandler handleNativeEvent() nothrow pure @nogc const @safe {
return handleNativeEvent_;
}
@property void handleNativeEvent(NativeEventHandler neh) nothrow pure @nogc @safe {
handleNativeEvent_ = neh;
}
version(Windows)
// compatibility shim with the old deprecated way
// in this one, if you return 0, it means you must return. otherwise the ret value is ignored.
deprecated("This old api ignored your non-zero return values and that hurt it a lot. Add an `out int pleaseReturn` param to your delegate and set it to one if you must return the result to Windows. Otherwise, leave it zero and processing will continue through to the default window message processor.") @property void handleNativeEvent(int delegate(HWND, UINT, WPARAM, LPARAM) dg) {
handleNativeEvent_ = delegate int(HWND h, UINT m, WPARAM w, LPARAM l, out int r) {
auto ret = dg(h, m, w, l);
if(ret == 0)
r = 1;
return ret;
};
}
/// This is the same as handleNativeEvent, but static so it can hook ALL events in the loop.
/// If you used to use handleNativeEvent depending on it being static, just change it to use
/// this instead and it will work the same way.
__gshared NativeEventHandler handleNativeGlobalEvent;
// private:
/// The native implementation is available, but you shouldn't use it unless you are
/// familiar with the underlying operating system, don't mind depending on it, and
/// know simpledisplay.d's internals too. It is virtually private; you can hopefully
/// do what you need to do with handleNativeEvent instead.
///
/// This is likely to eventually change to be just a struct holding platform-specific
/// handles instead of a template mixin at some point because I'm not happy with the
/// code duplication here (ironically).
mixin NativeSimpleWindowImplementation!() impl;
/**
This is in-process one-way (from anything to window) event sending mechanics.
It is thread-safe, so it can be used in multi-threaded applications to send,
for example, "wake up and repaint" events when thread completed some operation.
This will allow to avoid using timer pulse to check events with synchronization,
'cause event handler will be called in UI thread. You can stop guessing which
pulse frequency will be enough for your app.
Note that events handlers may be called in arbitrary order, i.e. last registered
handler can be called first, and vice versa.
*/
public:
/** Is our custom event queue empty? Can be used in simple cases to prevent
* "spamming" window with events it can't cope with.
* It is safe to call this from non-UI threads.
*/
@property bool eventQueueEmpty() () {
synchronized(this) {
foreach (const ref o; eventQueue[0..eventQueueUsed]) if (!o.doProcess) return false;
}
return true;
}
/** Does our custom event queue contains at least one with the given type?
* Can be used in simple cases to prevent "spamming" window with events
* it can't cope with.
* It is safe to call this from non-UI threads.
*/
@property bool eventQueued(ET:Object) () {
synchronized(this) {
foreach (const ref o; eventQueue[0..eventQueueUsed]) {
if (!o.doProcess) {
if (cast(ET)(o.evt)) return true;
}
}
}
return false;
}
/++
Event listeners added with [addEventListener] have their exceptions swallowed by the event loop. This delegate can handle them again before it proceeds.
History:
Added May 12, 2021
+/
void delegate(Exception e) nothrow eventUncaughtException;
/** Add listener for custom event. Can be used like this:
*
* ---------------------
* auto eid = win.addEventListener((MyStruct evt) { ... });
* ...
* win.removeEventListener(eid);
* ---------------------
*
* Returns: 0 on failure (should never happen, so ignore it)
*
* $(WARNING Don't use this method in object destructors!)
*
* $(WARNING It is better to register all event handlers and don't remove 'em,
* 'cause if event handler id counter will overflow, you won't be able
* to register any more events.)
*/
uint addEventListener(ET:Object) (void delegate (ET) dg) {
if (dg is null) return 0; // ignore empty handlers
synchronized(this) {
//FIXME: abort on overflow?
if (++lastUsedHandlerId == 0) { --lastUsedHandlerId; return 0; } // alas, can't register more events. at all.
EventHandlerEntry e;
e.dg = delegate (Object o) {
if (auto co = cast(ET)o) {
try {
dg(co);
} catch (Exception e) {
// sorry!
if(eventUncaughtException)
eventUncaughtException(e);
}
return true;
}
return false;
};
e.id = lastUsedHandlerId;
auto optr = eventHandlers.ptr;
eventHandlers ~= e;
if (eventHandlers.ptr !is optr) {
import core.memory : GC;
if (eventHandlers.ptr is GC.addrOf(eventHandlers.ptr)) GC.setAttr(eventHandlers.ptr, GC.BlkAttr.NO_INTERIOR);
}
return lastUsedHandlerId;
}
}
/// Remove event listener. It is safe to pass invalid event id here.
/// $(WARNING Don't use this method in object destructors!)
void removeEventListener() (uint id) {
if (id == 0 || id > lastUsedHandlerId) return;
synchronized(this) {
foreach (immutable idx; 0..eventHandlers.length) {
if (eventHandlers[idx].id == id) {
foreach (immutable c; idx+1..eventHandlers.length) eventHandlers[c-1] = eventHandlers[c];
eventHandlers[$-1].dg = null;
eventHandlers.length -= 1;
eventHandlers.assumeSafeAppend;
return;
}
}
}
}
/// Post event to queue. It is safe to call this from non-UI threads.
/// If `timeoutmsecs` is greater than zero, the event will be delayed for at least `timeoutmsecs` milliseconds.
/// if `replace` is `true`, replace all existing events typed `ET` with the new one (if `evt` is empty, remove 'em all)
/// Returns `true` if event was queued. Always returns `false` if `evt` is null.
bool postTimeout(ET:Object) (ET evt, uint timeoutmsecs, bool replace=false) {
if (this.closed) return false; // closed windows can't handle events
// remove all events of type `ET`
void removeAllET () {
uint eidx = 0, ec = eventQueueUsed;
auto eptr = eventQueue.ptr;
while (eidx < ec) {
if (eptr.doProcess) { ++eidx; ++eptr; continue; }
if (cast(ET)eptr.evt !is null) {
// i found her!
if (inCustomEventProcessor) {
// if we're in custom event processing loop, processor will clear it for us
eptr.evt = null;
++eidx;
++eptr;
} else {
foreach (immutable c; eidx+1..ec) eventQueue.ptr[c-1] = eventQueue.ptr[c];
ec = --eventQueueUsed;
// clear last event (it is already copied)
eventQueue.ptr[ec].evt = null;
}
} else {
++eidx;
++eptr;
}
}
}
if (evt is null) {
if (replace) { synchronized(this) removeAllET(); }
// ignore empty events, they can't be handled anyway
return false;
}
// add events even if no event FD/event object created yet
synchronized(this) {
if (replace) removeAllET();
if (eventQueueUsed == uint.max) return false; // just in case
if (eventQueueUsed < eventQueue.length) {
eventQueue[eventQueueUsed++] = QueuedEvent(evt, timeoutmsecs);
} else {
if (eventQueue.capacity == eventQueue.length) {
// need to reallocate; do a trick to ensure that old array is cleared
auto oarr = eventQueue;
eventQueue ~= QueuedEvent(evt, timeoutmsecs);
// just in case, do yet another check
if (oarr.length != 0 && oarr.ptr !is eventQueue.ptr) foreach (ref e; oarr[0..eventQueueUsed]) e.evt = null;
import core.memory : GC;
if (eventQueue.ptr is GC.addrOf(eventQueue.ptr)) GC.setAttr(eventQueue.ptr, GC.BlkAttr.NO_INTERIOR);
} else {
auto optr = eventQueue.ptr;
eventQueue ~= QueuedEvent(evt, timeoutmsecs);
assert(eventQueue.ptr is optr);
}
++eventQueueUsed;
assert(eventQueueUsed == eventQueue.length);
}
if (!eventWakeUp()) {
// can't wake up event processor, so there is no reason to keep the event
assert(eventQueueUsed > 0);
eventQueue[--eventQueueUsed].evt = null;
return false;
}
return true;
}
}
/// Post event to queue. It is safe to call this from non-UI threads.
/// if `replace` is `true`, replace all existing events typed `ET` with the new one (if `evt` is empty, remove 'em all)
/// Returns `true` if event was queued. Always returns `false` if `evt` is null.
bool postEvent(ET:Object) (ET evt, bool replace=false) {
return postTimeout!ET(evt, 0, replace);
}
private:
private import core.time : MonoTime;
version(Posix) {
__gshared int customEventFDRead = -1;
__gshared int customEventFDWrite = -1;
__gshared int customSignalFD = -1;
} else version(Windows) {
__gshared HANDLE customEventH = null;
}
// wake up event processor
static bool eventWakeUp () {
version(X11) {
import core.sys.posix.unistd : write;
ulong n = 1;
if (customEventFDWrite >= 0) write(customEventFDWrite, &n, n.sizeof);
return true;
} else version(Windows) {
if (customEventH !is null) SetEvent(customEventH);
return true;
} else {
// not implemented for other OSes
return false;
}
}
static struct QueuedEvent {
Object evt;
bool timed = false;
MonoTime hittime = MonoTime.zero;
bool doProcess = false; // process event at the current iteration (internal flag)
this (Object aevt, uint toutmsecs) {
evt = aevt;
if (toutmsecs > 0) {
import core.time : msecs;
timed = true;
hittime = MonoTime.currTime+toutmsecs.msecs;
}
}
}
alias CustomEventHandler = bool delegate (Object o) nothrow;
static struct EventHandlerEntry {
CustomEventHandler dg;
uint id;
}
uint lastUsedHandlerId;
EventHandlerEntry[] eventHandlers;
QueuedEvent[] eventQueue = null;
uint eventQueueUsed = 0; // to avoid `.assumeSafeAppend` and length changes
bool inCustomEventProcessor = false; // required to properly remove events
// process queued events and call custom event handlers
// this will not process events posted from called handlers (such events are postponed for the next iteration)
void processCustomEvents () {
bool hasSomethingToDo = false;
uint ecount;
bool ocep;
synchronized(this) {
ocep = inCustomEventProcessor;
inCustomEventProcessor = true;
ecount = eventQueueUsed; // user may want to post new events from an event handler; process 'em on next iteration
auto ctt = MonoTime.currTime;
bool hasEmpty = false;
// mark events to process (this is required for `eventQueued()`)
foreach (ref qe; eventQueue[0..ecount]) {
if (qe.evt is null) { hasEmpty = true; continue; }
if (qe.timed) {
qe.doProcess = (qe.hittime <= ctt);
} else {
qe.doProcess = true;
}
hasSomethingToDo = (hasSomethingToDo || qe.doProcess);
}
if (!hasSomethingToDo) {
// remove empty events
if (hasEmpty) {
uint eidx = 0, ec = eventQueueUsed;
auto eptr = eventQueue.ptr;
while (eidx < ec) {
if (eptr.evt is null) {
foreach (immutable c; eidx+1..ec) eventQueue.ptr[c-1] = eventQueue.ptr[c];
ec = --eventQueueUsed;
eventQueue.ptr[ec].evt = null; // make GC life easier
} else {
++eidx;
++eptr;
}
}
}
inCustomEventProcessor = ocep;
return;
}
}
// process marked events
uint efree = 0; // non-processed events will be put at this index
EventHandlerEntry[] eh;
Object evt;
foreach (immutable eidx; 0..ecount) {
synchronized(this) {
if (!eventQueue[eidx].doProcess) {
// skip this event
assert(efree <= eidx);
if (efree != eidx) {
// copy this event to queue start
eventQueue[efree] = eventQueue[eidx];
eventQueue[eidx].evt = null; // just in case
}
++efree;
continue;
}
evt = eventQueue[eidx].evt;
eventQueue[eidx].evt = null; // in case event handler will hit GC
if (evt is null) continue; // just in case
// try all handlers; this can be slow, but meh...
eh = eventHandlers;
}
foreach (ref evhan; eh) if (evhan.dg !is null) evhan.dg(evt);
evt = null;
eh = null;
}
synchronized(this) {
// move all unprocessed events to queue top; efree holds first "free index"
foreach (immutable eidx; ecount..eventQueueUsed) {
assert(efree <= eidx);
if (efree != eidx) eventQueue[efree] = eventQueue[eidx];
++efree;
}
eventQueueUsed = efree;
// wake up event processor on next event loop iteration if we have more queued events
// also, remove empty events
bool awaken = false;
uint eidx = 0, ec = eventQueueUsed;
auto eptr = eventQueue.ptr;
while (eidx < ec) {
if (eptr.evt is null) {
foreach (immutable c; eidx+1..ec) eventQueue.ptr[c-1] = eventQueue.ptr[c];
ec = --eventQueueUsed;
eventQueue.ptr[ec].evt = null; // make GC life easier
} else {
if (!awaken && !eptr.timed) { eventWakeUp(); awaken = true; }
++eidx;
++eptr;
}
}
inCustomEventProcessor = ocep;
}
}
// for all windows in nativeMapping
package static void processAllCustomEvents () {
cleanupQueue.process();
justCommunication.processCustomEvents();
foreach (SimpleWindow sw; SimpleWindow.nativeMapping.byValue) {
if (sw is null || sw.closed) continue;
sw.processCustomEvents();
}
runPendingRunInGuiThreadDelegates();
}
// 0: infinite (i.e. no scheduled events in queue)
uint eventQueueTimeoutMSecs () {
synchronized(this) {
if (eventQueueUsed == 0) return 0;
if (inCustomEventProcessor) assert(0, "WUTAFUUUUUUU..."); // the thing that should not be. ABSOLUTELY! (c)
uint res = int.max;
auto ctt = MonoTime.currTime;
foreach (const ref qe; eventQueue[0..eventQueueUsed]) {
if (qe.evt is null) assert(0, "WUTAFUUUUUUU..."); // the thing that should not be. ABSOLUTELY! (c)
if (qe.doProcess) continue; // just in case
if (!qe.timed) return 1; // minimal
if (qe.hittime <= ctt) return 1; // minimal
auto tms = (qe.hittime-ctt).total!"msecs";
if (tms < 1) tms = 1; // safety net
if (tms >= int.max) tms = int.max-1; // and another safety net
if (res > tms) res = cast(uint)tms;
}
return (res >= int.max ? 0 : res);
}
}
// for all windows in nativeMapping
static uint eventAllQueueTimeoutMSecs () {
uint res = uint.max;
foreach (SimpleWindow sw; SimpleWindow.nativeMapping.byValue) {
if (sw is null || sw.closed) continue;
uint to = sw.eventQueueTimeoutMSecs();
if (to && to < res) {
res = to;
if (to == 1) break; // can't have less than this
}
}
return (res >= int.max ? 0 : res);
}
version(X11) {
ResizeEvent pendingResizeEvent;
}
/++
When in opengl mode and automatically resizing, it will set the opengl viewport to stretch.
If you work with multiple opengl contexts and/or threads, this might be more trouble than it is
worth so you can disable it by setting this to `true`.
History:
Added November 13, 2022.
+/
public bool suppressAutoOpenglViewport = false;
private void updateOpenglViewportIfNeeded(int width, int height) {
if(suppressAutoOpenglViewport) return;
version(without_opengl) {} else
if(openglMode == OpenGlOptions.yes && resizability == Resizability.automaticallyScaleIfPossible) {
import std.stdio; writeln(width, " ", height);
setAsCurrentOpenGlContextNT();
glViewport(0, 0, width, height);
}
}
}
/++
Magic pseudo-window for just posting events to a global queue.
Not entirely supported, I might delete it at any time.
Added Nov 5, 2021.
+/
__gshared SimpleWindow justCommunication = new SimpleWindow(NativeWindowHandle.init);
/* Drag and drop support { */
version(X11) {
} else version(Windows) {
import core.sys.windows.uuid;
import core.sys.windows.ole2;
import core.sys.windows.oleidl;
import core.sys.windows.objidl;
import core.sys.windows.wtypes;
pragma(lib, "ole32");
void initDnd() {
auto err = OleInitialize(null);
if(err != S_OK && err != S_FALSE)
throw new Exception("init");//err);
}
}
/* } End drag and drop support */
/// Represents a mouse cursor (aka the mouse pointer, the image seen on screen that indicates where the mouse is pointing).
/// See [GenericCursor].
class MouseCursor {
int osId;
bool isStockCursor;
private this(int osId) {
this.osId = osId;
this.isStockCursor = true;
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms648385(v=vs.85).aspx
this(int xHotSpot, int yHotSpot, ubyte[] andMask, ubyte[] xorMask) {}
version(Windows) {
HCURSOR cursor_;
HCURSOR cursorHandle() {
if(cursor_ is null)
cursor_ = LoadCursor(null, MAKEINTRESOURCE(osId));
return cursor_;
}
} else static if(UsingSimpledisplayX11) {
Cursor cursor_ = None;
int xDisplaySequence;
Cursor cursorHandle() {
if(this.osId == None)
return None;
// we need to reload if we on a new X connection
if(cursor_ == None || XDisplayConnection.connectionSequenceNumber != xDisplaySequence) {
cursor_ = XCreateFontCursor(XDisplayConnection.get(), this.osId);
xDisplaySequence = XDisplayConnection.connectionSequenceNumber;
}
return cursor_;
}
}
}
// https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
// https://tronche.com/gui/x/xlib/appendix/b/
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms648391(v=vs.85).aspx
/// Note that there is no exact appearance guaranteed for any of these items; it may change appearance on different operating systems or future simpledisplay versions.
enum GenericCursorType {
Default, /// The default arrow pointer.
Wait, /// A cursor indicating something is loading and the user must wait.
Hand, /// A pointing finger, like the one used hovering over hyperlinks in a web browser.
Help, /// A cursor indicating the user can get help about the pointer location.
Cross, /// A crosshair.
Text, /// An i-beam shape, typically used to indicate text selection is possible.
Move, /// Pointer indicating movement is possible. May also be used as SizeAll.
UpArrow, /// An arrow pointing straight up.
Progress, /// The hourglass and arrow, indicating the computer is working but the user can still work. Not great results on X11.
NotAllowed, /// Indicates the current operation is not allowed. Not great results on X11.
SizeNesw, /// Arrow pointing northeast and southwest (lower-left corner resize indicator).
SizeNs, /// Arrow pointing north and south (upper/lower edge resize indicator).
SizeNwse, /// Arrow pointing northwest and southeast (upper-left corner resize indicator).
SizeWe, /// Arrow pointing west and east (left/right edge resize indicator).
}
/*
X_plus == css cell == Windows ?
*/
/// You get one by `GenericCursor.SomeTime`. See [GenericCursorType] for a list of types.
static struct GenericCursor {
static:
///
MouseCursor opDispatch(string str)() if(__traits(hasMember, GenericCursorType, str)) {
static MouseCursor mc;
auto type = __traits(getMember, GenericCursorType, str);
if(mc is null) {
version(Windows) {
int osId;
final switch(type) {
case GenericCursorType.Default: osId = IDC_ARROW; break;
case GenericCursorType.Wait: osId = IDC_WAIT; break;
case GenericCursorType.Hand: osId = IDC_HAND; break;
case GenericCursorType.Help: osId = IDC_HELP; break;
case GenericCursorType.Cross: osId = IDC_CROSS; break;
case GenericCursorType.Text: osId = IDC_IBEAM; break;
case GenericCursorType.Move: osId = IDC_SIZEALL; break;
case GenericCursorType.UpArrow: osId = IDC_UPARROW; break;
case GenericCursorType.Progress: osId = IDC_APPSTARTING; break;
case GenericCursorType.NotAllowed: osId = IDC_NO; break;
case GenericCursorType.SizeNesw: osId = IDC_SIZENESW; break;
case GenericCursorType.SizeNs: osId = IDC_SIZENS; break;
case GenericCursorType.SizeNwse: osId = IDC_SIZENWSE; break;
case GenericCursorType.SizeWe: osId = IDC_SIZEWE; break;
}
} else static if(UsingSimpledisplayX11) {
int osId;
final switch(type) {
case GenericCursorType.Default: osId = None; break;
case GenericCursorType.Wait: osId = 150 /* XC_watch */; break;
case GenericCursorType.Hand: osId = 60 /* XC_hand2 */; break;
case GenericCursorType.Help: osId = 92 /* XC_question_arrow */; break;
case GenericCursorType.Cross: osId = 34 /* XC_crosshair */; break;
case GenericCursorType.Text: osId = 152 /* XC_xterm */; break;
case GenericCursorType.Move: osId = 52 /* XC_fleur */; break;
case GenericCursorType.UpArrow: osId = 22 /* XC_center_ptr */; break;
case GenericCursorType.Progress: osId = 150 /* XC_watch, best i can do i think */; break;
case GenericCursorType.NotAllowed: osId = 24 /* XC_circle. not great */; break;
case GenericCursorType.SizeNesw: osId = 12 /* XC_bottom_left_corner */ ; break;
case GenericCursorType.SizeNs: osId = 116 /* XC_sb_v_double_arrow */; break;
case GenericCursorType.SizeNwse: osId = 14 /* XC_bottom_right_corner */; break;
case GenericCursorType.SizeWe: osId = 108 /* XC_sb_h_double_arrow */; break;
}
} else featureNotImplemented();
mc = new MouseCursor(osId);
}
return mc;
}
}
/++
If you want to get more control over the event loop, you can use this.
Typically though, you can just call [SimpleWindow.eventLoop] which forwards
to `EventLoop.get.run`.
+/
struct EventLoop {
@disable this();
/// Gets a reference to an existing event loop
static EventLoop get() {
return EventLoop(0, null);
}
static void quitApplication() {
EventLoop.get().exit();
}
private __gshared static Object monitor = new Object(); // deliberate CTFE usage here fyi
/// Construct an application-global event loop for yourself
/// See_Also: [SimpleWindow.setEventHandlers]
this(long pulseTimeout, void delegate() handlePulse) {
synchronized(monitor) {
if(impl is null) {
claimGuiThread();
version(sdpy_thread_checks) assert(thisIsGuiThread);
impl = new EventLoopImpl(pulseTimeout, handlePulse);
} else {
if(pulseTimeout) {
impl.pulseTimeout = pulseTimeout;
impl.handlePulse = handlePulse;
}
}
impl.refcount++;
}
}
~this() {
if(impl is null)
return;
impl.refcount--;
if(impl.refcount == 0) {
impl.dispose();
if(thisIsGuiThread)
guiThreadFinalize();
}
}
this(this) {
if(impl is null)
return;
impl.refcount++;
}
/// Runs the event loop until the whileCondition, if present, returns false
int run(bool delegate() whileCondition = null) {
assert(impl !is null);
impl.notExited = true;
return impl.run(whileCondition);
}
/// Exits the event loop
void exit() {
assert(impl !is null);
impl.notExited = false;
}
version(linux)
ref void delegate(int) signalHandler() {
assert(impl !is null);
return impl.signalHandler;
}
__gshared static EventLoopImpl* impl;
}
version(linux)
void delegate(int, int) globalHupHandler;
version(Posix)
void makeNonBlocking(int fd) {
import fcntl = core.sys.posix.fcntl;
auto flags = fcntl.fcntl(fd, fcntl.F_GETFL, 0);
if(flags == -1)
throw new Exception("fcntl get");
flags |= fcntl.O_NONBLOCK;
auto s = fcntl.fcntl(fd, fcntl.F_SETFL, flags);
if(s == -1)
throw new Exception("fcntl set");
}
struct EventLoopImpl {
int refcount;
bool notExited = true;
version(linux) {
static import ep = core.sys.linux.epoll;
static import unix = core.sys.posix.unistd;
static import err = core.stdc.errno;
import core.sys.linux.timerfd;
void delegate(int) signalHandler;
}
version(X11) {
int pulseFd = -1;
version(linux) ep.epoll_event[16] events = void;
} else version(Windows) {
Timer pulser;
HANDLE[] handles;
}
/// "Lock" this window handle, to do multithreaded synchronization. You probably won't need
/// to call this, as it's not recommended to share window between threads.
void mtLock () {
version(X11) {
XLockDisplay(this.display);
}
}
version(X11)
auto display() { return XDisplayConnection.get; }
/// "Unlock" this window handle, to do multithreaded synchronization. You probably won't need
/// to call this, as it's not recommended to share window between threads.
void mtUnlock () {
version(X11) {
XUnlockDisplay(this.display);
}
}
version(with_eventloop)
void initialize(long pulseTimeout) {}
else
void initialize(long pulseTimeout) {
version(Windows) {
if(pulseTimeout && handlePulse !is null)
pulser = new Timer(cast(int) pulseTimeout, handlePulse);
if (customEventH is null) {
customEventH = CreateEvent(null, FALSE/*autoreset*/, FALSE/*initial state*/, null);
if (customEventH !is null) {
handles ~= customEventH;
} else {
// this is something that should not be; better be safe than sorry
throw new Exception("can't create eventfd for custom event processing");
}
}
SimpleWindow.processAllCustomEvents(); // process events added before event object creation
}
version(linux) {
prepareEventLoop();
{
auto display = XDisplayConnection.get;
// adding Xlib file
ep.epoll_event ev = void;
{ import core.stdc.string : memset; memset(&ev, 0, ev.sizeof); } // this makes valgrind happy
ev.events = ep.EPOLLIN;
ev.data.fd = display.fd;
//import std.conv;
if(ep.epoll_ctl(epollFd, ep.EPOLL_CTL_ADD, display.fd, &ev) == -1)
throw new Exception("add x fd");// ~ to!string(epollFd));
displayFd = display.fd;
}
if(pulseTimeout && handlePulse !is null) {
pulseFd = timerfd_create(CLOCK_MONOTONIC, 0);
if(pulseFd == -1)
throw new Exception("pulse timer create failed");
itimerspec value;
value.it_value.tv_sec = cast(int) (pulseTimeout / 1000);
value.it_value.tv_nsec = (pulseTimeout % 1000) * 1000_000;
value.it_interval.tv_sec = cast(int) (pulseTimeout / 1000);
value.it_interval.tv_nsec = (pulseTimeout % 1000) * 1000_000;
if(timerfd_settime(pulseFd, 0, &value, null) == -1)
throw new Exception("couldn't make pulse timer");
ep.epoll_event ev = void;
{ import core.stdc.string : memset; memset(&ev, 0, ev.sizeof); } // this makes valgrind happy
ev.events = ep.EPOLLIN;
ev.data.fd = pulseFd;
ep.epoll_ctl(epollFd, ep.EPOLL_CTL_ADD, pulseFd, &ev);
}
// eventfd for custom events
if (customEventFDWrite == -1) {
customEventFDWrite = eventfd(0, 0);
customEventFDRead = customEventFDWrite;
if (customEventFDRead >= 0) {
ep.epoll_event ev = void;
{ import core.stdc.string : memset; memset(&ev, 0, ev.sizeof); } // this makes valgrind happy
ev.events = ep.EPOLLIN;
ev.data.fd = customEventFDRead;
ep.epoll_ctl(epollFd, ep.EPOLL_CTL_ADD, customEventFDRead, &ev);
} else {
// this is something that should not be; better be safe than sorry
throw new Exception("can't create eventfd for custom event processing");
}
}
if (customSignalFD == -1) {
import core.sys.linux.sys.signalfd;
sigset_t sigset;
auto err = sigemptyset(&sigset);
assert(!err);
err = sigaddset(&sigset, SIGINT);
assert(!err);
err = sigaddset(&sigset, SIGHUP);
assert(!err);
err = sigprocmask(SIG_BLOCK, &sigset, null);
assert(!err);
customSignalFD = signalfd(-1, &sigset, SFD_NONBLOCK);
assert(customSignalFD != -1);
ep.epoll_event ev = void;
{ import core.stdc.string : memset; memset(&ev, 0, ev.sizeof); } // this makes valgrind happy
ev.events = ep.EPOLLIN;
ev.data.fd = customSignalFD;
ep.epoll_ctl(epollFd, ep.EPOLL_CTL_ADD, customSignalFD, &ev);
}
} else version(Posix) {
prepareEventLoop();
if (customEventFDRead == -1) {
int[2] bfr;
import core.sys.posix.unistd;
auto ret = pipe(bfr);
if(ret == -1) throw new Exception("pipe");
customEventFDRead = bfr[0];
customEventFDWrite = bfr[1];
}
}
SimpleWindow.processAllCustomEvents(); // process events added before event FD creation
version(linux) {
this.mtLock();
scope(exit) this.mtUnlock();
XPending(display); // no, really
}
disposed = false;
}
bool disposed = true;
version(X11)
int displayFd = -1;
version(with_eventloop)
void dispose() {}
else
void dispose() {
disposed = true;
version(X11) {
if(pulseFd != -1) {
import unix = core.sys.posix.unistd;
unix.close(pulseFd);
pulseFd = -1;
}
version(linux)
if(displayFd != -1) {
// clean up xlib fd when we exit, in case we come back later e.g. X disconnect and reconnect with new FD, don't want to still keep the old one around
ep.epoll_event ev = void;
{ import core.stdc.string : memset; memset(&ev, 0, ev.sizeof); } // this makes valgrind happy
ev.events = ep.EPOLLIN;
ev.data.fd = displayFd;
//import std.conv;
ep.epoll_ctl(epollFd, ep.EPOLL_CTL_DEL, displayFd, &ev);
displayFd = -1;
}
} else version(Windows) {
if(pulser !is null) {
pulser.destroy();
pulser = null;
}
if (customEventH !is null) {
CloseHandle(customEventH);
customEventH = null;
}
}
}
this(long pulseTimeout, void delegate() handlePulse) {
this.pulseTimeout = pulseTimeout;
this.handlePulse = handlePulse;
initialize(pulseTimeout);
}
private long pulseTimeout;
void delegate() handlePulse;
~this() {
dispose();
}
version(Posix)
ref int customEventFDRead() { return SimpleWindow.customEventFDRead; }
version(Posix)
ref int customEventFDWrite() { return SimpleWindow.customEventFDWrite; }
version(linux)
ref int customSignalFD() { return SimpleWindow.customSignalFD; }
version(Windows)
ref auto customEventH() { return SimpleWindow.customEventH; }
version(with_eventloop) {
int loopHelper(bool delegate() whileCondition) {
// FIXME: whileCondition
import arsd.eventloop;
loop();
return 0;
}
} else
int loopHelper(bool delegate() whileCondition) {
version(X11) {
bool done = false;
XFlush(display);
insideXEventLoop = true;
scope(exit) insideXEventLoop = false;
version(linux) {
while(!done && (whileCondition is null || whileCondition() == true) && notExited) {
bool forceXPending = false;
auto wto = SimpleWindow.eventAllQueueTimeoutMSecs();
// eh... some events may be queued for "squashing" (or "late delivery"), so we have to do the following magic
{
this.mtLock();
scope(exit) this.mtUnlock();
if (XEventsQueued(this.display, QueueMode.QueuedAlready)) { forceXPending = true; if (wto > 10 || wto <= 0) wto = 10; } // so libX event loop will be able to do it's work
}
//{ import core.stdc.stdio; printf("*** wto=%d; force=%d\n", wto, (forceXPending ? 1 : 0)); }
auto nfds = ep.epoll_wait(epollFd, events.ptr, events.length, (wto == 0 || wto >= int.max ? -1 : cast(int)wto));
if(nfds == -1) {
if(err.errno == err.EINTR) {
//if(forceXPending) goto xpending;
continue; // interrupted by signal, just try again
}
throw new Exception("epoll wait failure");
}
SimpleWindow.processAllCustomEvents(); // anyway
//version(sdddd) { import std.stdio; writeln("nfds=", nfds, "; [0]=", events[0].data.fd); }
foreach(idx; 0 .. nfds) {
if(done) break;
auto fd = events[idx].data.fd;
assert(fd != -1); // should never happen cuz the api doesn't do that but better to assert than assume.
auto flags = events[idx].events;
if(flags & ep.EPOLLIN) {
if (fd == customSignalFD) {
version(linux) {
import core.sys.linux.sys.signalfd;
import core.sys.posix.unistd : read;
signalfd_siginfo info;
read(customSignalFD, &info, info.sizeof);
auto sig = info.ssi_signo;
if(EventLoop.get.signalHandler !is null) {
EventLoop.get.signalHandler()(sig);
} else {
EventLoop.get.exit();
}
}
} else if(fd == display.fd) {
version(sdddd) { import std.stdio; writeln("X EVENT PENDING!"); }
this.mtLock();
scope(exit) this.mtUnlock();
while(!done && XPending(display)) {
done = doXNextEvent(this.display);
}
forceXPending = false;
} else if(fd == pulseFd) {
long expirationCount;
// if we go over the count, I ignore it because i don't want the pulse to go off more often and eat tons of cpu time...
handlePulse();
// read just to clear the buffer so poll doesn't trigger again
// BTW I read AFTER the pulse because if the pulse handler takes
// a lot of time to execute, we don't want the app to get stuck
// in a loop of timer hits without a chance to do anything else
//
// IOW handlePulse happens at most once per pulse interval.
unix.read(pulseFd, &expirationCount, expirationCount.sizeof);
forceXPending = true; // some events might have been added while the pulse was going off and xlib already read it from the fd (like as a result of a draw done in the timer handler). if so we need to flush that separately to ensure it is not delayed
} else if (fd == customEventFDRead) {
// we have some custom events; process 'em
import core.sys.posix.unistd : read;
ulong n;
read(customEventFDRead, &n, n.sizeof); // reset counter value to zero again
//{ import core.stdc.stdio; printf("custom event! count=%u\n", eventQueueUsed); }
//SimpleWindow.processAllCustomEvents();
} else {
// some other timer
version(sdddd) { import std.stdio; writeln("unknown fd: ", fd); }
if(Timer* t = fd in Timer.mapping)
(*t).trigger();
if(PosixFdReader* pfr = fd in PosixFdReader.mapping)
(*pfr).ready(flags);
// or i might add support for other FDs too
// but for now it is just timer
// (if you want other fds, use arsd.eventloop and compile with -version=with_eventloop), it offers a fuller api for arbitrary stuff.
}
}
if(flags & ep.EPOLLHUP) {
if(PosixFdReader* pfr = fd in PosixFdReader.mapping)
(*pfr).hup(flags);
if(globalHupHandler)
globalHupHandler(fd, flags);
}
/+
} else {
// not interested in OUT, we are just reading here.
//
// error or hup might also be reported
// but it shouldn't here since we are only
// using a few types of FD and Xlib will report
// if it dies.
// so instead of thoughtfully handling it, I'll
// just throw. for now at least
throw new Exception("epoll did something else");
}
+/
}
// if we won't call `XPending()` here, libX may delay some internal event delivery.
// i.e. we HAVE to repeatedly call `XPending()` even if libX fd wasn't signalled!
xpending:
if (!done && forceXPending) {
this.mtLock();
scope(exit) this.mtUnlock();
//{ import core.stdc.stdio; printf("*** queued: %d\n", XEventsQueued(this.display, QueueMode.QueuedAlready)); }
while(!done && XPending(display)) {
done = doXNextEvent(this.display);
}
}
}
} else {
// Generic fallback: yes to simple pulse support,
// but NO timer support!
// FIXME: we could probably support the POSIX timer_create
// signal-based option, but I'm in no rush to write it since
// I prefer the fd-based functions.
while (!done && (whileCondition is null || whileCondition() == true) && notExited) {
import core.sys.posix.poll;
pollfd[] pfds;
pollfd[32] pfdsBuffer;
auto len = PosixFdReader.mapping.length + 2;
// FIXME: i should just reuse the buffer
if(len < pfdsBuffer.length)
pfds = pfdsBuffer[0 .. len];
else
pfds = new pollfd[](len);
pfds[0].fd = display.fd;
pfds[0].events = POLLIN;
pfds[0].revents = 0;
int slot = 1;
if(customEventFDRead != -1) {
pfds[slot].fd = customEventFDRead;
pfds[slot].events = POLLIN;
pfds[slot].revents = 0;
slot++;
}
foreach(fd, obj; PosixFdReader.mapping) {
if(!obj.enabled) continue;
pfds[slot].fd = fd;
pfds[slot].events = POLLIN;
pfds[slot].revents = 0;
slot++;
}
auto ret = poll(pfds.ptr, slot, pulseTimeout > 0 ? cast(int) pulseTimeout : -1);
if(ret == -1) throw new Exception("poll");
if(ret == 0) {
// FIXME it may not necessarily time out if events keep coming
if(handlePulse !is null)
handlePulse();
} else {
foreach(s; 0 .. slot) {
if(pfds[s].revents == 0) continue;
if(pfds[s].fd == display.fd) {
while(!done && XPending(display)) {
this.mtLock();
scope(exit) this.mtUnlock();
done = doXNextEvent(this.display);
}
} else if(customEventFDRead != -1 && pfds[s].fd == customEventFDRead) {
import core.sys.posix.unistd : read;
ulong n;
read(customEventFDRead, &n, n.sizeof);
SimpleWindow.processAllCustomEvents();
} else {
auto obj = PosixFdReader.mapping[pfds[s].fd];
if(pfds[s].revents & POLLNVAL) {
obj.dispose();
} else {
obj.ready(pfds[s].revents);
}
}
ret--;
if(ret == 0) break;
}
}
}
}
}
version(Windows) {
int ret = -1;
MSG message;
while(ret != 0 && (whileCondition is null || whileCondition() == true) && notExited) {
eventLoopRound++;
auto wto = SimpleWindow.eventAllQueueTimeoutMSecs();
auto waitResult = MsgWaitForMultipleObjectsEx(
cast(int) handles.length, handles.ptr,
(wto == 0 ? INFINITE : wto), /* timeout */
0x04FF, /* QS_ALLINPUT */
0x0002 /* MWMO_ALERTABLE */ | 0x0004 /* MWMO_INPUTAVAILABLE */);
SimpleWindow.processAllCustomEvents(); // anyway
enum WAIT_OBJECT_0 = 0;
if(waitResult >= WAIT_OBJECT_0 && waitResult < handles.length + WAIT_OBJECT_0) {
auto h = handles[waitResult - WAIT_OBJECT_0];
if(auto e = h in WindowsHandleReader.mapping) {
(*e).ready();
}
} else if(waitResult == handles.length + WAIT_OBJECT_0) {
// message ready
int count;
while(PeekMessage(&message, null, 0, 0, PM_NOREMOVE)) { // need to peek since sometimes MsgWaitForMultipleObjectsEx returns even though GetMessage can block. tbh i don't fully understand it but the docs say it is foreground activation
ret = GetMessage(&message, null, 0, 0);
if(ret == -1)
throw new Exception("GetMessage failed");
TranslateMessage(&message);
DispatchMessage(&message);
count++;
if(count > 10)
break; // take the opportunity to catch up on other events
if(ret == 0) { // WM_QUIT
EventLoop.quitApplication();
break;
}
}
} else if(waitResult == 0x000000C0L /* WAIT_IO_COMPLETION */) {
SleepEx(0, true); // I call this to give it a chance to do stuff like async io
} else if(waitResult == 258L /* WAIT_TIMEOUT */) {
// timeout, should never happen since we aren't using it
} else if(waitResult == 0xFFFFFFFF) {
// failed
throw new Exception("MsgWaitForMultipleObjectsEx failed");
} else {
// idk....
}
}
// return message.wParam;
return 0;
} else {
return 0;
}
}
int run(bool delegate() whileCondition = null) {
if(disposed)
initialize(this.pulseTimeout);
version(X11) {
try {
return loopHelper(whileCondition);
} catch(XDisconnectException e) {
if(e.userRequested) {
foreach(item; CapableOfHandlingNativeEvent.nativeHandleMapping)
item.discardConnectionState();
XCloseDisplay(XDisplayConnection.display);
}
XDisplayConnection.display = null;
this.dispose();
throw e;
}
} else {
return loopHelper(whileCondition);
}
}
}
/++
Provides an icon on the system notification area (also known as the system tray).
If a notification area is not available with the NotificationIcon object is created,
it will silently succeed and simply attempt to create one when an area becomes available.
NotificationAreaIcon on Windows assumes you are on Windows Vista or later.
If this is wrong, pass -version=WindowsXP to dmd when compiling and it will
use the older version.
+/
version(OSXCocoa) {} else // NotYetImplementedException
class NotificationAreaIcon : CapableOfHandlingNativeEvent {
version(X11) {
void recreateAfterDisconnect() {
stateDiscarded = false;
clippixmap = None;
throw new Exception("NOT IMPLEMENTED");
}
bool stateDiscarded;
void discardConnectionState() {
stateDiscarded = true;
}
}
version(X11) {
Image img;
NativeEventHandler getNativeEventHandler() {
return delegate int(XEvent e) {
switch(e.type) {
case EventType.Expose:
//case EventType.VisibilityNotify:
redraw();
break;
case EventType.ClientMessage:
version(sddddd) {
import std.stdio;
writeln("\t", e.xclient.message_type == GetAtom!("_XEMBED")(XDisplayConnection.get));
writeln("\t", e.xclient.format);
writeln("\t", e.xclient.data.l);
}
break;
case EventType.ButtonPress:
auto event = e.xbutton;
if (onClick !is null || onClickEx !is null) {
MouseButton mb = cast(MouseButton)0;
switch (event.button) {
case 1: mb = MouseButton.left; break; // left
case 2: mb = MouseButton.middle; break; // middle
case 3: mb = MouseButton.right; break; // right
case 4: mb = MouseButton.wheelUp; break; // scroll up
case 5: mb = MouseButton.wheelDown; break; // scroll down
case 6: break; // scroll left...
case 7: break; // scroll right...
case 8: mb = MouseButton.backButton; break;
case 9: mb = MouseButton.forwardButton; break;
default:
}
if (mb) {
try { onClick()(mb); } catch (Exception) {}
if (onClickEx !is null) try { onClickEx(event.x_root, event.y_root, mb, cast(ModifierState)event.state); } catch (Exception) {}
}
}
break;
case EventType.EnterNotify:
if (onEnter !is null) {
onEnter(e.xcrossing.x_root, e.xcrossing.y_root, cast(ModifierState)e.xcrossing.state);
}
break;
case EventType.LeaveNotify:
if (onLeave !is null) try { onLeave(); } catch (Exception) {}
break;
case EventType.DestroyNotify:
active = false;
CapableOfHandlingNativeEvent.nativeHandleMapping.remove(nativeHandle);
break;
case EventType.ConfigureNotify:
auto event = e.xconfigure;
this.width = event.width;
this.height = event.height;
//import std.stdio; writeln(width, " x " , height, " @ ", event.x, " ", event.y);
redraw();
break;
default: return 1;
}
return 1;
};
}
/* private */ void hideBalloon() {
balloon.close();
version(with_timer)
timer.destroy();
balloon = null;
version(with_timer)
timer = null;
}
void redraw() {
if (!active) return;
auto display = XDisplayConnection.get;
auto gc = DefaultGC(display, DefaultScreen(display));
XClearWindow(display, nativeHandle);
XSetClipMask(display, gc, clippixmap);
XSetForeground(display, gc,
cast(uint) 0 << 16 |
cast(uint) 0 << 8 |
cast(uint) 0);
XFillRectangle(display, nativeHandle, gc, 0, 0, width, height);
if (img is null) {
XSetForeground(display, gc,
cast(uint) 0 << 16 |
cast(uint) 127 << 8 |
cast(uint) 0);
XFillArc(display, nativeHandle,
gc, width / 4, height / 4, width * 2 / 4, height * 2 / 4, 0 * 64, 360 * 64);
} else {
int dx = 0;
int dy = 0;
if(width > img.width)
dx = (width - img.width) / 2;
if(height > img.height)
dy = (height - img.height) / 2;
XSetClipOrigin(display, gc, dx, dy);
if (img.usingXshm)
XShmPutImage(display, cast(Drawable)nativeHandle, gc, img.handle, 0, 0, dx, dy, img.width, img.height, false);
else
XPutImage(display, cast(Drawable)nativeHandle, gc, img.handle, 0, 0, dx, dy, img.width, img.height);
}
XSetClipMask(display, gc, None);
flushGui();
}
static Window getTrayOwner() {
auto display = XDisplayConnection.get;
auto i = cast(int) DefaultScreen(display);
if(i < 10 && i >= 0) {
static Atom atom;
if(atom == None)
atom = XInternAtom(display, cast(char*) ("_NET_SYSTEM_TRAY_S"~(cast(char) (i + '0')) ~ '\0').ptr, false);
return XGetSelectionOwner(display, atom);
}
return None;
}
static void sendTrayMessage(arch_long message, arch_long d1, arch_long d2, arch_long d3) {
auto to = getTrayOwner();
auto display = XDisplayConnection.get;
XEvent ev;
ev.xclient.type = EventType.ClientMessage;
ev.xclient.window = to;
ev.xclient.message_type = GetAtom!("_NET_SYSTEM_TRAY_OPCODE", true)(display);
ev.xclient.format = 32;
ev.xclient.data.l[0] = CurrentTime;
ev.xclient.data.l[1] = message;
ev.xclient.data.l[2] = d1;
ev.xclient.data.l[3] = d2;
ev.xclient.data.l[4] = d3;
XSendEvent(XDisplayConnection.get, to, false, EventMask.NoEventMask, &ev);
}
private static NotificationAreaIcon[] activeIcons;
// FIXME: possible leak with this stuff, should be able to clear it and stuff.
private void newManager() {
close();
createXWin();
if(this.clippixmap)
XFreePixmap(XDisplayConnection.get, clippixmap);
if(this.originalMemoryImage)
this.icon = this.originalMemoryImage;
else if(this.img)
this.icon = this.img;
}
private void createXWin () {
// create window
auto display = XDisplayConnection.get;
// to check for MANAGER on root window to catch new/changed tray owners
XDisplayConnection.addRootInput(EventMask.StructureNotifyMask);
// so if a thing does appear, we can handle it
foreach(ai; activeIcons)
if(ai is this)
goto alreadythere;
activeIcons ~= this;
alreadythere:
// and check for an existing tray
auto trayOwner = getTrayOwner();
if(trayOwner == None)
return;
//throw new Exception("No notification area found");
Visual* v = cast(Visual*) CopyFromParent;
/+
auto visualProp = getX11PropertyData(trayOwner, GetAtom!("_NET_SYSTEM_TRAY_VISUAL", true)(display));
if(visualProp !is null) {
c_ulong[] info = cast(c_ulong[]) visualProp;
if(info.length == 1) {
auto vid = info[0];
int returned;
XVisualInfo t;
t.visualid = vid;
auto got = XGetVisualInfo(display, VisualIDMask, &t, &returned);
if(got !is null) {
if(returned == 1) {
v = got.visual;
import std.stdio;
writeln("using special visual ", *got);
}
XFree(got);
}
}
}
+/
auto nativeWindow = XCreateWindow(display, RootWindow(display, DefaultScreen(display)), 0, 0, 16, 16, 0, 24, InputOutput, v, 0, null);
assert(nativeWindow);
XSetWindowBackgroundPixmap(display, nativeWindow, 1 /* ParentRelative */);
nativeHandle = nativeWindow;
///+
arch_ulong[2] info;
info[0] = 0;
info[1] = 1;
string title = this.name is null ? "simpledisplay.d program" : this.name;
auto XA_UTF8 = XInternAtom(display, "UTF8_STRING".ptr, false);
auto XA_NETWM_NAME = XInternAtom(display, "_NET_WM_NAME".ptr, false);
XChangeProperty(display, nativeWindow, XA_NETWM_NAME, XA_UTF8, 8, PropModeReplace, title.ptr, cast(uint)title.length);
XChangeProperty(
display,
nativeWindow,
GetAtom!("_XEMBED_INFO", true)(display),
GetAtom!("_XEMBED_INFO", true)(display),
32 /* bits */,
0 /*PropModeReplace*/,
info.ptr,
2);
import core.sys.posix.unistd;
arch_ulong pid = getpid();
XChangeProperty(
display,
nativeWindow,
GetAtom!("_NET_WM_PID", true)(display),
XA_CARDINAL,
32 /* bits */,
0 /*PropModeReplace*/,
&pid,
1);
updateNetWmIcon();
if (sdpyWindowClassStr !is null && sdpyWindowClassStr[0]) {
//{ import core.stdc.stdio; printf("winclass: [%s]\n", sdpyWindowClassStr); }
XClassHint klass;
XWMHints wh;
XSizeHints size;
klass.res_name = sdpyWindowClassStr;
klass.res_class = sdpyWindowClassStr;
XSetWMProperties(display, nativeWindow, null, null, null, 0, &size, &wh, &klass);
}
// believe it or not, THIS is what xfce needed for the 9999 issue
XSizeHints sh;
c_long spr;
XGetWMNormalHints(display, nativeWindow, &sh, &spr);
sh.flags |= PMaxSize | PMinSize;
// FIXME maybe nicer resizing
sh.min_width = 16;
sh.min_height = 16;
sh.max_width = 16;
sh.max_height = 16;
XSetWMNormalHints(display, nativeWindow, &sh);
//+/
XSelectInput(display, nativeWindow,
EventMask.ButtonPressMask | EventMask.ExposureMask | EventMask.StructureNotifyMask | EventMask.VisibilityChangeMask |
EventMask.EnterWindowMask | EventMask.LeaveWindowMask);
sendTrayMessage(SYSTEM_TRAY_REQUEST_DOCK, nativeWindow, 0, 0);
CapableOfHandlingNativeEvent.nativeHandleMapping[nativeWindow] = this;
active = true;
}
void updateNetWmIcon() {
if(img is null) return;
auto display = XDisplayConnection.get;
// FIXME: ensure this is correct
arch_ulong[] buffer;
auto imgMi = img.toTrueColorImage;
buffer ~= imgMi.width;
buffer ~= imgMi.height;
foreach(c; imgMi.imageData.colors) {
arch_ulong b;
b |= c.a << 24;
b |= c.r << 16;
b |= c.g << 8;
b |= c.b;
buffer ~= b;
}
XChangeProperty(
display,
nativeHandle,
GetAtom!"_NET_WM_ICON"(display),
GetAtom!"CARDINAL"(display),
32 /* bits */,
0 /*PropModeReplace*/,
buffer.ptr,
cast(int) buffer.length);
}
private SimpleWindow balloon;
version(with_timer)
private Timer timer;
private Window nativeHandle;
private Pixmap clippixmap = None;
private int width = 16;
private int height = 16;
private bool active = false;
void delegate (int x, int y, MouseButton button, ModifierState mods) onClickEx; /// x and y are globals (relative to root window). X11 only.
void delegate (int x, int y, ModifierState mods) onEnter; /// x and y are global window coordinates. X11 only.
void delegate () onLeave; /// X11 only.
@property bool closed () const pure nothrow @safe @nogc { return !active; } ///
/// X11 only. Get global window coordinates and size. This can be used to show various notifications.
void getWindowRect (out int x, out int y, out int width, out int height) {
if (!active) { width = 1; height = 1; return; } // 1: just in case
Window dummyw;
auto dpy = XDisplayConnection.get;
//XWindowAttributes xwa;
//XGetWindowAttributes(dpy, nativeHandle, &xwa);
//XTranslateCoordinates(dpy, nativeHandle, RootWindow(dpy, DefaultScreen(dpy)), xwa.x, xwa.y, &x, &y, &dummyw);
XTranslateCoordinates(dpy, nativeHandle, RootWindow(dpy, DefaultScreen(dpy)), x, y, &x, &y, &dummyw);
width = this.width;
height = this.height;
}
}
/+
What I actually want from this:
* set / change: icon, tooltip
* handle: mouse click, right click
* show: notification bubble.
+/
version(Windows) {
WindowsIcon win32Icon;
HWND hwnd;
NOTIFYICONDATAW data;
NativeEventHandler getNativeEventHandler() {
return delegate int(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam, out int mustReturn) {
if(msg == WM_USER) {
auto event = LOWORD(lParam);
auto iconId = HIWORD(lParam);
//auto x = GET_X_LPARAM(wParam);
//auto y = GET_Y_LPARAM(wParam);
switch(event) {
case WM_LBUTTONDOWN:
onClick()(MouseButton.left);
break;
case WM_RBUTTONDOWN:
onClick()(MouseButton.right);
break;
case WM_MBUTTONDOWN:
onClick()(MouseButton.middle);
break;
case WM_MOUSEMOVE:
// sent, we could use it.
break;
case WM_MOUSEWHEEL:
// NOT SENT
break;
//case NIN_KEYSELECT:
//case NIN_SELECT:
//break;
default: {}
}
}
return 0;
};
}
enum NIF_SHOWTIP = 0x00000080;
private static struct NOTIFYICONDATAW {
DWORD cbSize;
HWND hWnd;
UINT uID;
UINT uFlags;
UINT uCallbackMessage;
HICON hIcon;
WCHAR[128] szTip;
DWORD dwState;
DWORD dwStateMask;
WCHAR[256] szInfo;
union {
UINT uTimeout;
UINT uVersion;
}
WCHAR[64] szInfoTitle;
DWORD dwInfoFlags;
GUID guidItem;
HICON hBalloonIcon;
}
}
/++
Note that on Windows, only left, right, and middle buttons are sent.
Mouse wheel buttons are NOT set, so don't rely on those events if your
program is meant to be used on Windows too.
+/
this(string name, MemoryImage icon, void delegate(MouseButton button) onClick) {
// The canonical constructor for Windows needs the MemoryImage, so it is here,
// but on X, we need an Image, so its canonical ctor is there. They should
// forward to each other though.
version(X11) {
this.name = name;
this.onClick = onClick;
createXWin();
this.icon = icon;
} else version(Windows) {
this.onClick = onClick;
this.win32Icon = new WindowsIcon(icon);
HINSTANCE hInstance = cast(HINSTANCE) GetModuleHandle(null);
static bool registered = false;
if(!registered) {
WNDCLASSEX wc;
wc.cbSize = wc.sizeof;
wc.hInstance = hInstance;
wc.lpfnWndProc = &WndProc;
wc.lpszClassName = "arsd_simpledisplay_notification_icon"w.ptr;
if(!RegisterClassExW(&wc))
throw new WindowsApiException("RegisterClass");
registered = true;
}
this.hwnd = CreateWindowW("arsd_simpledisplay_notification_icon"w.ptr, "test"w.ptr /* name */, 0 /* dwStyle */, 0, 0, 0, 0, HWND_MESSAGE, null, hInstance, null);
if(hwnd is null)
throw new Exception("CreateWindow");
data.cbSize = data.sizeof;
data.hWnd = hwnd;
data.uID = cast(uint) cast(void*) this;
data.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_STATE | NIF_SHOWTIP /* use default tooltip, for now. */;
// NIF_INFO means show balloon
data.uCallbackMessage = WM_USER;
data.hIcon = this.win32Icon.hIcon;
data.szTip = ""; // FIXME
data.dwState = 0; // NIS_HIDDEN; // windows vista
data.dwStateMask = NIS_HIDDEN; // windows vista
data.uVersion = 4; // NOTIFYICON_VERSION_4; // Windows Vista and up
Shell_NotifyIcon(NIM_ADD, cast(NOTIFYICONDATA*) &data);
CapableOfHandlingNativeEvent.nativeHandleMapping[this.hwnd] = this;
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
/// ditto
this(string name, Image icon, void delegate(MouseButton button) onClick) {
version(X11) {
this.onClick = onClick;
this.name = name;
createXWin();
this.icon = icon;
} else version(Windows) {
this(name, icon is null ? null : icon.toTrueColorImage(), onClick);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
version(X11) {
/++
X-specific extension (for now at least)
+/
this(string name, MemoryImage icon, void delegate(int x, int y, MouseButton button, ModifierState mods) onClickEx) {
this.onClickEx = onClickEx;
createXWin();
if (icon !is null) this.icon = icon;
}
/// ditto
this(string name, Image icon, void delegate(int x, int y, MouseButton button, ModifierState mods) onClickEx) {
this.onClickEx = onClickEx;
createXWin();
this.icon = icon;
}
}
private void delegate (MouseButton button) onClick_;
///
@property final void delegate(MouseButton) onClick() {
if(onClick_ is null)
onClick_ = delegate void(MouseButton) {};
return onClick_;
}
/// ditto
@property final void onClick(void delegate(MouseButton) handler) {
// I made this a property setter so we can wrap smaller arg
// delegates and just forward all to onClickEx or something.
onClick_ = handler;
}
string name_;
@property void name(string n) {
name_ = n;
}
@property string name() {
return name_;
}
private MemoryImage originalMemoryImage;
///
@property void icon(MemoryImage i) {
version(X11) {
this.originalMemoryImage = i;
if (!active) return;
if (i !is null) {
this.img = Image.fromMemoryImage(i);
this.clippixmap = transparencyMaskFromMemoryImage(i, nativeHandle);
//import std.stdio; writeln("using pixmap ", clippixmap);
updateNetWmIcon();
redraw();
} else {
if (this.img !is null) {
this.img = null;
redraw();
}
}
} else version(Windows) {
this.win32Icon = new WindowsIcon(i);
data.uFlags = NIF_ICON;
data.hIcon = this.win32Icon.hIcon;
Shell_NotifyIcon(NIM_MODIFY, cast(NOTIFYICONDATA*) &data);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
/// ditto
@property void icon (Image i) {
version(X11) {
if (!active) return;
if (i !is img) {
originalMemoryImage = null;
img = i;
redraw();
}
} else version(Windows) {
this.icon(i is null ? null : i.toTrueColorImage());
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
/++
Shows a balloon notification. You can only show one balloon at a time, if you call
it twice while one is already up, the first balloon will be replaced.
The user is free to block notifications and they will automatically disappear after
a timeout period.
Params:
title = Title of the notification. Must be 40 chars or less or the OS may truncate it.
message = The message to pop up. Must be 220 chars or less or the OS may truncate it.
icon = the icon to display with the notification. If null, it uses your existing icon.
onclick = delegate called if the user clicks the balloon. (not yet implemented)
timeout = your suggested timeout period. The operating system is free to ignore your suggestion.
+/
void showBalloon(string title, string message, MemoryImage icon = null, void delegate() onclick = null, int timeout = 2_500) {
bool useCustom = true;
version(libnotify) {
if(onclick is null) // libnotify impl doesn't support callbacks yet because it doesn't do a dbus message loop
try {
if(!active) return;
if(libnotify is null) {
libnotify = new C_DynamicLibrary("libnotify.so");
libnotify.call!("notify_init", int, const char*)()((ApplicationName ~ "\0").ptr);
}
auto n = libnotify.call!("notify_notification_new", void*, const char*, const char*, const char*)()((title~"\0").ptr, (message~"\0").ptr, null /* icon */);
libnotify.call!("notify_notification_set_timeout", void, void*, int)()(n, timeout);
if(onclick) {
libnotify_action_delegates[libnotify_action_delegates_count] = onclick;
libnotify.call!("notify_notification_add_action", void, void*, const char*, const char*, typeof(&libnotify_action_callback_sdpy), void*, void*)()(n, "DEFAULT".ptr, "Go".ptr, &libnotify_action_callback_sdpy, cast(void*) libnotify_action_delegates_count, null);
libnotify_action_delegates_count++;
}
// FIXME icon
// set hint image-data
// set default action for onclick
void* error;
libnotify.call!("notify_notification_show", bool, void*, void**)()(n, &error);
useCustom = false;
} catch(Exception e) {
}
}
version(X11) {
if(useCustom) {
if(!active) return;
if(balloon) {
hideBalloon();
}
// I know there are two specs for this, but one is never
// implemented by any window manager I have ever seen, and
// the other is a bloated mess and too complicated for simpledisplay...
// so doing my own little window instead.
balloon = new SimpleWindow(380, 120, null, OpenGlOptions.no, Resizability.fixedSize, WindowTypes.notification, WindowFlags.dontAutoShow/*, window*/);
int x, y, width, height;
getWindowRect(x, y, width, height);
int bx = x - balloon.width;
int by = y - balloon.height;
if(bx < 0)
bx = x + width + balloon.width;
if(by < 0)
by = y + height;
// just in case, make sure it is actually on scren
if(bx < 0)
bx = 0;
if(by < 0)
by = 0;
balloon.move(bx, by);
auto painter = balloon.draw();
painter.fillColor = Color(220, 220, 220);
painter.outlineColor = Color.black;
painter.drawRectangle(Point(0, 0), balloon.width, balloon.height);
auto iconWidth = icon is null ? 0 : icon.width;
if(icon)
painter.drawImage(Point(4, 4), Image.fromMemoryImage(icon));
iconWidth += 6; // margin around the icon
// draw a close button
painter.outlineColor = Color(44, 44, 44);
painter.fillColor = Color(255, 255, 255);
painter.drawRectangle(Point(balloon.width - 15, 3), 13, 13);
painter.pen = Pen(Color.black, 3);
painter.drawLine(Point(balloon.width - 14, 4), Point(balloon.width - 4, 14));
painter.drawLine(Point(balloon.width - 4, 4), Point(balloon.width - 14, 13));
painter.pen = Pen(Color.black, 1);
painter.fillColor = Color(220, 220, 220);
// Draw the title and message
painter.drawText(Point(4 + iconWidth, 4), title);
painter.drawLine(
Point(4 + iconWidth, 4 + painter.fontHeight + 1),
Point(balloon.width - 4, 4 + painter.fontHeight + 1),
);
painter.drawText(Point(4 + iconWidth, 4 + painter.fontHeight + 4), message);
balloon.setEventHandlers(
(MouseEvent ev) {
if(ev.type == MouseEventType.buttonPressed) {
if(ev.x > balloon.width - 16 && ev.y < 16)
hideBalloon();
else if(onclick)
onclick();
}
}
);
balloon.show();
version(with_timer)
timer = new Timer(timeout, &hideBalloon);
else {} // FIXME
}
} else version(Windows) {
enum NIF_INFO = 0x00000010;
data.uFlags = NIF_INFO;
// FIXME: go back to the last valid unicode code point
if(title.length > 40)
title = title[0 .. 40];
if(message.length > 220)
message = message[0 .. 220];
enum NIIF_RESPECT_QUIET_TIME = 0x00000080;
enum NIIF_LARGE_ICON = 0x00000020;
enum NIIF_NOSOUND = 0x00000010;
enum NIIF_USER = 0x00000004;
enum NIIF_ERROR = 0x00000003;
enum NIIF_WARNING = 0x00000002;
enum NIIF_INFO = 0x00000001;
enum NIIF_NONE = 0;
WCharzBuffer t = WCharzBuffer(title);
WCharzBuffer m = WCharzBuffer(message);
t.copyInto(data.szInfoTitle);
m.copyInto(data.szInfo);
data.dwInfoFlags = NIIF_RESPECT_QUIET_TIME;
if(icon !is null) {
auto i = new WindowsIcon(icon);
data.hBalloonIcon = i.hIcon;
data.dwInfoFlags |= NIIF_USER;
}
Shell_NotifyIcon(NIM_MODIFY, cast(NOTIFYICONDATA*) &data);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
///
//version(Windows)
void show() {
version(X11) {
if(!hidden)
return;
sendTrayMessage(SYSTEM_TRAY_REQUEST_DOCK, nativeHandle, 0, 0);
hidden = false;
} else version(Windows) {
data.uFlags = NIF_STATE;
data.dwState = 0; // NIS_HIDDEN; // windows vista
data.dwStateMask = NIS_HIDDEN; // windows vista
Shell_NotifyIcon(NIM_MODIFY, cast(NOTIFYICONDATA*) &data);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
version(X11)
bool hidden = false;
///
//version(Windows)
void hide() {
version(X11) {
if(hidden)
return;
hidden = true;
XUnmapWindow(XDisplayConnection.get, nativeHandle);
} else version(Windows) {
data.uFlags = NIF_STATE;
data.dwState = NIS_HIDDEN; // windows vista
data.dwStateMask = NIS_HIDDEN; // windows vista
Shell_NotifyIcon(NIM_MODIFY, cast(NOTIFYICONDATA*) &data);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
///
void close () {
version(X11) {
if (active) {
active = false; // event handler will set this too, but meh
XUnmapWindow(XDisplayConnection.get, nativeHandle); // 'cause why not; let's be polite
XDestroyWindow(XDisplayConnection.get, nativeHandle);
flushGui();
}
} else version(Windows) {
Shell_NotifyIcon(NIM_DELETE, cast(NOTIFYICONDATA*) &data);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
~this() {
if(!thisIsGuiThread) return; // FIXME: leaks if multithreaded gc
version(X11)
if(clippixmap != None)
XFreePixmap(XDisplayConnection.get, clippixmap);
close();
}
}
version(X11)
/// Call `XFreePixmap` on the return value.
Pixmap transparencyMaskFromMemoryImage(MemoryImage i, Window window) {
char[] data = new char[](i.width * i.height / 8 + 2);
data[] = 0;
int bitOffset = 0;
foreach(c; i.getAsTrueColorImage().imageData.colors) { // FIXME inefficient unnecessary conversion in palette cases
ubyte v = c.a > 128 ? 1 : 0;
data[bitOffset / 8] |= v << (bitOffset%8);
bitOffset++;
}
auto handle = XCreateBitmapFromData(XDisplayConnection.get, cast(Drawable) window, data.ptr, i.width, i.height);
return handle;
}
// basic functions to make timers
/**
A timer that will trigger your function on a given interval.
You create a timer with an interval and a callback. It will continue
to fire on the interval until it is destroyed.
There are currently no one-off timers (instead, just create one and
destroy it when it is triggered) nor are there pause/resume functions -
the timer must again be destroyed and recreated if you want to pause it.
auto timer = new Timer(50, { it happened!; });
timer.destroy();
Timers can only be expected to fire when the event loop is running and only
once per iteration through the event loop.
History:
Prior to December 9, 2020, a timer pulse set too high with a handler too
slow could lock up the event loop. It now guarantees other things will
get a chance to run between timer calls, even if that means not keeping up
with the requested interval.
*/
version(with_timer) {
class Timer {
// FIXME: needs pause and unpause
// FIXME: I might add overloads for ones that take a count of
// how many elapsed since last time (on Windows, it will divide
// the ticks thing given, on Linux it is just available) and
// maybe one that takes an instance of the Timer itself too
/// Create a timer with a callback when it triggers.
this(int intervalInMilliseconds, void delegate() onPulse) {
assert(onPulse !is null);
this.intervalInMilliseconds = intervalInMilliseconds;
this.onPulse = onPulse;
version(Windows) {
/*
handle = SetTimer(null, handle, intervalInMilliseconds, &timerCallback);
if(handle == 0)
throw new Exception("SetTimer fail");
*/
// thanks to Archival 998 for the WaitableTimer blocks
handle = CreateWaitableTimer(null, false, null);
long initialTime = -intervalInMilliseconds;
if(handle is null || !SetWaitableTimer(handle, cast(LARGE_INTEGER*)&initialTime, intervalInMilliseconds, &timerCallback, handle, false))
throw new Exception("SetWaitableTimer Failed");
mapping[handle] = this;
} else version(linux) {
static import ep = core.sys.linux.epoll;
import core.sys.linux.timerfd;
fd = timerfd_create(CLOCK_MONOTONIC, 0);
if(fd == -1)
throw new Exception("timer create failed");
mapping[fd] = this;
itimerspec value;
value.it_value.tv_sec = cast(int) (intervalInMilliseconds / 1000);
value.it_value.tv_nsec = (intervalInMilliseconds % 1000) * 1000_000;
value.it_interval.tv_sec = cast(int) (intervalInMilliseconds / 1000);
value.it_interval.tv_nsec = (intervalInMilliseconds % 1000) * 1000_000;
if(timerfd_settime(fd, 0, &value, null) == -1)
throw new Exception("couldn't make pulse timer");
version(with_eventloop) {
import arsd.eventloop;
addFileEventListeners(fd, &trigger, null, null);
} else {
prepareEventLoop();
ep.epoll_event ev = void;
ev.events = ep.EPOLLIN;
ev.data.fd = fd;
ep.epoll_ctl(epollFd, ep.EPOLL_CTL_ADD, fd, &ev);
}
} else featureNotImplemented();
}
private int intervalInMilliseconds;
// just cuz I sometimes call it this.
alias dispose = destroy;
/// Stop and destroy the timer object.
void destroy() {
version(Windows) {
staticDestroy(handle);
handle = null;
} else version(linux) {
staticDestroy(fd);
fd = -1;
} else featureNotImplemented();
}
version(Windows)
static void staticDestroy(HANDLE handle) {
if(handle) {
// KillTimer(null, handle);
CancelWaitableTimer(cast(void*)handle);
mapping.remove(handle);
CloseHandle(handle);
}
}
else version(linux)
static void staticDestroy(int fd) {
if(fd != -1) {
import unix = core.sys.posix.unistd;
static import ep = core.sys.linux.epoll;
version(with_eventloop) {
import arsd.eventloop;
removeFileEventListeners(fd);
} else {
ep.epoll_event ev = void;
ev.events = ep.EPOLLIN;
ev.data.fd = fd;
ep.epoll_ctl(epollFd, ep.EPOLL_CTL_DEL, fd, &ev);
}
unix.close(fd);
mapping.remove(fd);
}
}
~this() {
version(Windows) { if(handle)
cleanupQueue.queue!staticDestroy(handle);
} else version(linux) { if(fd != -1)
cleanupQueue.queue!staticDestroy(fd);
}
}
void changeTime(int intervalInMilliseconds)
{
this.intervalInMilliseconds = intervalInMilliseconds;
version(Windows)
{
if(handle)
{
//handle = SetTimer(null, handle, intervalInMilliseconds, &timerCallback);
long initialTime = -intervalInMilliseconds;
if(handle is null || !SetWaitableTimer(handle, cast(LARGE_INTEGER*)&initialTime, intervalInMilliseconds, &timerCallback, handle, false))
throw new Exception("couldn't change pulse timer");
}
}
}
private:
void delegate() onPulse;
int lastEventLoopRoundTriggered;
void trigger() {
version(linux) {
import unix = core.sys.posix.unistd;
long val;
unix.read(fd, &val, val.sizeof); // gotta clear the pipe
} else version(Windows) {
if(this.lastEventLoopRoundTriggered == eventLoopRound)
return; // never try to actually run faster than the event loop
lastEventLoopRoundTriggered = eventLoopRound;
} else featureNotImplemented();
onPulse();
}
version(Windows)
void rearm() {
}
version(Windows)
extern(Windows)
//static void timerCallback(HWND, UINT, UINT_PTR timer, DWORD dwTime) nothrow {
static void timerCallback(HANDLE timer, DWORD lowTime, DWORD hiTime) nothrow {
if(Timer* t = timer in mapping) {
try
(*t).trigger();
catch(Exception e) { sdpy_abort(e); assert(0); }
}
}
version(Windows) {
//UINT_PTR handle;
//static Timer[UINT_PTR] mapping;
HANDLE handle;
__gshared Timer[HANDLE] mapping;
} else version(linux) {
int fd = -1;
__gshared Timer[int] mapping;
} else static assert(0, "timer not supported");
}
}
version(Windows)
private int eventLoopRound;
version(Windows)
/// Lets you add HANDLEs to the event loop. Not meant to be used for async I/O per se, but for other handles (it can only handle a few handles at a time.) Only works on certain types of handles! See: https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-msgwaitformultipleobjectsex
class WindowsHandleReader {
///
this(void delegate() onReady, HANDLE handle) {
this.onReady = onReady;
this.handle = handle;
mapping[handle] = this;
enable();
}
///
void enable() {
auto el = EventLoop.get().impl;
el.handles ~= handle;
}
///
void disable() {
auto el = EventLoop.get().impl;
for(int i = 0; i < el.handles.length; i++) {
if(el.handles[i] is handle) {
el.handles[i] = el.handles[$-1];
el.handles = el.handles[0 .. $-1];
return;
}
}
}
void dispose() {
disable();
if(handle)
mapping.remove(handle);
handle = null;
}
void ready() {
if(onReady)
onReady();
}
HANDLE handle;
void delegate() onReady;
__gshared WindowsHandleReader[HANDLE] mapping;
}
version(Posix)
/// Lets you add files to the event loop for reading. Use at your own risk.
class PosixFdReader {
///
this(void delegate() onReady, int fd, bool captureReads = true, bool captureWrites = false) {
this((int, bool, bool) { onReady(); }, fd, captureReads, captureWrites);
}
///
this(void delegate(int) onReady, int fd, bool captureReads = true, bool captureWrites = false) {
this((int fd, bool, bool) { onReady(fd); }, fd, captureReads, captureWrites);
}
///
this(void delegate(int fd, bool read, bool write) onReady, int fd, bool captureReads = true, bool captureWrites = false) {
this.onReady = onReady;
this.fd = fd;
this.captureWrites = captureWrites;
this.captureReads = captureReads;
mapping[fd] = this;
version(with_eventloop) {
import arsd.eventloop;
addFileEventListeners(fd, &readyel);
} else {
enable();
}
}
bool captureReads;
bool captureWrites;
version(with_eventloop) {} else
///
void enable() {
prepareEventLoop();
enabled = true;
version(linux) {
static import ep = core.sys.linux.epoll;
ep.epoll_event ev = void;
ev.events = (captureReads ? ep.EPOLLIN : 0) | (captureWrites ? ep.EPOLLOUT : 0);
//import std.stdio; writeln("enable ", fd, " ", captureReads, " ", captureWrites);
ev.data.fd = fd;
ep.epoll_ctl(epollFd, ep.EPOLL_CTL_ADD, fd, &ev);
} else {
}
}
version(with_eventloop) {} else
///
void disable() {
prepareEventLoop();
enabled = false;
version(linux) {
static import ep = core.sys.linux.epoll;
ep.epoll_event ev = void;
ev.events = (captureReads ? ep.EPOLLIN : 0) | (captureWrites ? ep.EPOLLOUT : 0);
//import std.stdio; writeln("disable ", fd, " ", captureReads, " ", captureWrites);
ev.data.fd = fd;
ep.epoll_ctl(epollFd, ep.EPOLL_CTL_DEL, fd, &ev);
}
}
version(with_eventloop) {} else
///
void dispose() {
if(enabled)
disable();
if(fd != -1)
mapping.remove(fd);
fd = -1;
}
void delegate(int, bool, bool) onReady;
version(with_eventloop)
void readyel() {
onReady(fd, true, true);
}
void ready(uint flags) {
version(linux) {
static import ep = core.sys.linux.epoll;
onReady(fd, (flags & ep.EPOLLIN) ? true : false, (flags & ep.EPOLLOUT) ? true : false);
} else {
import core.sys.posix.poll;
onReady(fd, (flags & POLLIN) ? true : false, (flags & POLLOUT) ? true : false);
}
}
void hup(uint flags) {
if(onHup)
onHup();
}
void delegate() onHup;
int fd = -1;
private bool enabled;
__gshared PosixFdReader[int] mapping;
}
// basic functions to access the clipboard
/+
http://msdn.microsoft.com/en-us/library/windows/desktop/ff729168%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms649039%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms649035%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms649051%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms649037%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms649035%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms649016%28v=vs.85%29.aspx
+/
/++
this does a delegate because it is actually an async call on X...
the receiver may never be called if the clipboard is empty or unavailable
gets plain text from the clipboard.
+/
void getClipboardText(SimpleWindow clipboardOwner, void delegate(in char[]) receiver) {
version(Windows) {
HWND hwndOwner = clipboardOwner ? clipboardOwner.impl.hwnd : null;
if(OpenClipboard(hwndOwner) == 0)
throw new Exception("OpenClipboard");
scope(exit)
CloseClipboard();
// see: https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getpriorityclipboardformat
if(auto dataHandle = GetClipboardData(CF_UNICODETEXT)) {
if(auto data = cast(wchar*) GlobalLock(dataHandle)) {
scope(exit)
GlobalUnlock(dataHandle);
// FIXME: CR/LF conversions
// FIXME: I might not have to copy it now that the receiver is in char[] instead of string
int len = 0;
auto d = data;
while(*d) {
d++;
len++;
}
string s;
s.reserve(len);
foreach(dchar ch; data[0 .. len]) {
s ~= ch;
}
receiver(s);
}
}
} else version(X11) {
getX11Selection!"CLIPBOARD"(clipboardOwner, receiver);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
// FIXME: a clipboard listener might be cool btw
/++
this does a delegate because it is actually an async call on X...
the receiver may never be called if the clipboard is empty or unavailable
gets image from the clipboard.
templated because it introduces an optional dependency on arsd.bmp
+/
void getClipboardImage()(SimpleWindow clipboardOwner, void delegate(MemoryImage) receiver) {
version(Windows) {
HWND hwndOwner = clipboardOwner ? clipboardOwner.impl.hwnd : null;
if(OpenClipboard(hwndOwner) == 0)
throw new Exception("OpenClipboard");
scope(exit)
CloseClipboard();
if(auto dataHandle = GetClipboardData(CF_DIBV5)) {
if(auto data = cast(ubyte*) GlobalLock(dataHandle)) {
scope(exit)
GlobalUnlock(dataHandle);
auto len = GlobalSize(dataHandle);
import arsd.bmp;
auto img = readBmp(data[0 .. len], false);
receiver(img);
}
}
} else version(X11) {
getX11Selection!"CLIPBOARD"(clipboardOwner, receiver);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
version(Windows)
struct WCharzBuffer {
wchar[] buffer;
wchar[256] staticBuffer = void;
size_t length() {
return buffer.length;
}
wchar* ptr() {
return buffer.ptr;
}
wchar[] slice() {
return buffer;
}
void copyInto(R)(ref R r) {
static if(is(R == wchar[N], size_t N)) {
r[0 .. this.length] = slice[];
r[this.length] = 0;
} else static assert(0, "can only copy into wchar[n], not " ~ R.stringof);
}
/++
conversionFlags = [WindowsStringConversionFlags]
+/
this(in char[] data, int conversionFlags = 0) {
conversionFlags |= WindowsStringConversionFlags.zeroTerminate; // this ALWAYS zero terminates cuz of its name
auto sz = sizeOfConvertedWstring(data, conversionFlags);
if(sz > staticBuffer.length)
buffer = new wchar[](sz);
else
buffer = staticBuffer[];
buffer = makeWindowsString(data, buffer, conversionFlags);
}
}
version(Windows)
int sizeOfConvertedWstring(in char[] s, int conversionFlags) {
int size = 0;
if(conversionFlags & WindowsStringConversionFlags.convertNewLines) {
// need to convert line endings, which means the length will get bigger.
// BTW I betcha this could be faster with some simd stuff.
char last;
foreach(char ch; s) {
if(ch == 10 && last != 13)
size++; // will add a 13 before it...
size++;
last = ch;
}
} else {
// no conversion necessary, just estimate based on length
/*
I don't think there's any string with a longer length
in code units when encoded in UTF-16 than it has in UTF-8.
This will probably over allocate, but that's OK.
*/
size = cast(int) s.length;
}
if(conversionFlags & WindowsStringConversionFlags.zeroTerminate)
size++;
return size;
}
version(Windows)
enum WindowsStringConversionFlags : int {
zeroTerminate = 1,
convertNewLines = 2,
}
version(Windows)
class WindowsApiException : Exception {
char[256] buffer;
this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null) {
assert(msg.length < 100);
auto error = GetLastError();
buffer[0 .. msg.length] = msg;
buffer[msg.length] = ' ';
int pos = cast(int) msg.length + 1;
if(error == 0)
buffer[pos++] = '0';
else {
auto ec = error;
auto init = pos;
while(ec) {
buffer[pos++] = (ec % 10) + '0';
ec /= 10;
}
buffer[pos++] = ' ';
size_t size = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, null, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), &(buffer[pos]), cast(DWORD) buffer.length - pos, null);
pos += size;
}
super(cast(string) buffer[0 .. pos], file, line, next);
}
}
class ErrnoApiException : Exception {
char[256] buffer;
this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null) {
assert(msg.length < 100);
import core.stdc.errno;
auto error = errno;
buffer[0 .. msg.length] = msg;
buffer[msg.length] = ' ';
int pos = cast(int) msg.length + 1;
if(error == 0)
buffer[pos++] = '0';
else {
auto init = pos;
while(error) {
buffer[pos++] = (error % 10) + '0';
error /= 10;
}
for(int i = 0; i < (pos - init) / 2; i++) {
char c = buffer[i + init];
buffer[i + init] = buffer[pos - (i + init) - 1];
buffer[pos - (i + init) - 1] = c;
}
}
super(cast(string) buffer[0 .. pos], file, line, next);
}
}
version(Windows)
wchar[] makeWindowsString(in char[] str, wchar[] buffer, int conversionFlags = WindowsStringConversionFlags.zeroTerminate) {
if(str.length == 0)
return null;
int pos = 0;
dchar last;
foreach(dchar c; str) {
if(c <= 0xFFFF) {
if((conversionFlags & WindowsStringConversionFlags.convertNewLines) && c == 10 && last != 13)
buffer[pos++] = 13;
buffer[pos++] = cast(wchar) c;
} else if(c <= 0x10FFFF) {
buffer[pos++] = cast(wchar)((((c - 0x10000) >> 10) & 0x3FF) + 0xD800);
buffer[pos++] = cast(wchar)(((c - 0x10000) & 0x3FF) + 0xDC00);
}
last = c;
}
if(conversionFlags & WindowsStringConversionFlags.zeroTerminate) {
buffer[pos] = 0;
}
return buffer[0 .. pos];
}
version(Windows)
char[] makeUtf8StringFromWindowsString(in wchar[] str, char[] buffer) {
if(str.length == 0)
return null;
auto got = WideCharToMultiByte(CP_UTF8, 0, str.ptr, cast(int) str.length, buffer.ptr, cast(int) buffer.length, null, null);
if(got == 0) {
if(GetLastError() == ERROR_INSUFFICIENT_BUFFER)
throw new Exception("not enough buffer");
else
throw new Exception("conversion"); // FIXME: GetLastError
}
return buffer[0 .. got];
}
version(Windows)
string makeUtf8StringFromWindowsString(in wchar[] str) {
char[] buffer;
auto got = WideCharToMultiByte(CP_UTF8, 0, str.ptr, cast(int) str.length, null, 0, null, null);
buffer.length = got;
// it is unique because we just allocated it above!
return cast(string) makeUtf8StringFromWindowsString(str, buffer);
}
version(Windows)
string makeUtf8StringFromWindowsString(wchar* str) {
char[] buffer;
auto got = WideCharToMultiByte(CP_UTF8, 0, str, -1, null, 0, null, null);
buffer.length = got;
got = WideCharToMultiByte(CP_UTF8, 0, str, -1, buffer.ptr, cast(int) buffer.length, null, null);
if(got == 0) {
if(GetLastError() == ERROR_INSUFFICIENT_BUFFER)
throw new Exception("not enough buffer");
else
throw new Exception("conversion"); // FIXME: GetLastError
}
return cast(string) buffer[0 .. got];
}
int findIndexOfZero(in wchar[] str) {
foreach(idx, wchar ch; str)
if(ch == 0)
return cast(int) idx;
return cast(int) str.length;
}
int findIndexOfZero(in char[] str) {
foreach(idx, char ch; str)
if(ch == 0)
return cast(int) idx;
return cast(int) str.length;
}
/// Copies some text to the clipboard.
void setClipboardText(SimpleWindow clipboardOwner, string text) {
assert(clipboardOwner !is null);
version(Windows) {
if(OpenClipboard(clipboardOwner.impl.hwnd) == 0)
throw new Exception("OpenClipboard");
scope(exit)
CloseClipboard();
EmptyClipboard();
auto sz = sizeOfConvertedWstring(text, WindowsStringConversionFlags.convertNewLines | WindowsStringConversionFlags.zeroTerminate);
auto handle = GlobalAlloc(GMEM_MOVEABLE, sz * 2); // zero terminated wchars
if(handle is null) throw new Exception("GlobalAlloc");
if(auto data = cast(wchar*) GlobalLock(handle)) {
auto slice = data[0 .. sz];
scope(failure)
GlobalUnlock(handle);
auto str = makeWindowsString(text, slice, WindowsStringConversionFlags.convertNewLines | WindowsStringConversionFlags.zeroTerminate);
GlobalUnlock(handle);
SetClipboardData(CF_UNICODETEXT, handle);
}
} else version(X11) {
setX11Selection!"CLIPBOARD"(clipboardOwner, text);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
void setClipboardImage()(SimpleWindow clipboardOwner, MemoryImage img) {
assert(clipboardOwner !is null);
version(Windows) {
if(OpenClipboard(clipboardOwner.impl.hwnd) == 0)
throw new Exception("OpenClipboard");
scope(exit)
CloseClipboard();
EmptyClipboard();
import arsd.bmp;
ubyte[] mdata;
mdata.reserve(img.width * img.height);
void sink(ubyte b) {
mdata ~= b;
}
writeBmpIndirect(img, &sink, false);
auto handle = GlobalAlloc(GMEM_MOVEABLE, mdata.length);
if(handle is null) throw new Exception("GlobalAlloc");
if(auto data = cast(ubyte*) GlobalLock(handle)) {
auto slice = data[0 .. mdata.length];
scope(failure)
GlobalUnlock(handle);
slice[] = mdata[];
GlobalUnlock(handle);
SetClipboardData(CF_DIB, handle);
}
} else version(X11) {
static class X11SetSelectionHandler_Image : X11SetSelectionHandler {
mixin X11SetSelectionHandler_Basics;
private const(ubyte)[] mdata;
private const(ubyte)[] mdata_original;
this(MemoryImage img) {
import arsd.bmp;
mdata.reserve(img.width * img.height);
void sink(ubyte b) {
mdata ~= b;
}
writeBmpIndirect(img, &sink, true);
mdata_original = mdata;
}
Atom[] availableFormats() {
auto display = XDisplayConnection.get;
return [
GetAtom!"image/bmp"(display),
GetAtom!"TARGETS"(display)
];
}
ubyte[] getData(Atom format, return scope ubyte[] data) {
if(mdata.length < data.length) {
data[0 .. mdata.length] = mdata[];
auto ret = data[0 .. mdata.length];
mdata = mdata[$..$];
return ret;
} else {
data[] = mdata[0 .. data.length];
mdata = mdata[data.length .. $];
return data[];
}
}
void done() {
mdata = mdata_original;
}
}
setX11Selection!"CLIPBOARD"(clipboardOwner, new X11SetSelectionHandler_Image(img));
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
version(X11) {
// and the PRIMARY on X, be sure to put these in static if(UsingSimpledisplayX11)
private Atom*[] interredAtoms; // for discardAndRecreate
// FIXME: do a GetAtomUpfront too that just queues all at CT and combines it all.
/// Platform-specific for X11.
/// History: On February 21, 2021, I changed the default value of `create` to be true.
@property Atom GetAtom(string name, bool create = true)(Display* display) {
static Atom a;
if(!a) {
a = XInternAtom(display, name, !create);
interredAtoms ~= &a;
}
if(a == None)
throw new Exception("XInternAtom " ~ name ~ " " ~ (create ? "true":"false"));
return a;
}
/// Platform-specific for X11 - gets atom names as a string.
string getAtomName(Atom atom, Display* display) {
auto got = XGetAtomName(display, atom);
scope(exit) XFree(got);
import core.stdc.string;
string s = got[0 .. strlen(got)].idup;
return s;
}
/// Asserts ownership of PRIMARY and copies the text into a buffer that clients can request later.
void setPrimarySelection(SimpleWindow window, string text) {
setX11Selection!"PRIMARY"(window, text);
}
/// Asserts ownership of SECONDARY and copies the text into a buffer that clients can request later.
void setSecondarySelection(SimpleWindow window, string text) {
setX11Selection!"SECONDARY"(window, text);
}
interface X11SetSelectionHandler {
// should include TARGETS right now
Atom[] availableFormats();
// Return the slice of data you filled, empty slice if done.
// this is to support the incremental thing
ubyte[] getData(Atom format, return scope ubyte[] data);
void done();
void handleRequest(XEvent);
bool matchesIncr(Window, Atom);
void sendMoreIncr(XPropertyEvent*);
}
mixin template X11SetSelectionHandler_Basics() {
Window incrWindow;
Atom incrAtom;
Atom selectionAtom;
Atom formatAtom;
ubyte[] toSend;
bool matchesIncr(Window w, Atom a) {
return incrAtom && incrAtom == a && w == incrWindow;
}
void sendMoreIncr(XPropertyEvent* event) {
auto display = XDisplayConnection.get;
XChangeProperty (display,
incrWindow,
incrAtom,
formatAtom,
8 /* bits */, PropModeReplace,
toSend.ptr, cast(int) toSend.length);
if(toSend.length != 0) {
toSend = this.getData(formatAtom, toSend[]);
} else {
this.done();
incrWindow = None;
incrAtom = None;
selectionAtom = None;
formatAtom = None;
toSend = null;
}
}
void handleRequest(XEvent ev) {
auto display = XDisplayConnection.get;
XSelectionRequestEvent* event = &ev.xselectionrequest;
XSelectionEvent selectionEvent;
selectionEvent.type = EventType.SelectionNotify;
selectionEvent.display = event.display;
selectionEvent.requestor = event.requestor;
selectionEvent.selection = event.selection;
selectionEvent.time = event.time;
selectionEvent.target = event.target;
bool supportedType() {
foreach(t; this.availableFormats())
if(t == event.target)
return true;
return false;
}
if(event.property == None) {
selectionEvent.property = event.target;
XSendEvent(display, selectionEvent.requestor, false, 0, cast(XEvent*) &selectionEvent);
XFlush(display);
} if(event.target == GetAtom!"TARGETS"(display)) {
/* respond with the supported types */
auto tlist = this.availableFormats();
XChangeProperty(display, event.requestor, event.property, XA_ATOM, 32, PropModeReplace, cast(void*)tlist.ptr, cast(int) tlist.length);
selectionEvent.property = event.property;
XSendEvent(display, selectionEvent.requestor, false, 0, cast(XEvent*) &selectionEvent);
XFlush(display);
} else if(supportedType()) {
auto buffer = new ubyte[](1024 * 64);
auto toSend = this.getData(event.target, buffer[]);
if(toSend.length < 32 * 1024) {
// small enough to send directly...
selectionEvent.property = event.property;
XChangeProperty (display,
selectionEvent.requestor,
selectionEvent.property,
event.target,
8 /* bits */, 0 /* PropModeReplace */,
toSend.ptr, cast(int) toSend.length);
XSendEvent(display, selectionEvent.requestor, false, 0, cast(XEvent*) &selectionEvent);
XFlush(display);
} else {
// large, let's send incrementally
arch_ulong l = toSend.length;
// if I wanted other events from this window don't want to clear that out....
XWindowAttributes xwa;
XGetWindowAttributes(display, selectionEvent.requestor, &xwa);
XSelectInput(display, selectionEvent.requestor, cast(EventMask) (xwa.your_event_mask | EventMask.PropertyChangeMask));
incrWindow = event.requestor;
incrAtom = event.property;
formatAtom = event.target;
selectionAtom = event.selection;
this.toSend = toSend;
selectionEvent.property = event.property;
XChangeProperty (display,
selectionEvent.requestor,
selectionEvent.property,
GetAtom!"INCR"(display),
32 /* bits */, PropModeReplace,
&l, 1);
XSendEvent(display, selectionEvent.requestor, false, 0, cast(XEvent*) &selectionEvent);
XFlush(display);
}
//if(after)
//after();
} else {
debug(sdpy_clip) {
import std.stdio; writeln("Unsupported data ", getAtomName(event.target, display));
}
selectionEvent.property = None; // I don't know how to handle this type...
XSendEvent(display, selectionEvent.requestor, false, EventMask.NoEventMask, cast(XEvent*) &selectionEvent);
XFlush(display);
}
}
}
class X11SetSelectionHandler_Text : X11SetSelectionHandler {
mixin X11SetSelectionHandler_Basics;
private const(ubyte)[] text;
private const(ubyte)[] text_original;
this(string text) {
this.text = cast(const ubyte[]) text;
this.text_original = this.text;
}
Atom[] availableFormats() {
auto display = XDisplayConnection.get;
return [
GetAtom!"UTF8_STRING"(display),
GetAtom!"text/plain"(display),
XA_STRING,
GetAtom!"TARGETS"(display)
];
}
ubyte[] getData(Atom format, return scope ubyte[] data) {
if(text.length < data.length) {
data[0 .. text.length] = text[];
return data[0 .. text.length];
} else {
data[] = text[0 .. data.length];
text = text[data.length .. $];
return data[];
}
}
void done() {
text = text_original;
}
}
/// The `after` delegate is called after a client requests the UTF8_STRING thing. it is a mega-hack right now! (note to self july 2020... why did i do that?!)
void setX11Selection(string atomName)(SimpleWindow window, string text, void delegate() after = null) {
setX11Selection!atomName(window, new X11SetSelectionHandler_Text(text), after);
}
void setX11Selection(string atomName)(SimpleWindow window, X11SetSelectionHandler data, void delegate() after = null) {
assert(window !is null);
auto display = XDisplayConnection.get();
static if (atomName == "PRIMARY") Atom a = XA_PRIMARY;
else static if (atomName == "SECONDARY") Atom a = XA_SECONDARY;
else Atom a = GetAtom!atomName(display);
XSetSelectionOwner(display, a, window.impl.window, 0 /* CurrentTime */);
window.impl.setSelectionHandlers[a] = data;
}
///
void getPrimarySelection(SimpleWindow window, void delegate(in char[]) handler) {
getX11Selection!"PRIMARY"(window, handler);
}
// added July 28, 2020
// undocumented as experimental tho
interface X11GetSelectionHandler {
void handleData(Atom target, in ubyte[] data);
Atom findBestFormat(Atom[] answer);
void prepareIncremental(Window, Atom);
bool matchesIncr(Window, Atom);
void handleIncrData(Atom, in ubyte[] data);
}
mixin template X11GetSelectionHandler_Basics() {
Window incrWindow;
Atom incrAtom;
void prepareIncremental(Window w, Atom a) {
incrWindow = w;
incrAtom = a;
}
bool matchesIncr(Window w, Atom a) {
return incrWindow == w && incrAtom == a;
}
Atom incrFormatAtom;
ubyte[] incrData;
void handleIncrData(Atom format, in ubyte[] data) {
incrFormatAtom = format;
if(data.length)
incrData ~= data;
else
handleData(incrFormatAtom, incrData);
}
}
///
void getX11Selection(string atomName)(SimpleWindow window, void delegate(in char[]) handler, Time timestamp = 0 /* CurrentTime */) {
assert(window !is null);
auto display = XDisplayConnection.get();
auto atom = GetAtom!atomName(display);
static class X11GetSelectionHandler_Text : X11GetSelectionHandler {
this(void delegate(in char[]) handler) {
this.handler = handler;
}
mixin X11GetSelectionHandler_Basics;
void delegate(in char[]) handler;
void handleData(Atom target, in ubyte[] data) {
if(target == GetAtom!"UTF8_STRING"(XDisplayConnection.get) || target == XA_STRING || target == GetAtom!"text/plain"(XDisplayConnection.get))
handler(cast(const char[]) data);
}
Atom findBestFormat(Atom[] answer) {
Atom best = None;
foreach(option; answer) {
if(option == GetAtom!"UTF8_STRING"(XDisplayConnection.get)) {
best = option;
break;
} else if(option == XA_STRING) {
best = option;
} else if(option == GetAtom!"text/plain"(XDisplayConnection.get)) {
best = option;
}
}
return best;
}
}
window.impl.getSelectionHandlers[atom] = new X11GetSelectionHandler_Text(handler);
auto target = GetAtom!"TARGETS"(display);
// SDD_DATA is "simpledisplay.d data"
XConvertSelection(display, atom, target, GetAtom!("SDD_DATA", true)(display), window.impl.window, timestamp);
}
/// Gets the image on the clipboard, if there is one. Added July 2020.
void getX11Selection(string atomName)(SimpleWindow window, void delegate(MemoryImage) handler) {
assert(window !is null);
auto display = XDisplayConnection.get();
auto atom = GetAtom!atomName(display);
static class X11GetSelectionHandler_Image : X11GetSelectionHandler {
this(void delegate(MemoryImage) handler) {
this.handler = handler;
}
mixin X11GetSelectionHandler_Basics;
void delegate(MemoryImage) handler;
void handleData(Atom target, in ubyte[] data) {
if(target == GetAtom!"image/bmp"(XDisplayConnection.get)) {
import arsd.bmp;
handler(readBmp(data));
}
}
Atom findBestFormat(Atom[] answer) {
Atom best = None;
foreach(option; answer) {
if(option == GetAtom!"image/bmp"(XDisplayConnection.get)) {
best = option;
}
}
return best;
}
}
window.impl.getSelectionHandlers[atom] = new X11GetSelectionHandler_Image(handler);
auto target = GetAtom!"TARGETS"(display);
// SDD_DATA is "simpledisplay.d data"
XConvertSelection(display, atom, target, GetAtom!("SDD_DATA", true)(display), window.impl.window, 0 /*CurrentTime*/);
}
///
void[] getX11PropertyData(Window window, Atom property, Atom type = AnyPropertyType) {
Atom actualType;
int actualFormat;
arch_ulong actualItems;
arch_ulong bytesRemaining;
void* data;
auto display = XDisplayConnection.get();
if(XGetWindowProperty(display, window, property, 0, 0x7fffffff, false, type, &actualType, &actualFormat, &actualItems, &bytesRemaining, &data) == Success) {
if(actualFormat == 0)
return null;
else {
int byteLength;
if(actualFormat == 32) {
// 32 means it is a C long... which is variable length
actualFormat = cast(int) arch_long.sizeof * 8;
}
// then it is just a bit count
byteLength = cast(int) (actualItems * actualFormat / 8);
auto d = new ubyte[](byteLength);
d[] = cast(ubyte[]) data[0 .. byteLength];
XFree(data);
return d;
}
}
return null;
}
/* defined in the systray spec */
enum SYSTEM_TRAY_REQUEST_DOCK = 0;
enum SYSTEM_TRAY_BEGIN_MESSAGE = 1;
enum SYSTEM_TRAY_CANCEL_MESSAGE = 2;
/** Global hotkey handler. Simpledisplay will usually create one for you, but if you want to use subclassing
* instead of delegates, you can subclass this, and override `doHandle()` method. */
public class GlobalHotkey {
KeyEvent key;
void delegate () handler;
void doHandle () { if (handler !is null) handler(); } /// this will be called by hotkey manager
/// Create from initialzed KeyEvent object
this (KeyEvent akey, void delegate () ahandler=null) {
if (akey.key == 0 || !GlobalHotkeyManager.isGoodModifierMask(akey.modifierState)) throw new Exception("invalid global hotkey");
key = akey;
handler = ahandler;
}
/// Create from emacs-like key name ("C-M-Y", etc.)
this (const(char)[] akey, void delegate () ahandler=null) {
key = KeyEvent.parse(akey);
if (key.key == 0 || !GlobalHotkeyManager.isGoodModifierMask(key.modifierState)) throw new Exception("invalid global hotkey");
handler = ahandler;
}
}
private extern(C) int XGrabErrorHandler (Display* dpy, XErrorEvent* evt) nothrow @nogc {
//conwriteln("failed to grab key");
GlobalHotkeyManager.ghfailed = true;
return 0;
}
private extern(C) int XShmErrorHandler (Display* dpy, XErrorEvent* evt) nothrow @nogc {
Image.impl.xshmfailed = true;
return 0;
}
private __gshared int errorHappened;
private extern(C) int adrlogger (Display* dpy, XErrorEvent* evt) nothrow @nogc {
import core.stdc.stdio;
char[265] buffer;
XGetErrorText(dpy, evt.error_code, buffer.ptr, cast(int) buffer.length);
debug printf("X Error %d: %s / Serial: %lld, Opcode: %d.%d, XID: 0x%llx\n", evt.error_code, buffer.ptr, evt.serial, evt.request_code, evt.minor_code, evt.resourceid);
errorHappened = true;
return 0;
}
/++
Global hotkey manager. It contains static methods to manage global hotkeys.
---
try {
GlobalHotkeyManager.register("M-H-A", delegate () { hideShowWindows(); });
} catch (Exception e) {
conwriteln("ERROR registering hotkey!");
}
EventLoop.get.run();
---
The key strings are based on Emacs. In practical terms,
`M` means `alt` and `H` means the Windows logo key. `C`
is `ctrl`.
$(WARNING
This is X-specific right now. If you are on
Windows, try [registerHotKey] instead.
We will probably merge these into a single
interface later.
)
+/
public class GlobalHotkeyManager : CapableOfHandlingNativeEvent {
version(X11) {
void recreateAfterDisconnect() {
throw new Exception("NOT IMPLEMENTED");
}
void discardConnectionState() {
throw new Exception("NOT IMPLEMENTED");
}
}
private static immutable uint[8] masklist = [ 0,
KeyOrButtonMask.LockMask,
KeyOrButtonMask.Mod2Mask,
KeyOrButtonMask.Mod3Mask,
KeyOrButtonMask.LockMask|KeyOrButtonMask.Mod2Mask,
KeyOrButtonMask.LockMask|KeyOrButtonMask.Mod3Mask,
KeyOrButtonMask.LockMask|KeyOrButtonMask.Mod2Mask|KeyOrButtonMask.Mod3Mask,
KeyOrButtonMask.Mod2Mask|KeyOrButtonMask.Mod3Mask,
];
private __gshared GlobalHotkeyManager ghmanager;
private __gshared bool ghfailed = false;
private static bool isGoodModifierMask (uint modmask) pure nothrow @safe @nogc {
if (modmask == 0) return false;
if (modmask&(KeyOrButtonMask.LockMask|KeyOrButtonMask.Mod2Mask|KeyOrButtonMask.Mod3Mask)) return false;
if (modmask&~(KeyOrButtonMask.Mod5Mask-1)) return false;
return true;
}
private static uint cleanupModifiers (uint modmask) pure nothrow @safe @nogc {
modmask &= ~(KeyOrButtonMask.LockMask|KeyOrButtonMask.Mod2Mask|KeyOrButtonMask.Mod3Mask); // remove caps, num, scroll
modmask &= (KeyOrButtonMask.Mod5Mask-1); // and other modifiers
return modmask;
}
private static uint keyEvent2KeyCode() (scope auto ref const KeyEvent ke) {
uint keycode = cast(uint)ke.key;
auto dpy = XDisplayConnection.get;
return XKeysymToKeycode(dpy, keycode);
}
private static ulong keyCode2Hash() (uint keycode, uint modstate) pure nothrow @safe @nogc { return ((cast(ulong)modstate)<<32)|keycode; }
private __gshared GlobalHotkey[ulong] globalHotkeyList;
NativeEventHandler getNativeEventHandler () {
return delegate int (XEvent e) {
if (e.type != EventType.KeyPress) return 1;
auto kev = cast(const(XKeyEvent)*)&e;
auto hash = keyCode2Hash(e.xkey.keycode, cleanupModifiers(e.xkey.state));
if (auto ghkp = hash in globalHotkeyList) {
try {
ghkp.doHandle();
} catch (Exception e) {
import core.stdc.stdio : stderr, fprintf;
stderr.fprintf("HOTKEY HANDLER EXCEPTION: %.*s", cast(uint)e.msg.length, e.msg.ptr);
}
}
return 1;
};
}
private this () {
auto dpy = XDisplayConnection.get;
auto root = RootWindow(dpy, DefaultScreen(dpy));
CapableOfHandlingNativeEvent.nativeHandleMapping[root] = this;
XDisplayConnection.addRootInput(EventMask.KeyPressMask);
}
/// Register new global hotkey with initialized `GlobalHotkey` object.
/// This function will throw if it failed to register hotkey (i.e. hotkey is invalid or already taken).
static void register (GlobalHotkey gh) {
if (gh is null) return;
if (gh.key.key == 0 || !isGoodModifierMask(gh.key.modifierState)) throw new Exception("invalid global hotkey");
auto dpy = XDisplayConnection.get;
immutable keycode = keyEvent2KeyCode(gh.key);
auto hash = keyCode2Hash(keycode, gh.key.modifierState);
if (hash in globalHotkeyList) throw new Exception("duplicate global hotkey");
if (ghmanager is null) ghmanager = new GlobalHotkeyManager();
XSync(dpy, 0/*False*/);
Window root = RootWindow(dpy, DefaultScreen(dpy));
XErrorHandler savedErrorHandler = XSetErrorHandler(&XGrabErrorHandler);
ghfailed = false;
foreach (immutable uint ormask; masklist[]) {
XGrabKey(dpy, keycode, gh.key.modifierState|ormask, /*grab_window*/root, /*owner_events*/0/*False*/, GrabMode.GrabModeAsync, GrabMode.GrabModeAsync);
}
XSync(dpy, 0/*False*/);
XSetErrorHandler(savedErrorHandler);
if (ghfailed) {
savedErrorHandler = XSetErrorHandler(&XGrabErrorHandler);
foreach (immutable uint ormask; masklist[]) XUngrabKey(dpy, keycode, gh.key.modifierState|ormask, /*grab_window*/root);
XSync(dpy, 0/*False*/);
XSetErrorHandler(savedErrorHandler);
throw new Exception("cannot register global hotkey");
}
globalHotkeyList[hash] = gh;
}
/// Ditto
static void register (const(char)[] akey, void delegate () ahandler) {
register(new GlobalHotkey(akey, ahandler));
}
private static void removeByHash (ulong hash) {
if (auto ghp = hash in globalHotkeyList) {
auto dpy = XDisplayConnection.get;
immutable keycode = keyEvent2KeyCode(ghp.key);
Window root = RootWindow(dpy, DefaultScreen(dpy));
XSync(dpy, 0/*False*/);
XErrorHandler savedErrorHandler = XSetErrorHandler(&XGrabErrorHandler);
foreach (immutable uint ormask; masklist[]) XUngrabKey(dpy, keycode, ghp.key.modifierState|ormask, /*grab_window*/root);
XSync(dpy, 0/*False*/);
XSetErrorHandler(savedErrorHandler);
globalHotkeyList.remove(hash);
}
}
/// Register new global hotkey with previously used `GlobalHotkey` object.
/// It is safe to unregister unknown or invalid hotkey.
static void unregister (GlobalHotkey gh) {
//TODO: add second AA for faster search? prolly doesn't worth it.
if (gh is null) return;
foreach (const ref kv; globalHotkeyList.byKeyValue) {
if (kv.value is gh) {
removeByHash(kv.key);
return;
}
}
}
/// Ditto.
static void unregister (const(char)[] key) {
auto kev = KeyEvent.parse(key);
immutable keycode = keyEvent2KeyCode(kev);
removeByHash(keyCode2Hash(keycode, kev.modifierState));
}
}
}
version(Windows) {
/++
See [SyntheticInput.sendSyntheticInput] instead for cross-platform applications.
This is platform-specific UTF-16 function for Windows. Sends a string as key press and release events to the actively focused window (not necessarily your application).
+/
void sendSyntheticInput(wstring s) {
INPUT[] inputs;
inputs.reserve(s.length * 2);
foreach(wchar c; s) {
INPUT input;
input.type = INPUT_KEYBOARD;
input.ki.wScan = c;
input.ki.dwFlags = KEYEVENTF_UNICODE;
inputs ~= input;
input.ki.dwFlags |= KEYEVENTF_KEYUP;
inputs ~= input;
}
if(SendInput(cast(int) inputs.length, inputs.ptr, INPUT.sizeof) != inputs.length) {
throw new Exception("SendInput failed");
}
}
// global hotkey helper function
/// Platform-specific for Windows. Registers a global hotkey. Returns a registration ID. See [GlobalHotkeyManager] for Linux. Maybe some day I will merge these.
int registerHotKey(SimpleWindow window, UINT modifiers, UINT vk, void delegate() handler) {
__gshared int hotkeyId = 0;
int id = ++hotkeyId;
if(!RegisterHotKey(window.impl.hwnd, id, modifiers, vk))
throw new Exception("RegisterHotKey failed");
__gshared void delegate()[WPARAM][HWND] handlers;
handlers[window.impl.hwnd][id] = handler;
int delegate(HWND, UINT, WPARAM, LPARAM, out int) oldHandler;
auto nativeEventHandler = delegate int(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam, out int mustReturn) {
switch(msg) {
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms646279%28v=vs.85%29.aspx
case WM_HOTKEY:
if(auto list = hwnd in handlers) {
if(auto h = wParam in *list) {
(*h)();
return 0;
}
}
goto default;
default:
}
if(oldHandler)
return oldHandler(hwnd, msg, wParam, lParam, mustReturn);
return 1; // pass it on
};
if(window.handleNativeEvent.funcptr !is nativeEventHandler.funcptr) {
oldHandler = window.handleNativeEvent;
window.handleNativeEvent = nativeEventHandler;
}
return id;
}
/// Platform-specific for Windows. Unregisters a key. The id is the value returned by [registerHotKey].
void unregisterHotKey(SimpleWindow window, int id) {
if(!UnregisterHotKey(window.impl.hwnd, id))
throw new Exception("UnregisterHotKey");
}
}
version (X11) {
pragma(lib, "dl");
import core.sys.posix.dlfcn;
}
/++
Allows for sending synthetic input to the X server via the Xtst
extension or on Windows using SendInput.
Please remember user input is meant to be user - don't use this
if you have some other alternative!
History:
Added May 17, 2020 with the X implementation.
Added unified implementation for Windows on April 3, 2022. (Prior to that, you had to use the top-level [sendSyntheticInput] or the Windows SendInput call directly.)
Bugs:
All methods on OSX Cocoa will throw not yet implemented exceptions.
+/
struct SyntheticInput {
@disable this();
private int* refcount;
version(X11) {
private void* lib;
private extern(C) {
void function(Display*, uint keycode, bool press, arch_ulong delay) XTestFakeKeyEvent;
void function(Display*, uint button, bool press, arch_ulong delay) XTestFakeButtonEvent;
}
}
/// The dummy param must be 0.
this(int dummy) {
version(X11) {
lib = dlopen("libXtst.so", RTLD_NOW);
if(lib is null)
throw new Exception("cannot load xtest lib extension");
scope(failure)
dlclose(lib);
XTestFakeButtonEvent = cast(typeof(XTestFakeButtonEvent)) dlsym(lib, "XTestFakeButtonEvent");
XTestFakeKeyEvent = cast(typeof(XTestFakeKeyEvent)) dlsym(lib, "XTestFakeKeyEvent");
if(XTestFakeKeyEvent is null)
throw new Exception("No XTestFakeKeyEvent");
if(XTestFakeButtonEvent is null)
throw new Exception("No XTestFakeButtonEvent");
}
refcount = new int;
*refcount = 1;
}
this(this) {
if(refcount)
*refcount += 1;
}
~this() {
if(refcount) {
*refcount -= 1;
if(*refcount == 0)
// I commented this because if I close the lib before
// XCloseDisplay, it is liable to segfault... so just
// gonna keep it loaded if it is loaded, no big deal
// anyway.
{} // dlclose(lib);
}
}
/++
Simulates typing a string into the keyboard.
Bugs:
On X11, this ONLY works with basic ascii! On Windows, it can handle more.
Not implemented except on Windows and X11.
+/
void sendSyntheticInput(string s) {
version(Windows) {
INPUT[] inputs;
inputs.reserve(s.length * 2);
auto ei = GetMessageExtraInfo();
foreach(wchar c; s) {
INPUT input;
input.type = INPUT_KEYBOARD;
input.ki.wScan = c;
input.ki.dwFlags = KEYEVENTF_UNICODE;
input.ki.dwExtraInfo = ei;
inputs ~= input;
input.ki.dwFlags |= KEYEVENTF_KEYUP;
inputs ~= input;
}
if(SendInput(cast(int) inputs.length, inputs.ptr, INPUT.sizeof) != inputs.length) {
throw new Exception("SendInput failed");
}
} else version(X11) {
int delay = 0;
foreach(ch; s) {
pressKey(cast(Key) ch, true, delay);
pressKey(cast(Key) ch, false, delay);
delay += 5;
}
} else throw new NotYetImplementedException();
}
/++
Sends a fake press or release key event.
Please note you need to call [flushGui] or return to the event loop for this to actually be sent on X11.
Bugs:
The `delay` parameter is not implemented yet on Windows.
Not implemented except on Windows and X11.
+/
void pressKey(Key key, bool pressed, int delay = 0) {
version(Windows) {
INPUT input;
input.type = INPUT_KEYBOARD;
input.ki.wVk = cast(ushort) key;
input.ki.dwFlags = pressed ? 0 : KEYEVENTF_KEYUP;
input.ki.dwExtraInfo = GetMessageExtraInfo();
if(SendInput(1, &input, INPUT.sizeof) != 1) {
throw new Exception("SendInput failed");
}
} else version(X11) {
XTestFakeKeyEvent(XDisplayConnection.get, XKeysymToKeycode(XDisplayConnection.get, key), pressed, delay + pressed ? 0 : 5);
} else throw new NotYetImplementedException();
}
/++
Sends a fake mouse button press or release event.
Please note you need to call [flushGui] or return to the event loop for this to actually be sent on X11.
`pressed` param must be `true` if button is `wheelUp` or `wheelDown`.
Bugs:
The `delay` parameter is not implemented yet on Windows.
The backButton and forwardButton will throw NotYetImplementedException on Windows.
All arguments will throw NotYetImplementedException on OSX Cocoa.
+/
void pressMouseButton(MouseButton button, bool pressed, int delay = 0) {
version(Windows) {
INPUT input;
input.type = INPUT_MOUSE;
input.mi.dwExtraInfo = GetMessageExtraInfo();
// input.mi.mouseData for a wheel event
switch(button) {
case MouseButton.left: input.mi.dwFlags = pressed ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_LEFTUP; break;
case MouseButton.middle: input.mi.dwFlags = pressed ? MOUSEEVENTF_MIDDLEDOWN : MOUSEEVENTF_MIDDLEUP; break;
case MouseButton.right: input.mi.dwFlags = pressed ? MOUSEEVENTF_RIGHTDOWN : MOUSEEVENTF_RIGHTUP; break;
case MouseButton.wheelUp:
case MouseButton.wheelDown:
input.mi.dwFlags = MOUSEEVENTF_WHEEL;
input.mi.mouseData = button == MouseButton.wheelUp ? 120 : -120;
break;
case MouseButton.backButton: throw new NotYetImplementedException();
case MouseButton.forwardButton: throw new NotYetImplementedException();
default:
}
if(SendInput(1, &input, INPUT.sizeof) != 1) {
throw new Exception("SendInput failed");
}
} else version(X11) {
int btn;
switch(button) {
case MouseButton.left: btn = 1; break;
case MouseButton.middle: btn = 2; break;
case MouseButton.right: btn = 3; break;
case MouseButton.wheelUp: btn = 4; break;
case MouseButton.wheelDown: btn = 5; break;
case MouseButton.backButton: btn = 8; break;
case MouseButton.forwardButton: btn = 9; break;
default:
}
assert(btn);
XTestFakeButtonEvent(XDisplayConnection.get, btn, pressed, delay);
} else throw new NotYetImplementedException();
}
///
static void moveMouseArrowBy(int dx, int dy) {
version(Windows) {
INPUT input;
input.type = INPUT_MOUSE;
input.mi.dwExtraInfo = GetMessageExtraInfo();
input.mi.dx = dx;
input.mi.dy = dy;
input.mi.dwFlags = MOUSEEVENTF_MOVE;
if(SendInput(1, &input, INPUT.sizeof) != 1) {
throw new Exception("SendInput failed");
}
} else version(X11) {
auto disp = XDisplayConnection.get();
XWarpPointer(disp, None, None, 0, 0, 0, 0, dx, dy);
XFlush(disp);
} else throw new NotYetImplementedException();
}
///
static void moveMouseArrowTo(int x, int y) {
version(Windows) {
INPUT input;
input.type = INPUT_MOUSE;
input.mi.dwExtraInfo = GetMessageExtraInfo();
input.mi.dx = x;
input.mi.dy = y;
input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
if(SendInput(1, &input, INPUT.sizeof) != 1) {
throw new Exception("SendInput failed");
}
} else version(X11) {
auto disp = XDisplayConnection.get();
auto root = RootWindow(disp, DefaultScreen(disp));
XWarpPointer(disp, None, root, 0, 0, 0, 0, x, y);
XFlush(disp);
} else throw new NotYetImplementedException();
}
}
/++
[ScreenPainter] operations can use different operations to combine the color with the color on screen.
See_Also:
$(LIST
*[ScreenPainter]
*[ScreenPainter.rasterOp]
)
+/
enum RasterOp {
normal, /// Replaces the pixel.
xor, /// Uses bitwise xor to draw.
}
// being phobos-free keeps the size WAY down
private const(char)* toStringz(string s) { return (s ~ '\0').ptr; }
package(arsd) const(wchar)* toWStringz(wstring s) { return (s ~ '\0').ptr; }
package(arsd) const(wchar)* toWStringz(string s) {
wstring r;
foreach(dchar c; s)
r ~= c;
r ~= '\0';
return r.ptr;
}
private string[] split(in void[] a, char c) {
string[] ret;
size_t previous = 0;
foreach(i, char ch; cast(ubyte[]) a) {
if(ch == c) {
ret ~= cast(string) a[previous .. i];
previous = i + 1;
}
}
if(previous != a.length)
ret ~= cast(string) a[previous .. $];
return ret;
}
version(without_opengl) {
enum OpenGlOptions {
no,
}
} else {
/++
Determines if you want an OpenGL context created on the new window.
See more: [#topics-3d|in the 3d topic].
---
import arsd.simpledisplay;
void main() {
auto window = new SimpleWindow(500, 500, "OpenGL Test", OpenGlOptions.yes);
// Set up the matrix
window.setAsCurrentOpenGlContext(); // make this window active
// This is called on each frame, we will draw our scene
window.redrawOpenGlScene = delegate() {
};
window.eventLoop(0);
}
---
+/
enum OpenGlOptions {
no, /// No OpenGL context is created
yes, /// Yes, create an OpenGL context
}
version(X11) {
static if (!SdpyIsUsingIVGLBinds) {
struct __GLXFBConfigRec {}
alias GLXFBConfig = __GLXFBConfigRec*;
//pragma(lib, "GL");
//pragma(lib, "GLU");
interface GLX {
extern(C) nothrow @nogc {
XVisualInfo* glXChooseVisual(Display *dpy, int screen,
const int *attrib_list);
void glXCopyContext(Display *dpy, GLXContext src,
GLXContext dst, arch_ulong mask);
GLXContext glXCreateContext(Display *dpy, XVisualInfo *vis,
GLXContext share_list, Bool direct);
GLXPixmap glXCreateGLXPixmap(Display *dpy, XVisualInfo *vis,
Pixmap pixmap);
void glXDestroyContext(Display *dpy, GLXContext ctx);
void glXDestroyGLXPixmap(Display *dpy, GLXPixmap pix);
int glXGetConfig(Display *dpy, XVisualInfo *vis,
int attrib, int *value);
GLXContext glXGetCurrentContext();
GLXDrawable glXGetCurrentDrawable();
Bool glXIsDirect(Display *dpy, GLXContext ctx);
Bool glXMakeCurrent(Display *dpy, GLXDrawable drawable,
GLXContext ctx);
Bool glXQueryExtension(Display *dpy, int *error_base, int *event_base);
Bool glXQueryVersion(Display *dpy, int *major, int *minor);
void glXSwapBuffers(Display *dpy, GLXDrawable drawable);
void glXUseXFont(Font font, int first, int count, int list_base);
void glXWaitGL();
void glXWaitX();
GLXFBConfig* glXChooseFBConfig (Display*, int, int*, int*);
int glXGetFBConfigAttrib (Display*, GLXFBConfig, int, int*);
XVisualInfo* glXGetVisualFromFBConfig (Display*, GLXFBConfig);
char* glXQueryExtensionsString (Display*, int);
void* glXGetProcAddress (const(char)*);
}
}
version(OSX)
mixin DynamicLoad!(GLX, "GL", 0, openGlLibrariesSuccessfullyLoaded) glx;
else
mixin DynamicLoad!(GLX, "GLX", 0, openGlLibrariesSuccessfullyLoaded) glx;
shared static this() {
glx.loadDynamicLibrary();
}
alias glbindGetProcAddress = glXGetProcAddress;
}
} else version(Windows) {
/* it is done below by interface GL */
} else
static assert(0, "OpenGL not supported on your system yet. Try -version=X11 if you have X Windows available, or -version=without_opengl to go without.");
}
deprecated("Sorry, I misspelled it in the first version! Use `Resizability` instead.")
alias Resizablity = Resizability;
/// When you create a SimpleWindow, you can see its resizability to be one of these via the constructor...
enum Resizability {
fixedSize, /// the window cannot be resized. If it is resized anyway, simpledisplay will position and truncate your drawn content without necessarily informing your program, maintaining the API illusion of a non-resizable window.
allowResizing, /// the window can be resized. The buffer (if there is one) will automatically adjust size, but not stretch the contents. the windowResized delegate will be called so you can respond to the new size yourself. This allows most control for both user and you as the library consumer, but you also have to do the most work to handle it well.
/++
$(PITFALL
Planned for the future but not implemented.
)
Allow the user to resize the window, but try to maintain the original aspect ratio of the client area. The simpledisplay library may letterbox your content if necessary but will not stretch it. The windowResized delegate and width and height members will be updated with the size.
History:
Added November 11, 2022, but not yet implemented and may not be for some time.
+/
/*@future*/ allowResizingMaintainingAspectRatio, // gdc 9 doesn't allow the @future thing here but that's still the intention
/++
If possible, your drawing buffer will remain the same size and simply be automatically scaled to the new window size, letterboxing if needed to keep the aspect ratio. If this is impossible, it will fallback to [fixedSize]. The simpledisplay library will always provide the illusion that your window is the same size you requested, even if it scales things for you, meaning [width] and [height] will never change.
History:
Prior to November 11, 2022, width and height would change, which made this mode harder to use than intended. While I had documented this as a possiblity, I still considered it a bug, a leaky abstraction, and changed the code to tighten it up. After that date, the width and height members, as well as mouse coordinates, are always scaled to maintain the illusion of a fixed canvas size.
Your programs should not be affected, as they will continue to function as if the user simply never resized the window at all.
+/
automaticallyScaleIfPossible,
}
/++
Alignment for [ScreenPainter.drawText]. Left, Center, or Right may be combined with VerticalTop, VerticalCenter, or VerticalBottom via bitwise or.
+/
enum TextAlignment : uint {
Left = 0, ///
Center = 1, ///
Right = 2, ///
VerticalTop = 0, ///
VerticalCenter = 4, ///
VerticalBottom = 8, ///
}
public import arsd.color; // no longer stand alone... :-( but i need a common type for this to work with images easily.
alias Rectangle = arsd.color.Rectangle;
/++
Keyboard press and release events.
+/
struct KeyEvent {
/// see table below. Always use the symbolic names, even for ASCII characters, since the actual numbers vary across platforms. See [Key]
Key key;
ubyte hardwareCode; /// A platform and hardware specific code for the key
bool pressed; /// true if the key was just pressed, false if it was just released. note: released events aren't always sent...
deprecated("This never actually worked anyway, you should do a character event handler instead.") dchar character;
uint modifierState; /// see enum [ModifierState]. They are bitwise combined together.
SimpleWindow window; /// associated Window
/++
A view into the upcoming buffer holding coming character events that are sent if and only if neither
the alt or super modifier keys are pressed (check this with `!(modifierState & (ModifierState.window | ModifierState.alt))`
to predict if char events are actually coming..
Only available on X systems since this information is not given ahead of time elsewhere.
(Well, you COULD probably dig it up, but as far as I know right now, it isn't terribly pretty.)
I'm adding this because it is useful to the terminal emulator, but given its platform specificness
and potential quirks I'd recommend avoiding it.
History:
Added April 26, 2021 (dub v9.5)
+/
version(X11)
dchar[] charsPossible;
// convert key event to simplified string representation a-la emacs
const(char)[] toStrBuf(bool growdest=false) (char[] dest) const nothrow @trusted {
uint dpos = 0;
void put (const(char)[] s...) nothrow @trusted {
static if (growdest) {
foreach (char ch; s) if (dpos < dest.length) dest.ptr[dpos++] = ch; else { dest ~= ch; ++dpos; }
} else {
foreach (char ch; s) if (dpos < dest.length) dest.ptr[dpos++] = ch;
}
}
void putMod (ModifierState mod, Key key, string text) nothrow @trusted {
if ((this.modifierState&mod) != 0 && (this.pressed || this.key != key)) put(text);
}
if (!this.key && !(this.modifierState&(ModifierState.ctrl|ModifierState.alt|ModifierState.shift|ModifierState.windows))) return null;
// put modifiers
// releasing modifier keys can produce bizarre things like "Ctrl+Ctrl", so hack around it
putMod(ModifierState.ctrl, Key.Ctrl, "Ctrl+");
putMod(ModifierState.alt, Key.Alt, "Alt+");
putMod(ModifierState.windows, Key.Shift, "Windows+");
putMod(ModifierState.shift, Key.Shift, "Shift+");
if (this.key) {
foreach (string kn; __traits(allMembers, Key)) {
if (this.key == __traits(getMember, Key, kn)) {
// HACK!
static if (kn == "N0") put("0");
else static if (kn == "N1") put("1");
else static if (kn == "N2") put("2");
else static if (kn == "N3") put("3");
else static if (kn == "N4") put("4");
else static if (kn == "N5") put("5");
else static if (kn == "N6") put("6");
else static if (kn == "N7") put("7");
else static if (kn == "N8") put("8");
else static if (kn == "N9") put("9");
else put(kn);
return dest[0..dpos];
}
}
put("Unknown");
} else {
if (dpos && dest[dpos-1] == '+') --dpos;
}
return dest[0..dpos];
}
string toStr() () { return cast(string)toStrBuf!true(null); } // it is safe to cast here
/** Parse string into key name with modifiers. It accepts things like:
*
* C-H-1 -- emacs style (ctrl, and windows, and 1)
*
* Ctrl+Win+1 -- windows style
*
* Ctrl-Win-1 -- '-' is a valid delimiter too
*
* Ctrl Win 1 -- and space
*
* and even "Win + 1 + Ctrl".
*/
static KeyEvent parse (const(char)[] name, bool* ignoreModsOut=null, int* updown=null) nothrow @trusted @nogc {
auto nanchor = name; // keep it anchored, 'cause `name` may have NO_INTERIOR set
// remove trailing spaces
while (name.length && name[$-1] <= ' ') name = name[0..$-1];
// tokens delimited by blank, '+', or '-'
// null on eol
const(char)[] getToken () nothrow @trusted @nogc {
// remove leading spaces and delimiters
while (name.length && (name[0] <= ' ' || name[0] == '+' || name[0] == '-')) name = name[1..$];
if (name.length == 0) return null; // oops, no more tokens
// get token
size_t epos = 0;
while (epos < name.length && name[epos] > ' ' && name[epos] != '+' && name[epos] != '-') ++epos;
assert(epos > 0 && epos <= name.length);
auto res = name[0..epos];
name = name[epos..$];
return res;
}
static bool strEquCI (const(char)[] s0, const(char)[] s1) pure nothrow @trusted @nogc {
if (s0.length != s1.length) return false;
foreach (immutable ci, char c0; s0) {
if (c0 >= 'A' && c0 <= 'Z') c0 += 32; // poor man's tolower
char c1 = s1[ci];
if (c1 >= 'A' && c1 <= 'Z') c1 += 32; // poor man's tolower
if (c0 != c1) return false;
}
return true;
}
if (ignoreModsOut !is null) *ignoreModsOut = false;
if (updown !is null) *updown = -1;
KeyEvent res;
res.key = cast(Key)0; // just in case
const(char)[] tk, tkn; // last token
bool allowEmascStyle = true;
bool ignoreModifiers = false;
tokenloop: for (;;) {
tk = tkn;
tkn = getToken();
//k8: yay, i took "Bloody Mess" trait from Fallout!
if (tkn.length != 0 && tk.length == 0) { tk = tkn; continue tokenloop; }
if (tkn.length == 0 && tk.length == 0) break; // no more tokens
if (allowEmascStyle && tkn.length != 0) {
if (tk.length == 1) {
char mdc = tk[0];
if (mdc >= 'a' && mdc <= 'z') mdc -= 32; // poor man's toupper()
if (mdc == 'C' && (res.modifierState&ModifierState.ctrl) == 0) {res.modifierState |= ModifierState.ctrl; continue tokenloop; }
if (mdc == 'M' && (res.modifierState&ModifierState.alt) == 0) { res.modifierState |= ModifierState.alt; continue tokenloop; }
if (mdc == 'H' && (res.modifierState&ModifierState.windows) == 0) { res.modifierState |= ModifierState.windows; continue tokenloop; }
if (mdc == 'S' && (res.modifierState&ModifierState.shift) == 0) { res.modifierState |= ModifierState.shift; continue tokenloop; }
if (mdc == '*') { ignoreModifiers = true; continue tokenloop; }
if (mdc == 'U' || mdc == 'R') { if (updown !is null) *updown = 0; continue tokenloop; }
if (mdc == 'D' || mdc == 'P') { if (updown !is null) *updown = 1; continue tokenloop; }
}
}
allowEmascStyle = false;
if (strEquCI(tk, "Ctrl")) { res.modifierState |= ModifierState.ctrl; continue tokenloop; }
if (strEquCI(tk, "Alt")) { res.modifierState |= ModifierState.alt; continue tokenloop; }
if (strEquCI(tk, "Win") || strEquCI(tk, "Windows")) { res.modifierState |= ModifierState.windows; continue tokenloop; }
if (strEquCI(tk, "Shift")) { res.modifierState |= ModifierState.shift; continue tokenloop; }
if (strEquCI(tk, "Release")) { if (updown !is null) *updown = 0; continue tokenloop; }
if (strEquCI(tk, "Press")) { if (updown !is null) *updown = 1; continue tokenloop; }
if (tk == "*") { ignoreModifiers = true; continue tokenloop; }
if (tk.length == 0) continue;
// try key name
if (res.key == 0) {
// little hack
if (tk.length == 1 && tk[0] >= '0' && tk[0] <= '9') {
final switch (tk[0]) {
case '0': tk = "N0"; break;
case '1': tk = "N1"; break;
case '2': tk = "N2"; break;
case '3': tk = "N3"; break;
case '4': tk = "N4"; break;
case '5': tk = "N5"; break;
case '6': tk = "N6"; break;
case '7': tk = "N7"; break;
case '8': tk = "N8"; break;
case '9': tk = "N9"; break;
}
}
foreach (string kn; __traits(allMembers, Key)) {
if (strEquCI(tk, kn)) { res.key = __traits(getMember, Key, kn); continue tokenloop; }
}
}
// unknown or duplicate key name, get out of here
break;
}
if (ignoreModsOut !is null) *ignoreModsOut = ignoreModifiers;
return res; // something
}
bool opEquals() (const(char)[] name) const nothrow @trusted @nogc {
enum modmask = (ModifierState.ctrl|ModifierState.alt|ModifierState.shift|ModifierState.windows);
void doModKey (ref uint mask, ref Key kk, Key k, ModifierState mst) {
if (kk == k) { mask |= mst; kk = cast(Key)0; }
}
bool ignoreMods;
int updown;
auto ke = KeyEvent.parse(name, &ignoreMods, &updown);
if ((updown == 0 && this.pressed) || (updown == 1 && !this.pressed)) return false;
if (this.key != ke.key) {
// things like "ctrl+alt" are complicated
uint tkm = this.modifierState&modmask;
uint kkm = ke.modifierState&modmask;
Key tk = this.key;
// ke
doModKey(kkm, ke.key, Key.Ctrl, ModifierState.ctrl);
doModKey(kkm, ke.key, Key.Alt, ModifierState.alt);
doModKey(kkm, ke.key, Key.Windows, ModifierState.windows);
doModKey(kkm, ke.key, Key.Shift, ModifierState.shift);
// this
doModKey(tkm, tk, Key.Ctrl, ModifierState.ctrl);
doModKey(tkm, tk, Key.Alt, ModifierState.alt);
doModKey(tkm, tk, Key.Windows, ModifierState.windows);
doModKey(tkm, tk, Key.Shift, ModifierState.shift);
return (tk == ke.key && tkm == kkm);
}
return (ignoreMods || ((this.modifierState&modmask) == (ke.modifierState&modmask)));
}
}
/// Sets the application name.
@property string ApplicationName(string name) {
return _applicationName = name;
}
string _applicationName;
/// ditto
@property string ApplicationName() {
if(_applicationName is null) {
import core.runtime;
return Runtime.args[0];
}
return _applicationName;
}
/// Type of a [MouseEvent].
enum MouseEventType : int {
motion = 0, /// The mouse moved inside the window
buttonPressed = 1, /// A mouse button was pressed or the wheel was spun
buttonReleased = 2, /// A mouse button was released
}
// FIXME: mouse move should be distinct from presses+releases, so we can avoid subscribing to those events in X unnecessarily
/++
Listen for this on your event listeners if you are interested in mouse action.
Note that [button] is used on mouse press and release events. If you are curious about which button is being held in during motion, use [modifierState] and check the bitmask for [ModifierState.leftButtonDown], etc.
Examples:
This will draw boxes on the window with the mouse as you hold the left button.
---
import arsd.simpledisplay;
void main() {
auto window = new SimpleWindow();
window.eventLoop(0,
(MouseEvent ev) {
if(ev.modifierState & ModifierState.leftButtonDown) {
auto painter = window.draw();
painter.fillColor = Color.red;
painter.outlineColor = Color.black;
painter.drawRectangle(Point(ev.x / 16 * 16, ev.y / 16 * 16), 16, 16);
}
}
);
}
---
+/
struct MouseEvent {
MouseEventType type; /// movement, press, release, double click. See [MouseEventType]
int x; /// Current X position of the cursor when the event fired, relative to the upper-left corner of the window, reported in pixels. (0, 0) is the upper left, (window.width - 1, window.height - 1) is the lower right corner of the window.
int y; /// Current Y position of the cursor when the event fired.
int dx; /// Change in X position since last report
int dy; /// Change in Y position since last report
MouseButton button; /// See [MouseButton]
int modifierState; /// See [ModifierState]
version(X11)
private Time timestamp;
/// Returns a linear representation of mouse button,
/// for use with static arrays. Guaranteed to be >= 0 && <= 15
///
/// Its implementation is based on range-limiting `core.bitop.bsf(button) + 1`.
@property ubyte buttonLinear() const {
import core.bitop;
if(button == 0)
return 0;
return (bsf(button) + 1) & 0b1111;
}
bool doubleClick; /// was it a double click? Only set on type == [MouseEventType.buttonPressed]
SimpleWindow window; /// The window in which the event happened.
Point globalCoordinates() {
Point p;
if(window is null)
throw new Exception("wtf");
static if(UsingSimpledisplayX11) {
Window child;
XTranslateCoordinates(
XDisplayConnection.get,
window.impl.window,
RootWindow(XDisplayConnection.get, DefaultScreen(XDisplayConnection.get)),
x, y, &p.x, &p.y, &child);
return p;
} else version(Windows) {
POINT[1] points;
points[0].x = x;
points[0].y = y;
MapWindowPoints(
window.impl.hwnd,
null,
points.ptr,
points.length
);
p.x = points[0].x;
p.y = points[0].y;
return p;
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
bool opEquals() (const(char)[] str) pure nothrow @trusted @nogc { return equStr(this, str); }
/**
can contain emacs-like modifier prefix
case-insensitive names:
lmbX/leftX
rmbX/rightX
mmbX/middleX
wheelX
motion (no prefix allowed)
'X' is either "up" or "down" (or "-up"/"-down"); if omited, means "down"
*/
static bool equStr() (scope auto ref const MouseEvent event, const(char)[] str) pure nothrow @trusted @nogc {
if (str.length == 0) return false; // just in case
debug(arsd_mevent_strcmp) { import iv.cmdcon; conwriteln("str=<", str, ">"); }
enum Flag : uint { Up = 0x8000_0000U, Down = 0x4000_0000U, Any = 0x1000_0000U }
auto anchor = str;
uint mods = 0; // uint.max == any
// interesting bits in kmod
uint kmodmask =
ModifierState.shift|
ModifierState.ctrl|
ModifierState.alt|
ModifierState.windows|
ModifierState.leftButtonDown|
ModifierState.middleButtonDown|
ModifierState.rightButtonDown|
0;
uint lastButt = uint.max; // otherwise, bit 31 means "down"
bool wasButtons = false;
while (str.length) {
if (str.ptr[0] <= ' ') {
while (str.length && str.ptr[0] <= ' ') str = str[1..$];
continue;
}
// one-letter modifier?
if (str.length >= 2 && str.ptr[1] == '-') {
switch (str.ptr[0]) {
case '*': // "any" modifier (cannot be undone)
mods = mods.max;
break;
case 'C': case 'c': // emacs "ctrl"
if (mods != mods.max) mods |= ModifierState.ctrl;
break;
case 'M': case 'm': // emacs "meta"
if (mods != mods.max) mods |= ModifierState.alt;
break;
case 'S': case 's': // emacs "shift"
if (mods != mods.max) mods |= ModifierState.shift;
break;
case 'H': case 'h': // emacs "hyper" (aka winkey)
if (mods != mods.max) mods |= ModifierState.windows;
break;
default:
return false; // unknown modifier
}
str = str[2..$];
continue;
}
// word
char[16] buf = void; // locased
auto wep = 0;
while (str.length) {
immutable char ch = str.ptr[0];
if (ch <= ' ' || ch == '-') break;
str = str[1..$];
if (wep > buf.length) return false; // too long
if (ch >= 'A' && ch <= 'Z') buf.ptr[wep++] = cast(char)(ch+32); // poor man tolower
else if (ch >= 'a' && ch <= 'z') buf.ptr[wep++] = ch;
else return false; // invalid char
}
if (wep == 0) return false; // just in case
uint bnum;
enum UpDown { None = -1, Up, Down, Any }
auto updown = UpDown.None; // 0: up; 1: down
switch (buf[0..wep]) {
// left button
case "lmbup": case "leftup": updown = UpDown.Up; goto case "lmb";
case "lmbdown": case "leftdown": updown = UpDown.Down; goto case "lmb";
case "lmbany": case "leftany": updown = UpDown.Any; goto case "lmb";
case "lmb": case "left": bnum = 0; break;
// middle button
case "mmbup": case "middleup": updown = UpDown.Up; goto case "mmb";
case "mmbdown": case "middledown": updown = UpDown.Down; goto case "mmb";
case "mmbany": case "middleany": updown = UpDown.Any; goto case "mmb";
case "mmb": case "middle": bnum = 1; break;
// right button
case "rmbup": case "rightup": updown = UpDown.Up; goto case "rmb";
case "rmbdown": case "rightdown": updown = UpDown.Down; goto case "rmb";
case "rmbany": case "rightany": updown = UpDown.Any; goto case "rmb";
case "rmb": case "right": bnum = 2; break;
// wheel
case "wheelup": updown = UpDown.Up; goto case "wheel";
case "wheeldown": updown = UpDown.Down; goto case "wheel";
case "wheelany": updown = UpDown.Any; goto case "wheel";
case "wheel": bnum = 3; break;
// motion
case "motion": bnum = 7; break;
// unknown
default: return false;
}
debug(arsd_mevent_strcmp) { import iv.cmdcon; conprintfln(" 0: mods=0x%08x; bnum=%u; updown=%s [%s]", mods, bnum, updown, str); }
// parse possible "-up" or "-down"
if (updown == UpDown.None && bnum < 7 && str.length > 0 && str.ptr[0] == '-') {
wep = 0;
foreach (immutable idx, immutable char ch; str[1..$]) {
if (ch <= ' ' || ch == '-') break;
assert(idx == wep); // for now; trick
if (wep > buf.length) { wep = 0; break; } // too long
if (ch >= 'A' && ch <= 'Z') buf.ptr[wep++] = cast(char)(ch+32); // poor man tolower
else if (ch >= 'a' && ch <= 'z') buf.ptr[wep++] = ch;
else { wep = 0; break; } // invalid char
}
if (wep == 2 && buf[0..wep] == "up") updown = UpDown.Up;
else if (wep == 4 && buf[0..wep] == "down") updown = UpDown.Down;
else if (wep == 3 && buf[0..wep] == "any") updown = UpDown.Any;
// remove parsed part
if (updown != UpDown.None) str = str[wep+1..$];
}
if (updown == UpDown.None) {
updown = UpDown.Down;
}
wasButtons = wasButtons || (bnum <= 2);
//assert(updown != UpDown.None);
debug(arsd_mevent_strcmp) { import iv.cmdcon; conprintfln(" 1: mods=0x%08x; bnum=%u; updown=%s [%s]", mods, bnum, updown, str); }
// if we have a previous button, it goes to modifiers (unless it is a wheel or motion)
if (lastButt != lastButt.max) {
if ((lastButt&0xff) >= 3) return false; // wheel or motion
if (mods != mods.max) {
uint butbit = 0;
final switch (lastButt&0x03) {
case 0: butbit = ModifierState.leftButtonDown; break;
case 1: butbit = ModifierState.middleButtonDown; break;
case 2: butbit = ModifierState.rightButtonDown; break;
}
if (lastButt&Flag.Down) mods |= butbit;
else if (lastButt&Flag.Up) mods &= ~butbit;
else if (lastButt&Flag.Any) kmodmask &= ~butbit;
}
}
// remember last button
lastButt = bnum|(updown == UpDown.Up ? Flag.Up : updown == UpDown.Any ? Flag.Any : Flag.Down);
}
// no button -- nothing to do
if (lastButt == lastButt.max) return false;
// done parsing, check if something's left
foreach (immutable char ch; str) if (ch > ' ') return false; // oops
// remove action button from mask
if ((lastButt&0xff) < 3) {
final switch (lastButt&0x03) {
case 0: kmodmask &= ~cast(uint)ModifierState.leftButtonDown; break;
case 1: kmodmask &= ~cast(uint)ModifierState.middleButtonDown; break;
case 2: kmodmask &= ~cast(uint)ModifierState.rightButtonDown; break;
}
}
// special case: "Motion" means "ignore buttons"
if ((lastButt&0xff) == 7 && !wasButtons) {
debug(arsd_mevent_strcmp) { import iv.cmdcon; conwriteln(" *: special motion"); }
kmodmask &= ~cast(uint)(ModifierState.leftButtonDown|ModifierState.middleButtonDown|ModifierState.rightButtonDown);
}
uint kmod = event.modifierState&kmodmask;
debug(arsd_mevent_strcmp) { import iv.cmdcon; conprintfln(" *: mods=0x%08x; lastButt=0x%08x; kmod=0x%08x; type=%s", mods, lastButt, kmod, event.type); }
// check modifier state
if (mods != mods.max) {
if (kmod != mods) return false;
}
// now check type
if ((lastButt&0xff) == 7) {
// motion
if (event.type != MouseEventType.motion) return false;
} else if ((lastButt&0xff) == 3) {
// wheel
if (lastButt&Flag.Up) return (event.type == MouseEventType.buttonPressed && event.button == MouseButton.wheelUp);
if (lastButt&Flag.Down) return (event.type == MouseEventType.buttonPressed && event.button == MouseButton.wheelDown);
if (lastButt&Flag.Any) return (event.type == MouseEventType.buttonPressed && (event.button == MouseButton.wheelUp || event.button == MouseButton.wheelUp));
return false;
} else {
// buttons
if (((lastButt&Flag.Down) != 0 && event.type != MouseEventType.buttonPressed) ||
((lastButt&Flag.Up) != 0 && event.type != MouseEventType.buttonReleased))
{
return false;
}
// button number
switch (lastButt&0x03) {
case 0: if (event.button != MouseButton.left) return false; break;
case 1: if (event.button != MouseButton.middle) return false; break;
case 2: if (event.button != MouseButton.right) return false; break;
default: return false;
}
}
return true;
}
}
version(arsd_mevent_strcmp_test) unittest {
MouseEvent event;
event.type = MouseEventType.buttonPressed;
event.button = MouseButton.left;
event.modifierState = ModifierState.ctrl;
assert(event == "C-LMB");
assert(event != "C-LMBUP");
assert(event != "C-LMB-UP");
assert(event != "C-S-LMB");
assert(event == "*-LMB");
assert(event != "*-LMB-UP");
event.type = MouseEventType.buttonReleased;
assert(event != "C-LMB");
assert(event == "C-LMBUP");
assert(event == "C-LMB-UP");
assert(event != "C-S-LMB");
assert(event != "*-LMB");
assert(event == "*-LMB-UP");
event.button = MouseButton.right;
event.modifierState |= ModifierState.shift;
event.type = MouseEventType.buttonPressed;
assert(event != "C-LMB");
assert(event != "C-LMBUP");
assert(event != "C-LMB-UP");
assert(event != "C-S-LMB");
assert(event != "*-LMB");
assert(event != "*-LMB-UP");
assert(event != "C-RMB");
assert(event != "C-RMBUP");
assert(event != "C-RMB-UP");
assert(event == "C-S-RMB");
assert(event == "*-RMB");
assert(event != "*-RMB-UP");
}
/// This gives a few more options to drawing lines and such
struct Pen {
Color color; /// the foreground color
int width = 1; /// width of the line. please note that on X, wide lines are drawn centered on the coordinates, so you may have to offset things.
Style style; /// See [Style]
/+
// From X.h
#define LineSolid 0
#define LineOnOffDash 1
#define LineDoubleDash 2
LineDou- The full path of the line is drawn, but the
bleDash even dashes are filled differently from the
odd dashes (see fill-style) with CapButt
style used where even and odd dashes meet.
/* capStyle */
#define CapNotLast 0
#define CapButt 1
#define CapRound 2
#define CapProjecting 3
/* joinStyle */
#define JoinMiter 0
#define JoinRound 1
#define JoinBevel 2
/* fillStyle */
#define FillSolid 0
#define FillTiled 1
#define FillStippled 2
#define FillOpaqueStippled 3
+/
/// Style of lines drawn
enum Style {
Solid, /// a solid line
Dashed, /// a dashed line
Dotted, /// a dotted line
}
}
/++
Represents an in-memory image in the format that the GUI expects, but with its raw data available to your program.
On Windows, this means a device-independent bitmap. On X11, it is an XImage.
$(NOTE If you are writing platform-aware code and need to know low-level details, uou may check `if(Image.impl.xshmAvailable)` to see if MIT-SHM is used on X11 targets to draw `Image`s and `Sprite`s. Use `static if(UsingSimpledisplayX11)` to determine if you are compiling for an X11 target.)
Drawing an image to screen is not necessarily fast, but applying algorithms to draw to the image itself should be fast. An `Image` is also the first step in loading and displaying images loaded from files.
If you intend to draw an image to screen several times, you will want to convert it into a [Sprite].
$(PITFALL `Image` may represent a scarce, shared resource that persists across process termination, and should be disposed of properly. On X11, it uses the MIT-SHM extension, if available, which uses shared memory handles with the X server, which is a long-lived process that holds onto them after your program terminates if you don't free it.
It is possible for your user's system to run out of these handles over time, forcing them to clean it up with extraordinary measures - their GUI is liable to stop working!
Be sure these are cleaned up properly. simpledisplay will do its best to do the right thing, including cleaning them up in garbage collection sweeps (one of which is run at most normal program terminations) and catching some deadly signals. It will almost always do the right thing. But, this is no substitute for you managing the resource properly yourself. (And try not to segfault, as recovery from them is alway dicey!)
Please call `destroy(image);` when you are done with it. The easiest way to do this is with scope:
---
auto image = new Image(256, 256);
scope(exit) destroy(image);
---
As long as you don't hold on to it outside the scope.
I might change it to be an owned pointer at some point in the future.
)
Drawing pixels on the image may be simple, using the `opIndexAssign` function, but
you can also often get a fair amount of speedup by getting the raw data format and
writing some custom code.
FIXME INSERT EXAMPLES HERE
+/
final class Image {
///
this(int width, int height, bool forcexshm=false, bool enableAlpha = false) {
this.width = width;
this.height = height;
this.enableAlpha = enableAlpha;
impl.createImage(width, height, forcexshm, enableAlpha);
}
///
this(Size size, bool forcexshm=false, bool enableAlpha = false) {
this(size.width, size.height, forcexshm, enableAlpha);
}
private bool suppressDestruction;
version(X11)
this(XImage* handle) {
this.handle = handle;
this.rawData = cast(ubyte*) handle.data;
this.width = handle.width;
this.height = handle.height;
this.enableAlpha = handle.depth == 32;
suppressDestruction = true;
}
~this() {
if(suppressDestruction) return;
impl.dispose();
}
// these numbers are used for working with rawData itself, skipping putPixel and getPixel
/// if you do the math yourself you might be able to optimize it. Call these functions only once and cache the value.
pure const @system nothrow {
/*
To use these to draw a blue rectangle with size WxH at position X,Y...
// make certain that it will fit before we proceed
enforce(X + W <= img.width && Y + H <= img.height); // you could also adjust the size to clip it, but be sure not to run off since this here will do raw pointers with no bounds checks!
// gather all the values you'll need up front. These can be kept until the image changes size if you want
// (though calculating them isn't really that expensive).
auto nextLineAdjustment = img.adjustmentForNextLine();
auto offR = img.redByteOffset();
auto offB = img.blueByteOffset();
auto offG = img.greenByteOffset();
auto bpp = img.bytesPerPixel();
auto data = img.getDataPointer();
// figure out the starting byte offset
auto offset = img.offsetForTopLeftPixel() + nextLineAdjustment*Y + bpp * X;
auto startOfLine = data + offset; // get our pointer lined up on the first pixel
// and now our drawing loop for the rectangle
foreach(y; 0 .. H) {
auto data = startOfLine; // we keep the start of line separately so moving to the next line is simple and portable
foreach(x; 0 .. W) {
// write our color
data[offR] = 0;
data[offG] = 0;
data[offB] = 255;
data += bpp; // moving to the next pixel is just an addition...
}
startOfLine += nextLineAdjustment;
}
As you can see, the loop itself was very simple thanks to the calculations being moved outside.
FIXME: I wonder if I can make the pixel formats consistently 32 bit across platforms, so the color offsets
can be made into a bitmask or something so we can write them as *uint...
*/
///
int offsetForTopLeftPixel() {
version(X11) {
return 0;
} else version(Windows) {
if(enableAlpha) {
return (width * 4) * (height - 1);
} else {
return (((cast(int) width * 3 + 3) / 4) * 4) * (height - 1);
}
} else version(OSXCocoa) {
return 0 ; //throw new NotYetImplementedException();
} else static assert(0, "fill in this info for other OSes");
}
///
int offsetForPixel(int x, int y) {
version(X11) {
auto offset = (y * width + x) * 4;
return offset;
} else version(Windows) {
if(enableAlpha) {
auto itemsPerLine = width * 4;
// remember, bmps are upside down
auto offset = itemsPerLine * (height - y - 1) + x * 4;
return offset;
} else {
auto itemsPerLine = ((cast(int) width * 3 + 3) / 4) * 4;
// remember, bmps are upside down
auto offset = itemsPerLine * (height - y - 1) + x * 3;
return offset;
}
} else version(OSXCocoa) {
return 0 ; //throw new NotYetImplementedException();
} else static assert(0, "fill in this info for other OSes");
}
///
int adjustmentForNextLine() {
version(X11) {
return width * 4;
} else version(Windows) {
// windows bmps are upside down, so the adjustment is actually negative
if(enableAlpha)
return - (cast(int) width * 4);
else
return -((cast(int) width * 3 + 3) / 4) * 4;
} else version(OSXCocoa) {
return 0 ; //throw new NotYetImplementedException();
} else static assert(0, "fill in this info for other OSes");
}
/// once you have the position of a pixel, use these to get to the proper color
int redByteOffset() {
version(X11) {
return 2;
} else version(Windows) {
return 2;
} else version(OSXCocoa) {
return 0 ; //throw new NotYetImplementedException();
} else static assert(0, "fill in this info for other OSes");
}
///
int greenByteOffset() {
version(X11) {
return 1;
} else version(Windows) {
return 1;
} else version(OSXCocoa) {
return 0 ; //throw new NotYetImplementedException();
} else static assert(0, "fill in this info for other OSes");
}
///
int blueByteOffset() {
version(X11) {
return 0;
} else version(Windows) {
return 0;
} else version(OSXCocoa) {
return 0 ; //throw new NotYetImplementedException();
} else static assert(0, "fill in this info for other OSes");
}
/// Only valid if [enableAlpha] is true
int alphaByteOffset() {
version(X11) {
return 3;
} else version(Windows) {
return 3;
} else version(OSXCocoa) {
return 3; //throw new NotYetImplementedException();
} else static assert(0, "fill in this info for other OSes");
}
}
///
final void putPixel(int x, int y, Color c) {
if(x < 0 || x >= width)
return;
if(y < 0 || y >= height)
return;
impl.setPixel(x, y, c);
}
///
final Color getPixel(int x, int y) {
if(x < 0 || x >= width)
return Color.transparent;
if(y < 0 || y >= height)
return Color.transparent;
version(OSXCocoa) throw new NotYetImplementedException(); else
return impl.getPixel(x, y);
}
///
final void opIndexAssign(Color c, int x, int y) {
putPixel(x, y, c);
}
///
TrueColorImage toTrueColorImage() {
auto tci = new TrueColorImage(width, height);
convertToRgbaBytes(tci.imageData.bytes);
return tci;
}
///
static Image fromMemoryImage(MemoryImage i, bool enableAlpha = false) {
auto tci = i.getAsTrueColorImage();
auto img = new Image(tci.width, tci.height, false, enableAlpha);
img.setRgbaBytes(tci.imageData.bytes);
return img;
}
/// this is here for interop with arsd.image. where can be a TrueColorImage's data member
/// if you pass in a buffer, it will put it right there. length must be width*height*4 already
/// if you pass null, it will allocate a new one.
ubyte[] getRgbaBytes(ubyte[] where = null) {
if(where is null)
where = new ubyte[this.width*this.height*4];
convertToRgbaBytes(where);
return where;
}
/// this is here for interop with arsd.image. from can be a TrueColorImage's data member
void setRgbaBytes(in ubyte[] from ) {
assert(from.length == this.width * this.height * 4);
setFromRgbaBytes(from);
}
// FIXME: make properly cross platform by getting rgba right
/// warning: this is not portable across platforms because the data format can change
ubyte* getDataPointer() {
return impl.rawData;
}
/// for use with getDataPointer
final int bytesPerLine() const pure @safe nothrow {
version(Windows)
return enableAlpha ? (width * 4) : (((cast(int) width * 3 + 3) / 4) * 4);
else version(X11)
return 4 * width;
else version(OSXCocoa)
return 4 * width;
else static assert(0);
}
/// for use with getDataPointer
final int bytesPerPixel() const pure @safe nothrow {
version(Windows)
return enableAlpha ? 4 : 3;
else version(X11)
return 4;
else version(OSXCocoa)
return 4;
else static assert(0);
}
///
immutable int width;
///
immutable int height;
///
immutable bool enableAlpha;
//private:
mixin NativeImageImplementation!() impl;
}
/++
A convenience function to pop up a window displaying the image.
If you pass a win, it will draw the image in it. Otherwise, it will
create a window with the size of the image and run its event loop, closing
when a key is pressed.
History:
`BlockingMode` parameter added on December 8, 2021. Previously, it would
always block until the application quit which could cause bizarre behavior
inside a more complex application. Now, the default is to block until
this window closes if it is the only event loop running, and otherwise,
not to block at all and just pop up the display window asynchronously.
+/
void displayImage(Image image, SimpleWindow win = null, BlockingMode bm = BlockingMode.untilWindowCloses | BlockingMode.onlyIfNotNested) {
if(win is null) {
win = new SimpleWindow(image);
{
auto p = win.draw;
p.drawImage(Point(0, 0), image);
}
win.eventLoopWithBlockingMode(
bm, 0,
(KeyEvent ev) {
if (ev.pressed && (ev.key == Key.Escape || ev.key == Key.Space)) win.close();
} );
} else {
win.image = image;
}
}
enum FontWeight : int {
dontcare = 0,
thin = 100,
extralight = 200,
light = 300,
regular = 400,
medium = 500,
semibold = 600,
bold = 700,
extrabold = 800,
heavy = 900
}
/++
Interface with the common functionality for font measurements between [OperatingSystemFont] and [DrawableFont].
History:
Added October 24, 2022. The methods were already on [OperatingSystemFont] before that.
+/
interface MeasurableFont {
/++
Returns true if it is a monospace font, meaning each of the
glyphs (at least the ascii characters) have matching width
and no kerning, so you can determine the display width of some
strings by simply multiplying the string width by [averageWidth].
(Please note that multiply doesn't $(I actually) work in general,
consider characters like tab and newline, but it does sometimes.)
+/
bool isMonospace();
/++
The average width of glyphs in the font, traditionally equal to the
width of the lowercase x. Can be used to estimate bounding boxes,
especially if the font [isMonospace].
Given in pixels.
+/
int averageWidth();
/++
The height of the bounding box of a line.
+/
int height();
/++
The maximum ascent of a glyph above the baseline.
Given in pixels.
+/
int ascent();
/++
The maximum descent of a glyph below the baseline. For example, how low the g might go.
Given in pixels.
+/
int descent();
/++
The display width of the given string, and if you provide a window, it will use it to
make the pixel count on screen more accurate too, but this shouldn't generally be necessary.
Given in pixels.
+/
int stringWidth(scope const(char)[] s, SimpleWindow window = null);
}
// FIXME: i need a font cache and it needs to handle disconnects.
/++
Represents a font loaded off the operating system or the X server.
While the api here is unified cross platform, the fonts are not necessarily
available, even across machines of the same platform, so be sure to always check
for null (using [isNull]) and have a fallback plan.
When you have a font you like, use [ScreenPainter.setFont] to load it for drawing.
Worst case, a null font will automatically fall back to the default font loaded
for your system.
+/
class OperatingSystemFont : MeasurableFont {
// FIXME: when the X Connection is lost, these need to be invalidated!
// that means I need to store the original stuff again to reconstruct it too.
version(X11) {
XFontStruct* font;
XFontSet fontset;
version(with_xft) {
XftFont* xftFont;
bool isXft;
}
} else version(Windows) {
HFONT font;
int width_;
int height_;
} else version(OSXCocoa) {
// FIXME
} else static assert(0);
/++
Constructs the class and immediately calls [load].
+/
this(string name, int size = 0, FontWeight weight = FontWeight.dontcare, bool italic = false) {
load(name, size, weight, italic);
}
/++
Constructs the object, but does nothing. Call one of [load] or [loadDefault] to populate the object.
You can also call the platform-specific [loadXft], [loadCoreX], or [loadWin32] functions if appropriate for you.
History:
Added January 24, 2021.
+/
this() {
// this space intentionally left blank
}
/++
Constructs a copy of the given font object.
History:
Added January 7, 2023.
+/
this(OperatingSystemFont font) {
if(font is null || font.loadedInfo is LoadedInfo.init)
loadDefault();
else
load(font.loadedInfo.tupleof);
}
/++
Loads specifically with the Xft library - a freetype font from a fontconfig string.
History:
Added November 13, 2020.
+/
version(with_xft)
bool loadXft(string name, int size = 0, FontWeight weight = FontWeight.dontcare, bool italic = false) {
unload();
if(!XftLibrary.attempted) {
XftLibrary.loadDynamicLibrary();
}
if(!XftLibrary.loadSuccessful)
return false;
auto display = XDisplayConnection.get;
char[256] nameBuffer = void;
int nbp = 0;
void add(in char[] a) {
nameBuffer[nbp .. nbp + a.length] = a[];
nbp += a.length;
}
add(name);
if(size) {
add(":size=");
add(toInternal!string(size));
}
if(weight != FontWeight.dontcare) {
add(":weight=");
add(weightToString(weight));
}
if(italic)
add(":slant=100");
nameBuffer[nbp] = 0;
this.xftFont = XftFontOpenName(
display,
DefaultScreen(display),
nameBuffer.ptr
);
this.isXft = true;
if(xftFont !is null) {
isMonospace_ = stringWidth("x") == stringWidth("M");
ascent_ = xftFont.ascent;
descent_ = xftFont.descent;
}
return !isNull();
}
/++
Lists available fonts from the system that match the given pattern, finding names that are suitable for passing to [OperatingSystemFont]'s constructor.
Fonts will be fed to you (possibly! it is platform and implementation dependent on if it is called immediately or later) asynchronously through the given delegate. It should return `true` if you want more, `false` if you are done. The delegate will be called once after finishing with a `init` value to let you know it is done and you can do final processing.
If `pattern` is null, it returns all available font families.
Please note that you may also receive fonts that do not match your given pattern. You should still filter them in the handler; the pattern is really just an optimization hint rather than a formal guarantee.
The format of the pattern is platform-specific.
History:
Added May 1, 2021 (dub v9.5)
+/
static void listFonts(string pattern, bool delegate(in char[] name) handler) {
version(Windows) {
auto hdc = GetDC(null);
scope(exit) ReleaseDC(null, hdc);
LOGFONT logfont;
static extern(Windows) int proc(const LOGFONT* lf, const TEXTMETRIC* tm, DWORD type, LPARAM p) {
auto localHandler = *(cast(typeof(handler)*) p);
return localHandler(lf.lfFaceName[].sliceCString) ? 1 : 0;
}
EnumFontFamiliesEx(hdc, &logfont, &proc, cast(LPARAM) &handler, 0);
} else version(X11) {
//import core.stdc.stdio;
bool done = false;
version(with_xft) {
if(!XftLibrary.attempted) {
XftLibrary.loadDynamicLibrary();
}
if(!XftLibrary.loadSuccessful)
goto skipXft;
if(!FontConfigLibrary.attempted)
FontConfigLibrary.loadDynamicLibrary();
if(!FontConfigLibrary.loadSuccessful)
goto skipXft;
{
auto got = XftListFonts(XDisplayConnection.get, 0, null, "family".ptr, "style".ptr, null);
if(got is null)
goto skipXft;
scope(exit) FcFontSetDestroy(got);
auto fontPatterns = got.fonts[0 .. got.nfont];
foreach(candidate; fontPatterns) {
char* where, whereStyle;
char* pmg = FcNameUnparse(candidate);
//FcPatternGetString(candidate, "family", 0, &where);
//FcPatternGetString(candidate, "style", 0, &whereStyle);
//if(where && whereStyle) {
if(pmg) {
if(!handler(pmg.sliceCString))
return;
//printf("%s || %s %s\n", pmg, where, whereStyle);
}
}
}
}
skipXft:
if(pattern is null)
pattern = "*";
int count;
auto coreFontsRaw = XListFonts(XDisplayConnection.get, pattern.toStringz, 10000 /* max return */, &count);
scope(exit) XFreeFontNames(coreFontsRaw);
auto coreFonts = coreFontsRaw[0 .. count];
foreach(font; coreFonts) {
char[128] tmp;
tmp[0 ..5] = "core:";
auto cf = font.sliceCString;
if(5 + cf.length > tmp.length)
assert(0, "a font name was too long, sorry i didn't bother implementing a fallback");
tmp[5 .. 5 + cf.length] = cf;
if(!handler(tmp[0 .. 5 + cf.length]))
return;
}
}
}
/++
Returns the raw content of the ttf file, if possible. This allows you to use OperatingSystemFont
to look up fonts that you then pass to things like [arsd.ttf.OpenGlLimitedFont] or [arsd.nanovega].
Returns null if impossible. It is impossible if the loaded font is not a local TTF file or if the
underlying system doesn't support returning the raw bytes.
History:
Added September 10, 2021 (dub v10.3)
+/
ubyte[] getTtfBytes() {
if(isNull)
return null;
version(Windows) {
auto dc = GetDC(null);
auto orig = SelectObject(dc, font);
scope(exit) {
SelectObject(dc, orig);
ReleaseDC(null, dc);
}
auto res = GetFontData(dc, 0 /* whole file */, 0 /* offset */, null, 0);
if(res == GDI_ERROR)
return null;
ubyte[] buffer = new ubyte[](res);
res = GetFontData(dc, 0 /* whole file */, 0 /* offset */, buffer.ptr, cast(DWORD) buffer.length);
if(res == GDI_ERROR)
return null; // wtf really tbh
return buffer;
} else version(with_xft) {
if(isXft && xftFont) {
if(!FontConfigLibrary.attempted)
FontConfigLibrary.loadDynamicLibrary();
if(!FontConfigLibrary.loadSuccessful)
return null;
char* file;
if (FcPatternGetString(xftFont.pattern, "file", 0, &file) == 0 /*FcResultMatch*/) {
if (file !is null && file[0]) {
import core.stdc.stdio;
auto fp = fopen(file, "rb");
if(fp is null)
return null;
scope(exit)
fclose(fp);
fseek(fp, 0, SEEK_END);
ubyte[] buffer = new ubyte[](ftell(fp));
fseek(fp, 0, SEEK_SET);
auto got = fread(buffer.ptr, 1, buffer.length, fp);
if(got != buffer.length)
return null;
return buffer;
}
}
}
return null;
}
}
// see also: XftLockFace(font) which gives a FT_Face. from /usr/include/X11/Xft/Xft.h line 352
private string weightToString(FontWeight weight) {
with(FontWeight)
final switch(weight) {
case dontcare: return "*";
case thin: return "extralight";
case extralight: return "extralight";
case light: return "light";
case regular: return "regular";
case medium: return "medium";
case semibold: return "demibold";
case bold: return "bold";
case extrabold: return "demibold";
case heavy: return "black";
}
}
/++
Loads specifically a Core X font - rendered on the X server without antialiasing. Best performance.
History:
Added November 13, 2020. Before then, this code was integrated in the [load] function.
+/
version(X11)
bool loadCoreX(string name, int size = 0, FontWeight weight = FontWeight.dontcare, bool italic = false) {
unload();
string xfontstr;
if(name.length > 3 && name[0 .. 3] == "-*-") {
// this is kinda a disgusting hack but if the user sends an exact
// string I'd like to honor it...
xfontstr = name;
} else {
string weightstr = weightToString(weight);
string sizestr;
if(size == 0)
sizestr = "*";
else
sizestr = toInternal!string(size);
xfontstr = "-*-"~name~"-"~weightstr~"-"~(italic ? "i" : "r")~"-*-*-"~sizestr~"-*-*-*-*-*-*-*\0";
}
//import std.stdio; writeln(xfontstr);
auto display = XDisplayConnection.get;
font = XLoadQueryFont(display, xfontstr.ptr);
if(font is null)
return false;
char** lol;
int lol2;
char* lol3;
fontset = XCreateFontSet(display, xfontstr.ptr, &lol, &lol2, &lol3);
prepareFontInfo();
return !isNull();
}
version(X11)
private void prepareFontInfo() {
if(font !is null) {
isMonospace_ = stringWidth("l") == stringWidth("M");
ascent_ = font.max_bounds.ascent;
descent_ = font.max_bounds.descent;
}
}
/++
Loads a Windows font. You probably want to use [load] instead to be more generic.
History:
Added November 13, 2020. Before then, this code was integrated in the [load] function.
+/
version(Windows)
bool loadWin32(string name, int size = 0, FontWeight weight = FontWeight.dontcare, bool italic = false, HDC hdc = null) {
unload();
WCharzBuffer buffer = WCharzBuffer(name);
font = CreateFont(size, 0, 0, 0, cast(int) weight, italic, 0, 0, 0, 0, 0, 0, 0, buffer.ptr);
prepareFontInfo(hdc);
return !isNull();
}
version(Windows)
void prepareFontInfo(HDC hdc = null) {
if(font is null)
return;
TEXTMETRIC tm;
auto dc = hdc ? hdc : GetDC(null);
auto orig = SelectObject(dc, font);
GetTextMetrics(dc, &tm);
SelectObject(dc, orig);
if(hdc is null)
ReleaseDC(null, dc);
width_ = tm.tmAveCharWidth;
height_ = tm.tmHeight;
ascent_ = tm.tmAscent;
descent_ = tm.tmDescent;
// If this bit is set the font is a variable pitch font. If this bit is clear the font is a fixed pitch font. Note very carefully that those meanings are the opposite of what the constant name implies.
isMonospace_ = (tm.tmPitchAndFamily & TMPF_FIXED_PITCH) == 0;
}
/++
`name` is a font name, but it can also be a more complicated string parsed in an OS-specific way.
On X, you may prefix a name with `core:` to bypass the freetype engine causing this function to forward to [loadCoreX]. Otherwise,
it calls [loadXft] if the library is available. If the library or font is not available on Xft, it falls back on [loadCoreX].
On Windows, it forwards directly to [loadWin32].
Params:
name = font name. This is looked up by the operating system and may be interpreted differently across platforms or user machines and their preferences.
size = font size. This may be interpreted differently by different systems and different fonts. Size 0 means load a default, which may not exist and cause [isNull] to become true.
weight = approximate boldness, results may vary.
italic = try to get a slanted version of the given font.
History:
Xft support was added on November 13, 2020. It would only load core fonts. Xft inclusion changed font lookup and interpretation of the `size` parameter, requiring a major version bump. This caused release v9.0.
+/
bool load(string name, int size = 0, FontWeight weight = FontWeight.dontcare, bool italic = false) {
this.loadedInfo = LoadedInfo(name, size, weight, italic);
version(X11) {
version(with_xft) {
if(name.length > 5 && name[0 .. 5] == "core:") {
goto core;
}
if(loadXft(name, size, weight, italic))
return true;
// if xft fails, fallback to core to avoid breaking
// code that already depended on this.
}
core:
if(name.length > 5 && name[0 .. 5] == "core:") {
name = name[5 .. $];
}
return loadCoreX(name, size, weight, italic);
} else version(Windows) {
return loadWin32(name, size, weight, italic);
} else version(OSXCocoa) {
// FIXME
return false;
} else static assert(0);
}
private struct LoadedInfo {
string name;
int size;
FontWeight weight;
bool italic;
}
private LoadedInfo loadedInfo;
///
void unload() {
if(isNull())
return;
version(X11) {
auto display = XDisplayConnection.display;
if(display is null)
return;
version(with_xft) {
if(isXft) {
if(xftFont)
XftFontClose(display, xftFont);
isXft = false;
xftFont = null;
return;
}
}
if(font && font !is ScreenPainterImplementation.defaultfont)
XFreeFont(display, font);
if(fontset && fontset !is ScreenPainterImplementation.defaultfontset)
XFreeFontSet(display, fontset);
font = null;
fontset = null;
} else version(Windows) {
DeleteObject(font);
font = null;
} else version(OSXCocoa) {
// FIXME
} else static assert(0);
}
private bool isMonospace_;
/++
History:
Added January 16, 2021
+/
bool isMonospace() {
return isMonospace_;
}
/++
Returns the average width of the font, conventionally defined as the width of the lowercase 'x' character.
History:
Added March 26, 2020
Documented January 16, 2021
+/
int averageWidth() {
version(X11) {
return stringWidth("x");
} else version(Windows)
return width_;
else assert(0);
}
/++
Returns the width of the string as drawn on the specified window, or the default screen if the window is null.
History:
Added January 16, 2021
+/
int stringWidth(scope const(char)[] s, SimpleWindow window = null) {
// FIXME: what about tab?
if(isNull)
return 0;
version(X11) {
version(with_xft)
if(isXft && xftFont !is null) {
//return xftFont.max_advance_width;
XGlyphInfo extents;
XftTextExtentsUtf8(XDisplayConnection.get, xftFont, s.ptr, cast(int) s.length, &extents);
//import std.stdio; writeln(extents);
return extents.xOff;
}
if(font is null)
return 0;
else if(fontset) {
XRectangle rect;
Xutf8TextExtents(fontset, s.ptr, cast(int) s.length, null, &rect);
return rect.width;
} else {
return XTextWidth(font, s.ptr, cast(int) s.length);
}
} else version(Windows) {
WCharzBuffer buffer = WCharzBuffer(s);
return stringWidth(buffer.slice, window);
}
else assert(0);
}
version(Windows)
/// ditto
int stringWidth(scope const(wchar)[] s, SimpleWindow window = null) {
if(isNull)
return 0;
version(Windows) {
SIZE size;
prepareContext(window);
scope(exit) releaseContext();
GetTextExtentPoint32W(dc, s.ptr, cast(int) s.length, &size);
return size.cx;
} else {
// std.conv can do this easily but it is slow to import and i don't think it is worth it
static assert(0, "not implemented yet");
//return stringWidth(s, window);
}
}
private {
int prepRefcount;
version(Windows) {
HDC dc;
HANDLE orig;
HWND hwnd;
}
}
/++
[stringWidth] can be slow. This helps speed it up if you are doing a lot of calculations. Just prepareContext when you start this work and releaseContext when you are done. Important to release before too long though as it can be a scarce system resource.
History:
Added January 23, 2021
+/
void prepareContext(SimpleWindow window = null) {
prepRefcount++;
if(prepRefcount == 1) {
version(Windows) {
hwnd = window is null ? null : window.impl.hwnd;
dc = GetDC(hwnd);
orig = SelectObject(dc, font);
}
}
}
/// ditto
void releaseContext() {
prepRefcount--;
if(prepRefcount == 0) {
version(Windows) {
SelectObject(dc, orig);
ReleaseDC(hwnd, dc);
hwnd = null;
dc = null;
orig = null;
}
}
}
/+
FIXME: I think I need advance and kerning pair
int advance(dchar from, dchar to) { } // use dchar.init for first item in string
+/
/++
Returns the height of the font.
History:
Added March 26, 2020
Documented January 16, 2021
+/
int height() {
version(X11) {
version(with_xft)
if(isXft && xftFont !is null) {
return xftFont.ascent + xftFont.descent; // i don't use height here because it doesn't include the baseline pixel
}
if(font is null)
return 0;
return font.max_bounds.ascent + font.max_bounds.descent;
} else version(Windows)
return height_;
else assert(0);
}
private int ascent_;
private int descent_;
/++
Max ascent above the baseline.
History:
Added January 22, 2021
+/
int ascent() {
return ascent_;
}
/++
Max descent below the baseline.
History:
Added January 22, 2021
+/
int descent() {
return descent_;
}
/++
Loads the default font used by [ScreenPainter] if none others are loaded.
Returns:
This method mutates the `this` object, but then returns `this` for
easy chaining like:
---
auto font = foo.isNull ? foo : foo.loadDefault
---
History:
Added previously, but left unimplemented until January 24, 2021.
+/
OperatingSystemFont loadDefault() {
unload();
loadedInfo = LoadedInfo.init;
version(X11) {
// another option would be https://tronche.com/gui/x/xlib/graphics/font-metrics/XQueryFont.html
// but meh since sdpy does its own thing, this should be ok too
ScreenPainterImplementation.ensureDefaultFontLoaded();
this.font = ScreenPainterImplementation.defaultfont;
this.fontset = ScreenPainterImplementation.defaultfontset;
prepareFontInfo();
} else version(Windows) {
ScreenPainterImplementation.ensureDefaultFontLoaded();
this.font = ScreenPainterImplementation.defaultGuiFont;
prepareFontInfo();
} else throw new NotYetImplementedException();
return this;
}
///
bool isNull() {
version(OSXCocoa) throw new NotYetImplementedException(); else {
version(with_xft)
if(isXft)
return xftFont is null;
return font is null;
}
}
/* Metrics */
/+
GetABCWidth
GetKerningPairs
if I do it right, I can size it all here, and match
what happens when I draw the full string with the OS functions.
subclasses might do the same thing while getting the glyphs on images
struct GlyphInfo {
int glyph;
size_t stringIdxStart;
size_t stringIdxEnd;
Rectangle boundingBox;
}
GlyphInfo[] getCharBoxes() {
// XftTextExtentsUtf8
return null;
}
+/
~this() {
if(!thisIsGuiThread) return; // FIXME: leaks if multithreaded gc
unload();
}
}
version(Windows)
private string sliceCString(const(wchar)[] w) {
return makeUtf8StringFromWindowsString(cast(wchar*) w.ptr);
}
private inout(char)[] sliceCString(inout(char)* s) {
import core.stdc.string;
auto len = strlen(s);
return s[0 .. len];
}
/**
The 2D drawing proxy. You acquire one of these with [SimpleWindow.draw] rather
than constructing it directly. Then, it is reference counted so you can pass it
at around and when the last ref goes out of scope, the buffered drawing activities
are all carried out.
Most functions use the outlineColor instead of taking a color themselves.
ScreenPainter is reference counted and draws its buffer to the screen when its
final reference goes out of scope.
*/
struct ScreenPainter {
CapableOfBeingDrawnUpon window;
this(CapableOfBeingDrawnUpon window, NativeWindowHandle handle, bool manualInvalidations) {
this.window = window;
if(window.closed)
return; // null painter is now allowed so no need to throw anymore, this likely happens at the end of a program anyway
//currentClipRectangle = arsd.color.Rectangle(0, 0, window.width, window.height);
currentClipRectangle = arsd.color.Rectangle(short.min, short.min, short.max, short.max);
if(window.activeScreenPainter !is null) {
impl = window.activeScreenPainter;
if(impl.referenceCount == 0) {
impl.window = window;
impl.create(handle);
}
impl.manualInvalidations = manualInvalidations;
impl.referenceCount++;
// writeln("refcount ++ ", impl.referenceCount);
} else {
impl = new ScreenPainterImplementation;
impl.window = window;
impl.create(handle);
impl.referenceCount = 1;
impl.manualInvalidations = manualInvalidations;
window.activeScreenPainter = impl;
//import std.stdio; writeln("constructed");
}
copyActiveOriginals();
}
/++
EXPERIMENTAL. subject to change.
When you draw a cursor, you can draw this to notify your window of where it is,
for IME systems to use.
+/
void notifyCursorPosition(int x, int y, int width, int height) {
if(auto w = cast(SimpleWindow) window) {
w.setIMEPopupLocation(x + _originX + width, y + _originY + height);
}
}
/++
If you are using manual invalidations, this informs the
window system that a section needs to be redrawn.
If you didn't opt into manual invalidation, you don't
have to call this.
History:
Added December 30, 2021 (dub v10.5)
+/
void invalidateRect(Rectangle rect) {
if(impl is null) return;
// transform(rect)
rect.left += _originX;
rect.right += _originX;
rect.top += _originY;
rect.bottom += _originY;
impl.invalidateRect(rect);
}
private Pen originalPen;
private Color originalFillColor;
private arsd.color.Rectangle originalClipRectangle;
private OperatingSystemFont originalFont;
void copyActiveOriginals() {
if(impl is null) return;
originalPen = impl._activePen;
originalFillColor = impl._fillColor;
originalClipRectangle = impl._clipRectangle;
originalFont = impl._activeFont;
}
~this() {
if(impl is null) return;
impl.referenceCount--;
//writeln("refcount -- ", impl.referenceCount);
if(impl.referenceCount == 0) {
//import std.stdio; writeln("destructed");
impl.dispose();
*window.activeScreenPainter = ScreenPainterImplementation.init;
//import std.stdio; writeln("paint finished");
} else {
// there is still an active reference, reset stuff so the
// next user doesn't get weirdness via the reference
this.rasterOp = RasterOp.normal;
pen = originalPen;
fillColor = originalFillColor;
if(originalFont)
setFont(originalFont);
impl.setClipRectangle(originalClipRectangle.left, originalClipRectangle.top, originalClipRectangle.width, originalClipRectangle.height);
}
}
this(this) {
if(impl is null) return;
impl.referenceCount++;
//writeln("refcount ++ ", impl.referenceCount);
copyActiveOriginals();
}
private int _originX;
private int _originY;
@property int originX() { return _originX; }
@property int originY() { return _originY; }
@property int originX(int a) {
_originX = a;
return _originX;
}
@property int originY(int a) {
_originY = a;
return _originY;
}
arsd.color.Rectangle currentClipRectangle; // set BEFORE doing any transformations
private void transform(ref Point p) {
if(impl is null) return;
p.x += _originX;
p.y += _originY;
}
// this needs to be checked BEFORE the originX/Y transformation
private bool isClipped(Point p) {
return !currentClipRectangle.contains(p);
}
private bool isClipped(Point p, int width, int height) {
return !currentClipRectangle.overlaps(arsd.color.Rectangle(p, Size(width + 1, height + 1)));
}
private bool isClipped(Point p, Size s) {
return !currentClipRectangle.overlaps(arsd.color.Rectangle(p, Size(s.width + 1, s.height + 1)));
}
private bool isClipped(Point p, Point p2) {
// need to ensure the end points are actually included inside, so the +1 does that
return !currentClipRectangle.overlaps(arsd.color.Rectangle(p, p2 + Point(1, 1)));
}
/++
Sets the clipping region for drawing. If width == 0 && height == 0, disabled clipping.
Returns:
The old clip rectangle.
History:
Return value was `void` prior to May 10, 2021.
+/
arsd.color.Rectangle setClipRectangle(Point pt, int width, int height) {
if(impl is null) return currentClipRectangle;
if(pt == currentClipRectangle.upperLeft && width == currentClipRectangle.width && height == currentClipRectangle.height)
return currentClipRectangle; // no need to do anything
auto old = currentClipRectangle;
currentClipRectangle = arsd.color.Rectangle(pt, Size(width, height));
transform(pt);
impl.setClipRectangle(pt.x, pt.y, width, height);
return old;
}
/// ditto
arsd.color.Rectangle setClipRectangle(arsd.color.Rectangle rect) {
if(impl is null) return currentClipRectangle;
return setClipRectangle(rect.upperLeft, rect.width, rect.height);
}
///
void setFont(OperatingSystemFont font) {
if(impl is null) return;
impl.setFont(font);
}
///
int fontHeight() {
if(impl is null) return 0;
return impl.fontHeight();
}
private Pen activePen;
///
@property void pen(Pen p) {
if(impl is null) return;
activePen = p;
impl.pen(p);
}
///
@scriptable
@property void outlineColor(Color c) {
if(impl is null) return;
if(activePen.color == c)
return;
activePen.color = c;
impl.pen(activePen);
}
///
@scriptable
@property void fillColor(Color c) {
if(impl is null) return;
impl.fillColor(c);
}
///
@property void rasterOp(RasterOp op) {
if(impl is null) return;
impl.rasterOp(op);
}
void updateDisplay() {
// FIXME this should do what the dtor does
}
/// Scrolls the contents in the bounding rectangle by dx, dy. Positive dx means scroll left (make space available at the right), positive dy means scroll up (make space available at the bottom)
void scrollArea(Point upperLeft, int width, int height, int dx, int dy) {
if(impl is null) return;
if(isClipped(upperLeft, width, height)) return;
transform(upperLeft);
version(Windows) {
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb787589%28v=vs.85%29.aspx
RECT scroll = RECT(upperLeft.x, upperLeft.y, upperLeft.x + width, upperLeft.y + height);
RECT clip = scroll;
RECT uncovered;
HRGN hrgn;
if(!ScrollDC(impl.hdc, -dx, -dy, &scroll, &clip, hrgn, &uncovered))
throw new Exception("ScrollDC");
} else version(X11) {
// FIXME: clip stuff outside this rectangle
XCopyArea(impl.display, impl.d, impl.d, impl.gc, upperLeft.x, upperLeft.y, width, height, upperLeft.x - dx, upperLeft.y - dy);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
///
void clear(Color color = Color.white()) {
if(impl is null) return;
fillColor = color;
outlineColor = color;
drawRectangle(Point(0, 0), window.width, window.height);
}
/++
Draws a pixmap (represented by the [Sprite] class) on the drawable.
Params:
upperLeft = point on the window where the upper left corner of the image will be drawn
imageUpperLeft = point on the image to start the slice to draw
sliceSize = size of the slice of the image to draw on the window. If width or height is 0, it uses the entire width or height of the image.
History:
The `imageUpperLeft` and `sliceSize` parameters were added on March 11, 2021 (dub v9.3.0)
+/
version(OSXCocoa) {} else // NotYetImplementedException
void drawPixmap(Sprite s, Point upperLeft, Point imageUpperLeft = Point(0, 0), Size sliceSize = Size(0, 0)) {
if(impl is null) return;
if(isClipped(upperLeft, s.width, s.height)) return;
transform(upperLeft);
impl.drawPixmap(s, upperLeft.x, upperLeft.y, imageUpperLeft.x, imageUpperLeft.y, sliceSize.width, sliceSize.height);
}
///
void drawImage(Point upperLeft, Image i, Point upperLeftOfImage = Point(0, 0), int w = 0, int h = 0) {
if(impl is null) return;
//if(isClipped(upperLeft, w, h)) return; // FIXME
transform(upperLeft);
if(w == 0 || w > i.width)
w = i.width;
if(h == 0 || h > i.height)
h = i.height;
if(upperLeftOfImage.x < 0)
upperLeftOfImage.x = 0;
if(upperLeftOfImage.y < 0)
upperLeftOfImage.y = 0;
impl.drawImage(upperLeft.x, upperLeft.y, i, upperLeftOfImage.x, upperLeftOfImage.y, w, h);
}
///
Size textSize(in char[] text) {
if(impl is null) return Size(0, 0);
return impl.textSize(text);
}
/++
Draws a string in the window with the set font (see [setFont] to change it).
Params:
upperLeft = the upper left point of the bounding box of the text
text = the string to draw
lowerRight = the lower right point of the bounding box of the text. If 0, 0, there is no lower right bound.
alignment = A [arsd.docs.general_concepts#bitflags|combination] of [TextAlignment] flags
+/
@scriptable
void drawText(Point upperLeft, in char[] text, Point lowerRight = Point(0, 0), uint alignment = 0) {
if(impl is null) return;
if(lowerRight.x != 0 || lowerRight.y != 0) {
if(isClipped(upperLeft, lowerRight)) return;
transform(lowerRight);
} else {
if(isClipped(upperLeft, textSize(text))) return;
}
transform(upperLeft);
impl.drawText(upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y, text, alignment);
}
/++
Draws text using a custom font.
This is still MAJOR work in progress.
Creating a [DrawableFont] can be tricky and require additional dependencies.
+/
void drawText(DrawableFont font, Point upperLeft, in char[] text) {
if(impl is null) return;
if(isClipped(upperLeft, Point(int.max, int.max))) return;
transform(upperLeft);
font.drawString(this, upperLeft, text);
}
version(Windows)
void drawText(Point upperLeft, scope const(wchar)[] text) {
if(impl is null) return;
if(isClipped(upperLeft, Point(int.max, int.max))) return;
transform(upperLeft);
if(text.length && text[$-1] == '\n')
text = text[0 .. $-1]; // tailing newlines are weird on windows...
TextOutW(impl.hdc, upperLeft.x, upperLeft.y, text.ptr, cast(int) text.length);
}
static struct TextDrawingContext {
Point boundingBoxUpperLeft;
Point boundingBoxLowerRight;
Point currentLocation;
Point lastDrewUpperLeft;
Point lastDrewLowerRight;
// how do i do right aligned rich text?
// i kinda want to do a pre-made drawing then right align
// draw the whole block.
//
// That's exactly the diff: inline vs block stuff.
// I need to get coordinates of an inline section out too,
// not just a bounding box, but a series of bounding boxes
// should be ok. Consider what's needed to detect a click
// on a link in the middle of a paragraph breaking a line.
//
// Generally, we should be able to get the rectangles of
// any portion we draw.
//
// It also needs to tell what text is left if it overflows
// out of the box, so we can do stuff like float images around
// it. It should not attempt to draw a letter that would be
// clipped.
//
// I might also turn off word wrap stuff.
}
void drawText(TextDrawingContext context, in char[] text, uint alignment = 0) {
if(impl is null) return;
// FIXME
}
/// Drawing an individual pixel is slow. Avoid it if possible.
void drawPixel(Point where) {
if(impl is null) return;
if(isClipped(where)) return;
transform(where);
impl.drawPixel(where.x, where.y);
}
/// Draws a pen using the current pen / outlineColor
@scriptable
void drawLine(Point starting, Point ending) {
if(impl is null) return;
if(isClipped(starting, ending)) return;
transform(starting);
transform(ending);
impl.drawLine(starting.x, starting.y, ending.x, ending.y);
}
/// Draws a rectangle using the current pen/outline color for the border and brush/fill color for the insides
/// The outer lines, inclusive of x = 0, y = 0, x = width - 1, and y = height - 1 are drawn with the outlineColor
/// The rest of the pixels are drawn with the fillColor. If fillColor is transparent, those pixels are not drawn.
@scriptable
void drawRectangle(Point upperLeft, int width, int height) {
if(impl is null) return;
if(isClipped(upperLeft, width, height)) return;
transform(upperLeft);
impl.drawRectangle(upperLeft.x, upperLeft.y, width, height);
}
/// ditto
void drawRectangle(Point upperLeft, Size size) {
if(impl is null) return;
if(isClipped(upperLeft, size.width, size.height)) return;
transform(upperLeft);
impl.drawRectangle(upperLeft.x, upperLeft.y, size.width, size.height);
}
/// ditto
void drawRectangle(Point upperLeft, Point lowerRightInclusive) {
if(impl is null) return;
if(isClipped(upperLeft, lowerRightInclusive + Point(1, 1))) return;
transform(upperLeft);
transform(lowerRightInclusive);
impl.drawRectangle(upperLeft.x, upperLeft.y,
lowerRightInclusive.x - upperLeft.x + 1, lowerRightInclusive.y - upperLeft.y + 1);
}
// overload added on May 12, 2021
/// ditto
void drawRectangle(Rectangle rect) {
drawRectangle(rect.upperLeft, rect.size);
}
/// Arguments are the points of the bounding rectangle
void drawEllipse(Point upperLeft, Point lowerRight) {
if(impl is null) return;
if(isClipped(upperLeft, lowerRight)) return;
transform(upperLeft);
transform(lowerRight);
impl.drawEllipse(upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y);
}
/++
start and finish are units of degrees * 64
History:
The Windows implementation didn't match the Linux implementation until September 24, 2021.
They still don't exactly match in outlining the arc with straight lines (Windows does, Linux doesn't for now).
+/
void drawArc(Point upperLeft, int width, int height, int start, int finish) {
if(impl is null) return;
// FIXME: not actually implemented
if(isClipped(upperLeft, width, height)) return;
transform(upperLeft);
impl.drawArc(upperLeft.x, upperLeft.y, width, height, start, finish);
}
/// this function draws a circle with the drawEllipse() function above, it requires the upper left point and the radius
void drawCircle(Point upperLeft, int diameter) {
drawEllipse(upperLeft, Point(upperLeft.x + diameter, upperLeft.y + diameter));
}
/// .
void drawPolygon(Point[] vertexes) {
if(impl is null) return;
assert(vertexes.length);
int minX = int.max, minY = int.max, maxX = int.min, maxY = int.min;
foreach(ref vertex; vertexes) {
if(vertex.x < minX)
minX = vertex.x;
if(vertex.y < minY)
minY = vertex.y;
if(vertex.x > maxX)
maxX = vertex.x;
if(vertex.y > maxY)
maxY = vertex.y;
transform(vertex);
}
if(isClipped(Point(minX, maxY), Point(maxX + 1, maxY + 1))) return;
impl.drawPolygon(vertexes);
}
/// ditto
void drawPolygon(Point[] vertexes...) {
if(impl is null) return;
drawPolygon(vertexes);
}
// and do a draw/fill in a single call maybe. Windows can do it... but X can't, though it could do two calls.
//mixin NativeScreenPainterImplementation!() impl;
// HACK: if I mixin the impl directly, it won't let me override the copy
// constructor! The linker complains about there being multiple definitions.
// I'll make the best of it and reference count it though.
ScreenPainterImplementation* impl;
}
// HACK: I need a pointer to the implementation so it's separate
struct ScreenPainterImplementation {
CapableOfBeingDrawnUpon window;
int referenceCount;
mixin NativeScreenPainterImplementation!();
}
// FIXME: i haven't actually tested the sprite class on MS Windows
/**
Sprites are optimized for fast drawing on the screen, but slow for direct pixel
access. They are best for drawing a relatively unchanging image repeatedly on the screen.
On X11, this corresponds to an `XPixmap`. On Windows, it still uses a bitmap,
though I'm not sure that's ideal and the implementation might change.
You create one by giving a window and an image. It optimizes for that window,
and copies the image into it to use as the initial picture. Creating a sprite
can be quite slow (especially over a network connection) so you should do it
as little as possible and just hold on to your sprite handles after making them.
simpledisplay does try to do its best though, using the XSHM extension if available,
but you should still write your code as if it will always be slow.
Then you can use `sprite.drawAt(painter, point);` to draw it, which should be
a fast operation - much faster than drawing the Image itself every time.
`Sprite` represents a scarce resource which should be freed when you
are done with it. Use the `dispose` method to do this. Do not use a `Sprite`
after it has been disposed. If you are unsure about this, don't take chances,
just let the garbage collector do it for you. But ideally, you can manage its
lifetime more efficiently.
$(NOTE `Sprite`, like the rest of simpledisplay's `ScreenPainter`, does not
support alpha blending in its drawing at this time. That might change in the
future, but if you need alpha blending right now, use OpenGL instead. See
`gamehelpers.d` for a similar class to `Sprite` that uses OpenGL: `OpenGlTexture`.)
Update: on April 23, 2021, I finally added alpha blending support. You must opt
in by setting the enableAlpha = true in the constructor.
*/
version(OSXCocoa) {} else // NotYetImplementedException
class Sprite : CapableOfBeingDrawnUpon {
///
ScreenPainter draw() {
return ScreenPainter(this, handle, false);
}
/++
Copies the sprite's current state into a [TrueColorImage].
Be warned: this can be a very slow operation
History:
Actually implemented on March 14, 2021
+/
TrueColorImage takeScreenshot() {
return trueColorImageFromNativeHandle(handle, width, height);
}
void delegate() paintingFinishedDg() { return null; }
bool closed() { return false; }
ScreenPainterImplementation* activeScreenPainter_;
protected ScreenPainterImplementation* activeScreenPainter() { return activeScreenPainter_; }
protected void activeScreenPainter(ScreenPainterImplementation* i) { activeScreenPainter_ = i; }
version(Windows)
private ubyte* rawData;
// FIXME: sprites are lost when disconnecting from X! We need some way to invalidate them...
// ditto on the XPicture stuff
version(X11) {
private static XRenderPictFormat* RGB24;
private static XRenderPictFormat* ARGB32;
private Picture xrenderPicture;
}
version(X11)
private static void requireXRender() {
if(!XRenderLibrary.loadAttempted) {
XRenderLibrary.loadDynamicLibrary();
}
if(!XRenderLibrary.loadSuccessful)
throw new Exception("XRender library load failure");
auto display = XDisplayConnection.get;
// FIXME: if we migrate X displays, these need to be changed
if(RGB24 is null)
RGB24 = XRenderFindStandardFormat(display, PictStandardRGB24);
if(ARGB32 is null)
ARGB32 = XRenderFindStandardFormat(display, PictStandardARGB32);
}
protected this() {}
this(SimpleWindow win, int width, int height, bool enableAlpha = false) {
this._width = width;
this._height = height;
this.enableAlpha = enableAlpha;
version(X11) {
auto display = XDisplayConnection.get();
if(enableAlpha) {
requireXRender();
}
handle = XCreatePixmap(display, cast(Drawable) win.window, width, height, enableAlpha ? 32 : DefaultDepthOfDisplay(display));
if(enableAlpha) {
XRenderPictureAttributes attrs;
xrenderPicture = XRenderCreatePicture(display, handle, ARGB32, 0, &attrs);
}
} else version(Windows) {
version(CRuntime_DigitalMars) {
//if(enableAlpha)
//throw new Exception("Alpha support not available, try recompiling with -m32mscoff");
}
BITMAPINFO infoheader;
infoheader.bmiHeader.biSize = infoheader.bmiHeader.sizeof;
infoheader.bmiHeader.biWidth = width;
infoheader.bmiHeader.biHeight = height;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biBitCount = enableAlpha ? 32 : 24;
infoheader.bmiHeader.biCompression = BI_RGB;
// FIXME: this should prolly be a device dependent bitmap...
handle = CreateDIBSection(
null,
&infoheader,
DIB_RGB_COLORS,
cast(void**) &rawData,
null,
0);
if(handle is null)
throw new Exception("couldn't create pixmap");
}
}
/// Makes a sprite based on the image with the initial contents from the Image
this(SimpleWindow win, Image i) {
this(win, i.width, i.height, i.enableAlpha);
version(X11) {
auto display = XDisplayConnection.get();
auto gc = XCreateGC(display, this.handle, 0, null);
scope(exit) XFreeGC(display, gc);
if(i.usingXshm)
XShmPutImage(display, cast(Drawable) handle, gc, i.handle, 0, 0, 0, 0, i.width, i.height, false);
else
XPutImage(display, cast(Drawable) handle, gc, i.handle, 0, 0, 0, 0, i.width, i.height);
} else version(Windows) {
auto itemsPerLine = enableAlpha ? (4 * width) : (((cast(int) width * 3 + 3) / 4) * 4);
auto arrLength = itemsPerLine * height;
rawData[0..arrLength] = i.rawData[0..arrLength];
} else version(OSXCocoa) {
// FIXME: I have no idea if this is even any good
ubyte* rawData;
auto colorSpace = CGColorSpaceCreateDeviceRGB();
context = CGBitmapContextCreate(null, width, height, 8, 4*width,
colorSpace,
kCGImageAlphaPremultipliedLast
|kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
rawData = CGBitmapContextGetData(context);
auto rdl = (width * height * 4);
rawData[0 .. rdl] = i.rawData[0 .. rdl];
} else static assert(0);
}
/++
Draws the image on the specified painter at the specified point. The point is the upper-left point where the image will be drawn.
Params:
where = point on the window where the upper left corner of the image will be drawn
imageUpperLeft = point on the image to start the slice to draw
sliceSize = size of the slice of the image to draw on the window. If width or height is 0, it uses the entire width or height of the image.
History:
The `imageUpperLeft` and `sliceSize` parameters were added on March 11, 2021 (dub v9.3.0)
+/
void drawAt(ScreenPainter painter, Point where, Point imageUpperLeft = Point(0, 0), Size sliceSize = Size(0, 0)) {
painter.drawPixmap(this, where, imageUpperLeft, sliceSize);
}
/// Call this when you're ready to get rid of it
void dispose() {
version(X11) {
staticDispose(xrenderPicture, handle);
xrenderPicture = None;
handle = None;
} else version(Windows) {
staticDispose(handle);
handle = null;
} else version(OSXCocoa) {
staticDispose(context);
context = null;
} else static assert(0);
}
version(X11)
static void staticDispose(Picture xrenderPicture, Pixmap handle) {
if(xrenderPicture)
XRenderFreePicture(XDisplayConnection.get, xrenderPicture);
if(handle)
XFreePixmap(XDisplayConnection.get(), handle);
}
else version(Windows)
static void staticDispose(HBITMAP handle) {
if(handle)
DeleteObject(handle);
}
else version(OSXCocoa)
static void staticDispose(CGContextRef context) {
if(context)
CGContextRelease(context);
}
~this() {
version(X11) { if(xrenderPicture || handle)
cleanupQueue.queue!staticDispose(xrenderPicture, handle);
} else version(Windows) { if(handle)
cleanupQueue.queue!staticDispose(handle);
} else version(OSXCocoa) { if(context)
cleanupQueue.queue!staticDispose(context);
} else static assert(0);
}
///
final @property int width() { return _width; }
///
final @property int height() { return _height; }
///
static Sprite fromMemoryImage(SimpleWindow win, MemoryImage img, bool enableAlpha = false) {
return new Sprite(win, Image.fromMemoryImage(img, enableAlpha));
}
auto nativeHandle() {
return handle;
}
private:
int _width;
int _height;
bool enableAlpha;
version(X11)
Pixmap handle;
else version(Windows)
HBITMAP handle;
else version(OSXCocoa)
CGContextRef context;
else static assert(0);
}
/++
Represents a display-side gradient pseudo-image. Actually construct it with [LinearGradient], [RadialGradient], or [ConicalGradient].
History:
Added November 20, 2021 (dub v10.4)
+/
abstract class Gradient : Sprite {
protected this(int w, int h) {
version(X11) {
Sprite.requireXRender();
super();
enableAlpha = true;
_width = w;
_height = h;
} else version(Windows) {
super(null, w, h, true); // on Windows i'm just making a bitmap myself
}
}
version(Windows)
final void forEachPixel(scope Color delegate(int x, int y) dg) {
auto ptr = rawData;
foreach(j; 0 .. _height)
foreach(i; 0 .. _width) {
auto color = dg(i, _height - j - 1); // cuz of upside down bitmap
*rawData = (color.a * color.b) / 255; rawData++;
*rawData = (color.a * color.g) / 255; rawData++;
*rawData = (color.a * color.r) / 255; rawData++;
*rawData = color.a; rawData++;
}
}
version(X11)
protected void helper(scope Stop[] stops, scope Picture delegate(scope XFixed[] stopsPositions, scope XRenderColor[] colors) dg) {
assert(stops.length > 0);
assert(stops.length <= 16, "I got lazy with buffers");
XFixed[16] stopsPositions = void;
XRenderColor[16] colors = void;
foreach(idx, stop; stops) {
stopsPositions[idx] = cast(int)(stop.percentage * ushort.max);
auto c = stop.c;
colors[idx] = XRenderColor(
cast(ushort)(c.r * ushort.max / 255),
cast(ushort)(c.g * ushort.max / 255),
cast(ushort)(c.b * ushort.max / 255),
cast(ushort)(c.a * ubyte.max) // max value here is fractional
);
}
xrenderPicture = dg(stopsPositions, colors);
}
///
static struct Stop {
float percentage; /// between 0 and 1.0
Color c;
}
}
/++
Creates a linear gradient between p1 and p2.
X ONLY RIGHT NOW
History:
Added November 20, 2021 (dub v10.4)
Bugs:
Not yet implemented on Windows.
+/
class LinearGradient : Gradient {
/++
+/
this(Point p1, Point p2, Stop[] stops...) {
super(p2.x, p2.y);
version(X11) {
XLinearGradient gradient;
gradient.p1 = XPointFixed(p1.x * ushort.max, p1.y * ushort.max);
gradient.p2 = XPointFixed(p2.x * ushort.max, p2.y * ushort.max);
helper(stops, (scope XFixed[] stopsPositions, scope XRenderColor[] colors) {
return XRenderCreateLinearGradient(
XDisplayConnection.get,
&gradient,
stopsPositions.ptr,
colors.ptr,
cast(int) stops.length);
});
} else version(Windows) {
// FIXME
forEachPixel((int x, int y) {
import core.stdc.math;
//sqrtf(
return Color.transparent;
// return Color(x * 2, y * 2, 0, 128); // this result is so beautiful
});
}
}
}
/++
A conical gradient goes from color to color around a circumference from a center point.
X ONLY RIGHT NOW
History:
Added November 20, 2021 (dub v10.4)
Bugs:
Not yet implemented on Windows.
+/
class ConicalGradient : Gradient {
/++
+/
this(Point center, float angleInDegrees, Stop[] stops...) {
super(center.x * 2, center.y * 2);
version(X11) {
XConicalGradient gradient;
gradient.center = XPointFixed(center.x * ushort.max, center.y * ushort.max);
gradient.angle = cast(int)(angleInDegrees * ushort.max);
helper(stops, (scope XFixed[] stopsPositions, scope XRenderColor[] colors) {
return XRenderCreateConicalGradient(
XDisplayConnection.get,
&gradient,
stopsPositions.ptr,
colors.ptr,
cast(int) stops.length);
});
} else version(Windows) {
// FIXME
forEachPixel((int x, int y) {
import core.stdc.math;
//sqrtf(
return Color.transparent;
// return Color(x * 2, y * 2, 0, 128); // this result is so beautiful
});
}
}
}
/++
A radial gradient goes from color to color based on distance from the center.
It is like rings of color.
X ONLY RIGHT NOW
More specifically, you create two circles: an inner circle and an outer circle.
The gradient is only drawn in the area outside the inner circle but inside the outer
circle. The closest line between those two circles forms the line for the gradient
and the stops are calculated the same as the [LinearGradient]. Then it just sweeps around.
History:
Added November 20, 2021 (dub v10.4)
Bugs:
Not yet implemented on Windows.
+/
class RadialGradient : Gradient {
/++
+/
this(Point innerCenter, float innerRadius, Point outerCenter, float outerRadius, Stop[] stops...) {
super(cast(int)(outerCenter.x + outerRadius + 0.5), cast(int)(outerCenter.y + outerRadius + 0.5));
version(X11) {
XRadialGradient gradient;
gradient.inner = XCircle(innerCenter.x * ushort.max, innerCenter.y * ushort.max, cast(int) (innerRadius * ushort.max));
gradient.outer = XCircle(outerCenter.x * ushort.max, outerCenter.y * ushort.max, cast(int) (outerRadius * ushort.max));
helper(stops, (scope XFixed[] stopsPositions, scope XRenderColor[] colors) {
return XRenderCreateRadialGradient(
XDisplayConnection.get,
&gradient,
stopsPositions.ptr,
colors.ptr,
cast(int) stops.length);
});
} else version(Windows) {
// FIXME
forEachPixel((int x, int y) {
import core.stdc.math;
//sqrtf(
return Color.transparent;
// return Color(x * 2, y * 2, 0, 128); // this result is so beautiful
});
}
}
}
/+
NOT IMPLEMENTED
A display-stored image optimized for relatively quick drawing, like
[Sprite], but this one supports alpha channel blending and does NOT
support direct drawing upon it with a [ScreenPainter].
You can think of it as an [arsd.game.OpenGlTexture] for usage with a
plain [ScreenPainter]... sort of.
On X11, it requires the Xrender extension and library. This is available
almost everywhere though.
History:
Added November 14, 2020 but NOT ACTUALLY IMPLEMENTED
+/
version(none)
class AlphaSprite {
/++
Copies the given image into it.
+/
this(MemoryImage img) {
if(!XRenderLibrary.loadAttempted) {
XRenderLibrary.loadDynamicLibrary();
// FIXME: this needs to be reconstructed when the X server changes
repopulateX();
}
if(!XRenderLibrary.loadSuccessful)
throw new Exception("XRender library load failure");
// I probably need to put the alpha mask in a separate Picture
// ugh
// maybe the Sprite itself can have an alpha bitmask anyway
auto display = XDisplayConnection.get();
pixmap = XCreatePixmap(display, cast(Drawable) win.window, width, height, DefaultDepthOfDisplay(display));
XRenderPictureAttributes attrs;
handle = XRenderCreatePicture(
XDisplayConnection.get,
pixmap,
RGBA,
0,
&attrs
);
}
// maybe i'll use the create gradient functions too with static factories..
void drawAt(ScreenPainter painter, Point where) {
//painter.drawPixmap(this, where);
XRenderPictureAttributes attrs;
auto pic = XRenderCreatePicture(
XDisplayConnection.get,
painter.impl.d,
RGB,
0,
&attrs
);
XRenderComposite(
XDisplayConnection.get,
3, // PictOpOver
handle,
None,
pic,
0, // src
0,
0, // mask
0,
10, // dest
10,
100, // width
100
);
/+
XRenderFreePicture(
XDisplayConnection.get,
pic
);
XRenderFreePicture(
XDisplayConnection.get,
fill
);
+/
// on Windows you can stretch but Xrender still can't :(
}
static XRenderPictFormat* RGB;
static XRenderPictFormat* RGBA;
static void repopulateX() {
auto display = XDisplayConnection.get;
RGB = XRenderFindStandardFormat(display, PictStandardRGB24);
RGBA = XRenderFindStandardFormat(display, PictStandardARGB32);
}
XPixmap pixmap;
Picture handle;
}
///
interface CapableOfBeingDrawnUpon {
///
ScreenPainter draw();
///
int width();
///
int height();
protected ScreenPainterImplementation* activeScreenPainter();
protected void activeScreenPainter(ScreenPainterImplementation*);
bool closed();
void delegate() paintingFinishedDg();
/// Be warned: this can be a very slow operation
TrueColorImage takeScreenshot();
}
/// Flushes any pending gui buffers. Necessary if you are using with_eventloop with X - flush after you create your windows but before you call [arsd.eventloop.loop].
void flushGui() {
version(X11) {
auto dpy = XDisplayConnection.get();
XLockDisplay(dpy);
scope(exit) XUnlockDisplay(dpy);
XFlush(dpy);
}
}
/++
Runs the given code in the GUI thread when its event loop
is available, blocking until it completes. This allows you
to create and manipulate windows from another thread without
invoking undefined behavior.
If this is the gui thread, it runs the code immediately.
If no gui thread exists yet, the current thread is assumed
to be it. Attempting to create windows or run the event loop
in any other thread will cause an assertion failure.
$(TIP
Did you know you can use UFCS on delegate literals?
() {
// code here
}.runInGuiThread;
)
Returns:
`true` if the function was called, `false` if it was not.
The function may not be called because the gui thread had
already terminated by the time you called this.
History:
Added April 10, 2020 (v7.2.0)
Return value added and implementation tweaked to avoid locking
at program termination on February 24, 2021 (v9.2.1).
+/
bool runInGuiThread(scope void delegate() dg) @trusted {
claimGuiThread();
if(thisIsGuiThread) {
dg();
return true;
}
if(guiThreadTerminating)
return false;
import core.sync.semaphore;
static Semaphore sc;
if(sc is null)
sc = new Semaphore();
static RunQueueMember* rqm;
if(rqm is null)
rqm = new RunQueueMember;
rqm.dg = cast(typeof(rqm.dg)) dg;
rqm.signal = sc;
rqm.thrown = null;
synchronized(runInGuiThreadLock) {
runInGuiThreadQueue ~= rqm;
}
if(!SimpleWindow.eventWakeUp())
throw new Error("runInGuiThread impossible; eventWakeUp failed");
rqm.signal.wait();
auto t = rqm.thrown;
if(t)
throw t;
return true;
}
// note it runs sync if this is the gui thread....
void runInGuiThreadAsync(void delegate() dg, void delegate(Exception) nothrow handleError = null) nothrow {
claimGuiThread();
try {
if(thisIsGuiThread) {
dg();
return;
}
if(guiThreadTerminating)
return;
RunQueueMember* rqm = new RunQueueMember;
rqm.dg = cast(typeof(rqm.dg)) dg;
rqm.signal = null;
rqm.thrown = null;
synchronized(runInGuiThreadLock) {
runInGuiThreadQueue ~= rqm;
}
if(!SimpleWindow.eventWakeUp())
throw new Error("runInGuiThread impossible; eventWakeUp failed");
} catch(Exception e) {
if(handleError)
handleError(e);
}
}
private void runPendingRunInGuiThreadDelegates() {
more:
RunQueueMember* next;
synchronized(runInGuiThreadLock) {
if(runInGuiThreadQueue.length) {
next = runInGuiThreadQueue[0];
runInGuiThreadQueue = runInGuiThreadQueue[1 .. $];
} else {
next = null;
}
}
if(next) {
try {
next.dg();
next.thrown = null;
} catch(Throwable t) {
next.thrown = t;
}
if(next.signal)
next.signal.notify();
goto more;
}
}
private void claimGuiThread() nothrow {
import core.atomic;
if(cas(&guiThreadExists_, false, true))
thisIsGuiThread = true;
}
private struct RunQueueMember {
void delegate() dg;
import core.sync.semaphore;
Semaphore signal;
Throwable thrown;
}
private __gshared RunQueueMember*[] runInGuiThreadQueue;
private __gshared Object runInGuiThreadLock = new Object; // intentional CTFE
private bool thisIsGuiThread = false;
private shared bool guiThreadExists_ = false;
private shared bool guiThreadTerminating = false;
/++
Returns `true` if a gui thread exists, that is, a thread running the simpledisplay.d
event loop. All windows must be exclusively created and managed by a single thread.
If no gui thread exists, simpledisplay.d will automatically adopt the current thread
when you call one of its constructors.
If a gui thread exists, you should check [thisThreadRunningGui] to see if it is this
one. If so, you can run gui functions on it. If not, don't. The helper functions
[runInGuiThread] and [runInGuiThreadAsync] can be used to help you with this automatically.
The reason this function is available is in case you want to message pass between a gui
thread and your current thread. If no gui thread exists or if this is the gui thread,
you're liable to deadlock when trying to communicate since you'd end up talking to yourself.
History:
Added December 3, 2021 (dub v10.5)
+/
public bool guiThreadExists() {
return guiThreadExists_;
}
/++
Returns `true` if this thread is either running or set to be running the
simpledisplay.d gui core event loop because it owns windows.
It is important to keep gui-related functionality in the right thread, so you will
want to `runInGuiThread` when you call them (with some specific exceptions called
out in those specific functions' documentation). Notably, all windows must be
created and managed only from the gui thread.
Will return false if simpledisplay's other functions haven't been called
yet; check [guiThreadExists] in addition to this.
History:
Added December 3, 2021 (dub v10.5)
+/
public bool thisThreadRunningGui() {
return thisIsGuiThread;
}
/++
Function to help temporarily print debugging info. It will bypass any stdout/err redirection
and go to the controlling tty or console (attaching to the parent and/or allocating one as
needed on Windows. Please note it may overwrite output from other programs in the parent and the
allocated one will not survive if your program crashes. Use the `fileOverride` to print to a log
file instead if you are in one of those situations).
It does not support outputting very many types; just strings and ints are likely to actually work.
It will perform very slowly and swallows any errors that may occur. Moreover, the specific output
is unspecified meaning I can change it at any time. The only point of this function is to help
in temporary use for printf-style debugging. It is NOT nogc, but you can use the `debug` keyword
and the compiler will cheat for you. It is, however, formally nothrow and trusted to ease its use
in those contexts.
$(WARNING
I reserve the right to change this function at any time. You can use it if it helps you
but do not rely on it for anything permanent.
)
History:
Added December 3, 2021. Not formally supported under any stable tag.
+/
void sdpyPrintDebugString(string fileOverride = null, T...)(T t) nothrow @trusted {
try {
version(Windows) {
import core.sys.windows.wincon;
if(!AttachConsole(ATTACH_PARENT_PROCESS))
AllocConsole();
const(char)* fn = "CONOUT$";
} else version(Posix) {
const(char)* fn = "/dev/tty";
} else static assert(0, "Function not implemented for your system");
if(fileOverride.length)
fn = fileOverride.ptr;
import core.stdc.stdio;
auto fp = fopen(fn, "wt");
if(fp is null) return;
scope(exit) fclose(fp);
string str;
foreach(item; t) {
static if(is(typeof(item) : const(char)[]))
str ~= item;
else
str ~= toInternal!string(item);
str ~= " ";
}
str ~= "\n";
fwrite(str.ptr, 1, str.length, fp);
fflush(fp);
} catch(Exception e) {
// sorry no hope
}
}
private void guiThreadFinalize() {
assert(thisIsGuiThread);
guiThreadTerminating = true; // don't add any more from this point on
runPendingRunInGuiThreadDelegates();
}
/+
interface IPromise {
void reportProgress(int current, int max, string message);
/+ // not formally in cuz of templates but still
IPromise Then();
IPromise Catch();
IPromise Finally();
+/
}
/+
auto promise = async({ ... });
promise.Then(whatever).
Then(whateverelse).
Catch((exception) { });
A promise is run inside a fiber and it looks something like:
try {
auto res = whatever();
auto res2 = whateverelse(res);
} catch(Exception e) {
{ }(e);
}
When a thing succeeds, it is passed as an arg to the next
+/
class Promise(T) : IPromise {
auto Then() { return null; }
auto Catch() { return null; }
auto Finally() { return null; }
// wait for it to resolve and return the value, or rethrow the error if that occurred.
// cannot be called from the gui thread, but this is caught at runtime instead of compile time.
T await();
}
interface Task {
}
interface Resolvable(T) : Task {
void run();
void resolve(T);
Resolvable!T then(void delegate(T)); // returns a new promise
Resolvable!T error(Throwable); // js catch
Resolvable!T completed(); // js finally
}
/++
Runs `work` in a helper thread and sends its return value back to the main gui
thread as the argument to `uponCompletion`. If `work` throws, the exception is
sent to the `uponThrown` if given, or if null, rethrown from the event loop to
kill the program.
You can call reportProgress(position, max, message) to update your parent window
on your progress.
I should also use `shared` methods. FIXME
History:
Added March 6, 2021 (dub version 9.3).
+/
void runInWorkerThread(T)(T delegate(Task) work, void delegate(T) uponCompletion) {
uponCompletion(work(null));
}
+/
/// Used internal to dispatch events to various classes.
interface CapableOfHandlingNativeEvent {
NativeEventHandler getNativeEventHandler();
/*private*//*protected*/ __gshared CapableOfHandlingNativeEvent[NativeWindowHandle] nativeHandleMapping;
version(X11) {
// if this is impossible, you are allowed to just throw from it
// Note: if you call it from another object, set a flag cuz the manger will call you again
void recreateAfterDisconnect();
// discard any *connection specific* state, but keep enough that you
// can be recreated if possible. discardConnectionState() is always called immediately
// before recreateAfterDisconnect(), so you can set a flag there to decide if
// you need initialization order
void discardConnectionState();
}
}
version(X11)
/++
State of keys on mouse events, especially motion.
Do not trust the actual integer values in this, they are platform-specific. Always use the names.
+/
enum ModifierState : uint {
shift = 1, ///
capsLock = 2, ///
ctrl = 4, ///
alt = 8, /// Not always available on Windows
windows = 64, /// ditto
numLock = 16, ///
leftButtonDown = 256, /// these aren't available on Windows for key events, so don't use them for that unless your app is X only.
middleButtonDown = 512, /// ditto
rightButtonDown = 1024, /// ditto
}
else version(Windows)
/// ditto
enum ModifierState : uint {
shift = 4, ///
ctrl = 8, ///
// i'm not sure if the next two are available
alt = 256, /// not always available on Windows
windows = 512, /// ditto
capsLock = 1024, ///
numLock = 2048, ///
leftButtonDown = 1, /// not available on key events
middleButtonDown = 16, /// ditto
rightButtonDown = 2, /// ditto
backButtonDown = 0x20, /// not available on X
forwardButtonDown = 0x40, /// ditto
}
else version(OSXCocoa)
// FIXME FIXME NotYetImplementedException
enum ModifierState : uint {
shift = 1, ///
capsLock = 2, ///
ctrl = 4, ///
alt = 8, /// Not always available on Windows
windows = 64, /// ditto
numLock = 16, ///
leftButtonDown = 256, /// these aren't available on Windows for key events, so don't use them for that unless your app is X only.
middleButtonDown = 512, /// ditto
rightButtonDown = 1024, /// ditto
}
/// The names assume a right-handed mouse. These are bitwise combined on the events that use them.
enum MouseButton : int {
none = 0,
left = 1, ///
right = 2, ///
middle = 4, ///
wheelUp = 8, ///
wheelDown = 16, ///
backButton = 32, /// often found on the thumb and used for back in browsers
forwardButton = 64, /// often found on the thumb and used for forward in browsers
}
version(X11) {
// FIXME: match ASCII whenever we can. Most of it is already there,
// but there's a few exceptions and mismatches with Windows
/// Do not trust the numeric values as they are platform-specific. Always use the symbolic name.
enum Key {
Escape = 0xff1b, ///
F1 = 0xffbe, ///
F2 = 0xffbf, ///
F3 = 0xffc0, ///
F4 = 0xffc1, ///
F5 = 0xffc2, ///
F6 = 0xffc3, ///
F7 = 0xffc4, ///
F8 = 0xffc5, ///
F9 = 0xffc6, ///
F10 = 0xffc7, ///
F11 = 0xffc8, ///
F12 = 0xffc9, ///
PrintScreen = 0xff61, ///
ScrollLock = 0xff14, ///
Pause = 0xff13, ///
Grave = 0x60, /// The $(BACKTICK) ~ key
// number keys across the top of the keyboard
N1 = 0x31, /// Number key atop the keyboard
N2 = 0x32, ///
N3 = 0x33, ///
N4 = 0x34, ///
N5 = 0x35, ///
N6 = 0x36, ///
N7 = 0x37, ///
N8 = 0x38, ///
N9 = 0x39, ///
N0 = 0x30, ///
Dash = 0x2d, ///
Equals = 0x3d, ///
Backslash = 0x5c, /// The \ | key
Backspace = 0xff08, ///
Insert = 0xff63, ///
Home = 0xff50, ///
PageUp = 0xff55, ///
Delete = 0xffff, ///
End = 0xff57, ///
PageDown = 0xff56, ///
Up = 0xff52, ///
Down = 0xff54, ///
Left = 0xff51, ///
Right = 0xff53, ///
Tab = 0xff09, ///
Q = 0x71, ///
W = 0x77, ///
E = 0x65, ///
R = 0x72, ///
T = 0x74, ///
Y = 0x79, ///
U = 0x75, ///
I = 0x69, ///
O = 0x6f, ///
P = 0x70, ///
LeftBracket = 0x5b, /// the [ { key
RightBracket = 0x5d, /// the ] } key
CapsLock = 0xffe5, ///
A = 0x61, ///
S = 0x73, ///
D = 0x64, ///
F = 0x66, ///
G = 0x67, ///
H = 0x68, ///
J = 0x6a, ///
K = 0x6b, ///
L = 0x6c, ///
Semicolon = 0x3b, ///
Apostrophe = 0x27, ///
Enter = 0xff0d, ///
Shift = 0xffe1, ///
Z = 0x7a, ///
X = 0x78, ///
C = 0x63, ///
V = 0x76, ///
B = 0x62, ///
N = 0x6e, ///
M = 0x6d, ///
Comma = 0x2c, ///
Period = 0x2e, ///
Slash = 0x2f, /// the / ? key
Shift_r = 0xffe2, /// Note: this isn't sent on all computers, sometimes it just sends Shift, so don't rely on it. If it is supported though, it is the right Shift key, as opposed to the left Shift key
Ctrl = 0xffe3, ///
Windows = 0xffeb, ///
Alt = 0xffe9, ///
Space = 0x20, ///
Alt_r = 0xffea, /// ditto of shift_r
Windows_r = 0xffec, ///
Menu = 0xff67, ///
Ctrl_r = 0xffe4, ///
NumLock = 0xff7f, ///
Divide = 0xffaf, /// The / key on the number pad
Multiply = 0xffaa, /// The * key on the number pad
Minus = 0xffad, /// The - key on the number pad
Plus = 0xffab, /// The + key on the number pad
PadEnter = 0xff8d, /// Numberpad enter key
Pad1 = 0xff9c, /// Numberpad keys
Pad2 = 0xff99, ///
Pad3 = 0xff9b, ///
Pad4 = 0xff96, ///
Pad5 = 0xff9d, ///
Pad6 = 0xff98, ///
Pad7 = 0xff95, ///
Pad8 = 0xff97, ///
Pad9 = 0xff9a, ///
Pad0 = 0xff9e, ///
PadDot = 0xff9f, ///
}
} else version(Windows) {
// the character here is for en-us layouts and for illustration only
// if you actually want to get characters, wait for character events
// (the argument to your event handler is simply a dchar)
// those will be converted by the OS for the right locale.
enum Key {
Escape = 0x1b,
F1 = 0x70,
F2 = 0x71,
F3 = 0x72,
F4 = 0x73,
F5 = 0x74,
F6 = 0x75,
F7 = 0x76,
F8 = 0x77,
F9 = 0x78,
F10 = 0x79,
F11 = 0x7a,
F12 = 0x7b,
PrintScreen = 0x2c,
ScrollLock = 0x91,
Pause = 0x13,
Grave = 0xc0,
// number keys across the top of the keyboard
N1 = 0x31,
N2 = 0x32,
N3 = 0x33,
N4 = 0x34,
N5 = 0x35,
N6 = 0x36,
N7 = 0x37,
N8 = 0x38,
N9 = 0x39,
N0 = 0x30,
Dash = 0xbd,
Equals = 0xbb,
Backslash = 0xdc,
Backspace = 0x08,
Insert = 0x2d,
Home = 0x24,
PageUp = 0x21,
Delete = 0x2e,
End = 0x23,
PageDown = 0x22,
Up = 0x26,
Down = 0x28,
Left = 0x25,
Right = 0x27,
Tab = 0x09,
Q = 0x51,
W = 0x57,
E = 0x45,
R = 0x52,
T = 0x54,
Y = 0x59,
U = 0x55,
I = 0x49,
O = 0x4f,
P = 0x50,
LeftBracket = 0xdb,
RightBracket = 0xdd,
CapsLock = 0x14,
A = 0x41,
S = 0x53,
D = 0x44,
F = 0x46,
G = 0x47,
H = 0x48,
J = 0x4a,
K = 0x4b,
L = 0x4c,
Semicolon = 0xba,
Apostrophe = 0xde,
Enter = 0x0d,
Shift = 0x10,
Z = 0x5a,
X = 0x58,
C = 0x43,
V = 0x56,
B = 0x42,
N = 0x4e,
M = 0x4d,
Comma = 0xbc,
Period = 0xbe,
Slash = 0xbf,
Shift_r = 0xa1, // FIXME Note: this isn't sent on all computers, sometimes it just sends Shift, so don't rely on it
Ctrl = 0x11,
Windows = 0x5b,
Alt = -5, // FIXME
Space = 0x20,
Alt_r = 0xffea, // ditto of shift_r
Windows_r = 0x5c, // ditto of shift_r
Menu = 0x5d,
Ctrl_r = 0xa3, // ditto of shift_r
NumLock = 0x90,
Divide = 0x6f,
Multiply = 0x6a,
Minus = 0x6d,
Plus = 0x6b,
PadEnter = -8, // FIXME
Pad1 = 0x61,
Pad2 = 0x62,
Pad3 = 0x63,
Pad4 = 0x64,
Pad5 = 0x65,
Pad6 = 0x66,
Pad7 = 0x67,
Pad8 = 0x68,
Pad9 = 0x69,
Pad0 = 0x60,
PadDot = 0x6e,
}
// I'm keeping this around for reference purposes
// ideally all these buttons will be listed for all platforms,
// but now now I'm just focusing on my US keyboard
version(none)
enum Key {
LBUTTON = 0x01,
RBUTTON = 0x02,
CANCEL = 0x03,
MBUTTON = 0x04,
//static if (_WIN32_WINNT > = 0x500) {
XBUTTON1 = 0x05,
XBUTTON2 = 0x06,
//}
BACK = 0x08,
TAB = 0x09,
CLEAR = 0x0C,
RETURN = 0x0D,
SHIFT = 0x10,
CONTROL = 0x11,
MENU = 0x12,
PAUSE = 0x13,
CAPITAL = 0x14,
KANA = 0x15,
HANGEUL = 0x15,
HANGUL = 0x15,
JUNJA = 0x17,
FINAL = 0x18,
HANJA = 0x19,
KANJI = 0x19,
ESCAPE = 0x1B,
CONVERT = 0x1C,
NONCONVERT = 0x1D,
ACCEPT = 0x1E,
MODECHANGE = 0x1F,
SPACE = 0x20,
PRIOR = 0x21,
NEXT = 0x22,
END = 0x23,
HOME = 0x24,
LEFT = 0x25,
UP = 0x26,
RIGHT = 0x27,
DOWN = 0x28,
SELECT = 0x29,
PRINT = 0x2A,
EXECUTE = 0x2B,
SNAPSHOT = 0x2C,
INSERT = 0x2D,
DELETE = 0x2E,
HELP = 0x2F,
LWIN = 0x5B,
RWIN = 0x5C,
APPS = 0x5D,
SLEEP = 0x5F,
NUMPAD0 = 0x60,
NUMPAD1 = 0x61,
NUMPAD2 = 0x62,
NUMPAD3 = 0x63,
NUMPAD4 = 0x64,
NUMPAD5 = 0x65,
NUMPAD6 = 0x66,
NUMPAD7 = 0x67,
NUMPAD8 = 0x68,
NUMPAD9 = 0x69,
MULTIPLY = 0x6A,
ADD = 0x6B,
SEPARATOR = 0x6C,
SUBTRACT = 0x6D,
DECIMAL = 0x6E,
DIVIDE = 0x6F,
F1 = 0x70,
F2 = 0x71,
F3 = 0x72,
F4 = 0x73,
F5 = 0x74,
F6 = 0x75,
F7 = 0x76,
F8 = 0x77,
F9 = 0x78,
F10 = 0x79,
F11 = 0x7A,
F12 = 0x7B,
F13 = 0x7C,
F14 = 0x7D,
F15 = 0x7E,
F16 = 0x7F,
F17 = 0x80,
F18 = 0x81,
F19 = 0x82,
F20 = 0x83,
F21 = 0x84,
F22 = 0x85,
F23 = 0x86,
F24 = 0x87,
NUMLOCK = 0x90,
SCROLL = 0x91,
LSHIFT = 0xA0,
RSHIFT = 0xA1,
LCONTROL = 0xA2,
RCONTROL = 0xA3,
LMENU = 0xA4,
RMENU = 0xA5,
//static if (_WIN32_WINNT > = 0x500) {
BROWSER_BACK = 0xA6,
BROWSER_FORWARD = 0xA7,
BROWSER_REFRESH = 0xA8,
BROWSER_STOP = 0xA9,
BROWSER_SEARCH = 0xAA,
BROWSER_FAVORITES = 0xAB,
BROWSER_HOME = 0xAC,
VOLUME_MUTE = 0xAD,
VOLUME_DOWN = 0xAE,
VOLUME_UP = 0xAF,
MEDIA_NEXT_TRACK = 0xB0,
MEDIA_PREV_TRACK = 0xB1,
MEDIA_STOP = 0xB2,
MEDIA_PLAY_PAUSE = 0xB3,
LAUNCH_MAIL = 0xB4,
LAUNCH_MEDIA_SELECT = 0xB5,
LAUNCH_APP1 = 0xB6,
LAUNCH_APP2 = 0xB7,
//}
OEM_1 = 0xBA,
//static if (_WIN32_WINNT > = 0x500) {
OEM_PLUS = 0xBB,
OEM_COMMA = 0xBC,
OEM_MINUS = 0xBD,
OEM_PERIOD = 0xBE,
//}
OEM_2 = 0xBF,
OEM_3 = 0xC0,
OEM_4 = 0xDB,
OEM_5 = 0xDC,
OEM_6 = 0xDD,
OEM_7 = 0xDE,
OEM_8 = 0xDF,
//static if (_WIN32_WINNT > = 0x500) {
OEM_102 = 0xE2,
//}
PROCESSKEY = 0xE5,
//static if (_WIN32_WINNT > = 0x500) {
PACKET = 0xE7,
//}
ATTN = 0xF6,
CRSEL = 0xF7,
EXSEL = 0xF8,
EREOF = 0xF9,
PLAY = 0xFA,
ZOOM = 0xFB,
NONAME = 0xFC,
PA1 = 0xFD,
OEM_CLEAR = 0xFE,
}
} else version(OSXCocoa) {
// FIXME
enum Key {
Escape = 0x1b,
F1 = 0x70,
F2 = 0x71,
F3 = 0x72,
F4 = 0x73,
F5 = 0x74,
F6 = 0x75,
F7 = 0x76,
F8 = 0x77,
F9 = 0x78,
F10 = 0x79,
F11 = 0x7a,
F12 = 0x7b,
PrintScreen = 0x2c,
ScrollLock = -2, // FIXME
Pause = -3, // FIXME
Grave = 0xc0,
// number keys across the top of the keyboard
N1 = 0x31,
N2 = 0x32,
N3 = 0x33,
N4 = 0x34,
N5 = 0x35,
N6 = 0x36,
N7 = 0x37,
N8 = 0x38,
N9 = 0x39,
N0 = 0x30,
Dash = 0xbd,
Equals = 0xbb,
Backslash = 0xdc,
Backspace = 0x08,
Insert = 0x2d,
Home = 0x24,
PageUp = 0x21,
Delete = 0x2e,
End = 0x23,
PageDown = 0x22,
Up = 0x26,
Down = 0x28,
Left = 0x25,
Right = 0x27,
Tab = 0x09,
Q = 0x51,
W = 0x57,
E = 0x45,
R = 0x52,
T = 0x54,
Y = 0x59,
U = 0x55,
I = 0x49,
O = 0x4f,
P = 0x50,
LeftBracket = 0xdb,
RightBracket = 0xdd,
CapsLock = 0x14,
A = 0x41,
S = 0x53,
D = 0x44,
F = 0x46,
G = 0x47,
H = 0x48,
J = 0x4a,
K = 0x4b,
L = 0x4c,
Semicolon = 0xba,
Apostrophe = 0xde,
Enter = 0x0d,
Shift = 0x10,
Z = 0x5a,
X = 0x58,
C = 0x43,
V = 0x56,
B = 0x42,
N = 0x4e,
M = 0x4d,
Comma = 0xbc,
Period = 0xbe,
Slash = 0xbf,
Shift_r = -4, // FIXME Note: this isn't sent on all computers, sometimes it just sends Shift, so don't rely on it
Ctrl = 0x11,
Windows = 0x5b,
Alt = -5, // FIXME
Space = 0x20,
Alt_r = 0xffea, // ditto of shift_r
Windows_r = -6, // FIXME
Menu = 0x5d,
Ctrl_r = -7, // FIXME
NumLock = 0x90,
Divide = 0x6f,
Multiply = 0x6a,
Minus = 0x6d,
Plus = 0x6b,
PadEnter = -8, // FIXME
// FIXME for the rest of these:
Pad1 = 0xff9c,
Pad2 = 0xff99,
Pad3 = 0xff9b,
Pad4 = 0xff96,
Pad5 = 0xff9d,
Pad6 = 0xff98,
Pad7 = 0xff95,
Pad8 = 0xff97,
Pad9 = 0xff9a,
Pad0 = 0xff9e,
PadDot = 0xff9f,
}
}
/* Additional utilities */
Color fromHsl(real h, real s, real l) {
return arsd.color.fromHsl([h,s,l]);
}
/* ********** What follows is the system-specific implementations *********/
version(Windows) {
// helpers for making HICONs from MemoryImages
class WindowsIcon {
struct Win32Icon(int colorCount) {
align(1):
uint biSize;
int biWidth;
int biHeight;
ushort biPlanes;
ushort biBitCount;
uint biCompression;
uint biSizeImage;
int biXPelsPerMeter;
int biYPelsPerMeter;
uint biClrUsed;
uint biClrImportant;
RGBQUAD[colorCount] biColors;
/* Pixels:
Uint8 pixels[]
*/
/* Mask:
Uint8 mask[]
*/
ubyte[4096] data;
void fromMemoryImage(MemoryImage mi, out int icon_len, out int width, out int height) {
width = mi.width;
height = mi.height;
auto indexedImage = cast(IndexedImage) mi;
if(indexedImage is null)
indexedImage = quantize(mi.getAsTrueColorImage());
assert(width %8 == 0); // i don't want padding nor do i want the and mask to get fancy
assert(height %4 == 0);
int icon_plen = height*((width+3)&~3);
int icon_mlen = height*((((width+7)/8)+3)&~3);
icon_len = 40+icon_plen+icon_mlen + cast(int) RGBQUAD.sizeof * colorCount;
biSize = 40;
biWidth = width;
biHeight = height*2;
biPlanes = 1;
biBitCount = 8;
biSizeImage = icon_plen+icon_mlen;
int offset = 0;
int andOff = icon_plen * 8; // the and offset is in bits
for(int y = height - 1; y >= 0; y--) {
int off2 = y * width;
foreach(x; 0 .. width) {
const b = indexedImage.data[off2 + x];
data[offset] = b;
offset++;
const andBit = andOff % 8;
const andIdx = andOff / 8;
assert(b < indexedImage.palette.length);
// this is anded to the destination, since and 0 means erase,
// we want that to be opaque, and 1 for transparent
auto transparent = (indexedImage.palette[b].a <= 127);
data[andIdx] |= (transparent ? (1 << (7-andBit)) : 0);
andOff++;
}
andOff += andOff % 32;
}
foreach(idx, entry; indexedImage.palette) {
if(entry.a > 127) {
biColors[idx].rgbBlue = entry.b;
biColors[idx].rgbGreen = entry.g;
biColors[idx].rgbRed = entry.r;
} else {
biColors[idx].rgbBlue = 255;
biColors[idx].rgbGreen = 255;
biColors[idx].rgbRed = 255;
}
}
/*
data[0..icon_plen] = getFlippedUnfilteredDatastream(png);
data[icon_plen..icon_plen+icon_mlen] = getANDMask(png);
//icon_win32.biColors[1] = Win32Icon.RGBQUAD(0,255,0,0);
auto pngMap = fetchPaletteWin32(png);
biColors[0..pngMap.length] = pngMap[];
*/
}
}
Win32Icon!(256) icon_win32;
this(MemoryImage mi) {
int icon_len, width, height;
icon_win32.fromMemoryImage(mi, icon_len, width, height);
/*
PNG* png = readPnpngData);
PNGHeader pngh = getHeader(png);
void* icon_win32;
if(pngh.depth == 4) {
auto i = new Win32Icon!(16);
i.fromPNG(png, pngh, icon_len, width, height);
icon_win32 = i;
}
else if(pngh.depth == 8) {
auto i = new Win32Icon!(256);
i.fromPNG(png, pngh, icon_len, width, height);
icon_win32 = i;
} else assert(0);
*/
hIcon = CreateIconFromResourceEx(cast(ubyte*) &icon_win32, icon_len, true, 0x00030000, width, height, 0);
if(hIcon is null) throw new Exception("CreateIconFromResourceEx");
}
~this() {
if(!thisIsGuiThread) return; // FIXME: leaks if multithreaded gc
DestroyIcon(hIcon);
}
HICON hIcon;
}
alias int delegate(HWND, UINT, WPARAM, LPARAM, out int) NativeEventHandler;
alias HWND NativeWindowHandle;
extern(Windows)
LRESULT WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam) nothrow {
try {
if(SimpleWindow.handleNativeGlobalEvent !is null) {
// it returns zero if the message is handled, so we won't do anything more there
// do I like that though?
int mustReturn;
auto ret = SimpleWindow.handleNativeGlobalEvent(hWnd, iMessage, wParam, lParam, mustReturn);
if(mustReturn)
return ret;
}
if(auto window = hWnd in CapableOfHandlingNativeEvent.nativeHandleMapping) {
if(window.getNativeEventHandler !is null) {
int mustReturn;
auto ret = window.getNativeEventHandler()(hWnd, iMessage, wParam, lParam, mustReturn);
if(mustReturn)
return ret;
}
if(auto w = cast(SimpleWindow) (*window))
return w.windowProcedure(hWnd, iMessage, wParam, lParam);
else
return DefWindowProc(hWnd, iMessage, wParam, lParam);
} else {
return DefWindowProc(hWnd, iMessage, wParam, lParam);
}
} catch (Exception e) {
try {
sdpy_abort(e);
return 0;
} catch(Exception e) { assert(0); }
}
}
void sdpy_abort(Throwable e) nothrow {
try
MessageBoxA(null, (e.toString() ~ "\0").ptr, "Exception caught in WndProc", 0);
catch(Exception e)
MessageBoxA(null, "Exception.toString threw too!", "Exception caught in WndProc", 0);
ExitProcess(1);
}
mixin template NativeScreenPainterImplementation() {
HDC hdc;
HWND hwnd;
//HDC windowHdc;
HBITMAP oldBmp;
void create(NativeWindowHandle window) {
hwnd = window;
if(auto sw = cast(SimpleWindow) this.window) {
// drawing on a window, double buffer
auto windowHdc = GetDC(hwnd);
auto buffer = sw.impl.buffer;
if(buffer is null) {
hdc = windowHdc;
windowDc = true;
} else {
hdc = CreateCompatibleDC(windowHdc);
ReleaseDC(hwnd, windowHdc);
oldBmp = SelectObject(hdc, buffer);
}
} else {
// drawing on something else, draw directly
hdc = CreateCompatibleDC(null);
SelectObject(hdc, window);
}
// X doesn't draw a text background, so neither should we
SetBkMode(hdc, TRANSPARENT);
ensureDefaultFontLoaded();
if(defaultGuiFont) {
SelectObject(hdc, defaultGuiFont);
// DeleteObject(defaultGuiFont);
}
}
static HFONT defaultGuiFont;
static void ensureDefaultFontLoaded() {
static bool triedDefaultGuiFont = false;
if(!triedDefaultGuiFont) {
NONCLIENTMETRICS params;
params.cbSize = params.sizeof;
if(SystemParametersInfo(SPI_GETNONCLIENTMETRICS, params.sizeof, ¶ms, 0)) {
defaultGuiFont = CreateFontIndirect(¶ms.lfMessageFont);
}
triedDefaultGuiFont = true;
}
}
private OperatingSystemFont _activeFont;
void setFont(OperatingSystemFont font) {
_activeFont = font;
if(font && font.font) {
if(SelectObject(hdc, font.font) == HGDI_ERROR) {
// error... how to handle tho?
} else {
}
}
else if(defaultGuiFont)
SelectObject(hdc, defaultGuiFont);
}
arsd.color.Rectangle _clipRectangle;
void setClipRectangle(int x, int y, int width, int height) {
auto old = _clipRectangle;
_clipRectangle = arsd.color.Rectangle(Point(x, y), Size(width, height));
if(old == _clipRectangle)
return;
if(width == 0 || height == 0) {
SelectClipRgn(hdc, null);
} else {
auto region = CreateRectRgn(x, y, x + width, y + height);
SelectClipRgn(hdc, region);
DeleteObject(region);
}
}
// just because we can on Windows...
//void create(Image image);
void invalidateRect(Rectangle invalidRect) {
RECT rect;
rect.left = invalidRect.left;
rect.right = invalidRect.right;
rect.top = invalidRect.top;
rect.bottom = invalidRect.bottom;
InvalidateRect(hwnd, &rect, false);
}
bool manualInvalidations;
void dispose() {
// FIXME: this.window.width/height is probably wrong
// BitBlt(windowHdc, 0, 0, this.window.width, this.window.height, hdc, 0, 0, SRCCOPY);
// ReleaseDC(hwnd, windowHdc);
// FIXME: it shouldn't invalidate the whole thing in all cases... it would be ideal to do this right
if(cast(SimpleWindow) this.window) {
if(!manualInvalidations)
InvalidateRect(hwnd, cast(RECT*)null, false); // no need to erase bg as the whole thing gets bitblt'd ove
}
if(originalPen !is null)
SelectObject(hdc, originalPen);
if(currentPen !is null)
DeleteObject(currentPen);
if(originalBrush !is null)
SelectObject(hdc, originalBrush);
if(currentBrush !is null)
DeleteObject(currentBrush);
SelectObject(hdc, oldBmp);
if(windowDc)
ReleaseDC(hwnd, hdc);
else
DeleteDC(hdc);
if(window.paintingFinishedDg !is null)
window.paintingFinishedDg()();
}
bool windowDc;
HPEN originalPen;
HPEN currentPen;
Pen _activePen;
Color _outlineColor;
@property void pen(Pen p) {
_activePen = p;
_outlineColor = p.color;
HPEN pen;
if(p.color.a == 0) {
pen = GetStockObject(NULL_PEN);
} else {
int style = PS_SOLID;
final switch(p.style) {
case Pen.Style.Solid:
style = PS_SOLID;
break;
case Pen.Style.Dashed:
style = PS_DASH;
break;
case Pen.Style.Dotted:
style = PS_DOT;
break;
}
pen = CreatePen(style, p.width, RGB(p.color.r, p.color.g, p.color.b));
}
auto orig = SelectObject(hdc, pen);
if(originalPen is null)
originalPen = orig;
if(currentPen !is null)
DeleteObject(currentPen);
currentPen = pen;
// the outline is like a foreground since it's done that way on X
SetTextColor(hdc, RGB(p.color.r, p.color.g, p.color.b));
}
@property void rasterOp(RasterOp op) {
int mode;
final switch(op) {
case RasterOp.normal:
mode = R2_COPYPEN;
break;
case RasterOp.xor:
mode = R2_XORPEN;
break;
}
SetROP2(hdc, mode);
}
HBRUSH originalBrush;
HBRUSH currentBrush;
Color _fillColor = Color(1, 1, 1, 1); // what are the odds that they'd set this??
@property void fillColor(Color c) {
if(c == _fillColor)
return;
_fillColor = c;
HBRUSH brush;
if(c.a == 0) {
brush = GetStockObject(HOLLOW_BRUSH);
} else {
brush = CreateSolidBrush(RGB(c.r, c.g, c.b));
}
auto orig = SelectObject(hdc, brush);
if(originalBrush is null)
originalBrush = orig;
if(currentBrush !is null)
DeleteObject(currentBrush);
currentBrush = brush;
// background color is NOT set because X doesn't draw text backgrounds
// SetBkColor(hdc, RGB(255, 255, 255));
}
void drawImage(int x, int y, Image i, int ix, int iy, int w, int h) {
BITMAP bm;
HDC hdcMem = CreateCompatibleDC(hdc);
HBITMAP hbmOld = SelectObject(hdcMem, i.handle);
GetObject(i.handle, bm.sizeof, &bm);
// or should I AlphaBlend!??!?!
BitBlt(hdc, x, y, w /* bm.bmWidth */, /*bm.bmHeight*/ h, hdcMem, ix, iy, SRCCOPY);
SelectObject(hdcMem, hbmOld);
DeleteDC(hdcMem);
}
void drawPixmap(Sprite s, int x, int y, int ix, int iy, int w, int h) {
BITMAP bm;
HDC hdcMem = CreateCompatibleDC(hdc);
HBITMAP hbmOld = SelectObject(hdcMem, s.handle);
GetObject(s.handle, bm.sizeof, &bm);
version(CRuntime_DigitalMars) goto noalpha;
// or should I AlphaBlend!??!?! note it is supposed to be premultiplied http://www.fengyuan.com/article/alphablend.html
if(s.enableAlpha) {
auto dw = w ? w : bm.bmWidth;
auto dh = h ? h : bm.bmHeight;
BLENDFUNCTION bf;
bf.BlendOp = AC_SRC_OVER;
bf.SourceConstantAlpha = 255;
bf.AlphaFormat = AC_SRC_ALPHA;
AlphaBlend(hdc, x, y, dw, dh, hdcMem, ix, iy, dw, dh, bf);
} else {
noalpha:
BitBlt(hdc, x, y, w ? w : bm.bmWidth, h ? h : bm.bmHeight, hdcMem, ix, iy, SRCCOPY);
}
SelectObject(hdcMem, hbmOld);
DeleteDC(hdcMem);
}
Size textSize(scope const(char)[] text) {
bool dummyX;
if(text.length == 0) {
text = " ";
dummyX = true;
}
RECT rect;
WCharzBuffer buffer = WCharzBuffer(text);
DrawTextW(hdc, buffer.ptr, cast(int) buffer.length, &rect, DT_CALCRECT | DT_NOPREFIX);
return Size(dummyX ? 0 : rect.right, rect.bottom);
}
void drawText(int x, int y, int x2, int y2, scope const(char)[] text, uint alignment) {
if(text.length && text[$-1] == '\n')
text = text[0 .. $-1]; // tailing newlines are weird on windows...
if(text.length && text[$-1] == '\r')
text = text[0 .. $-1];
WCharzBuffer buffer = WCharzBuffer(text, WindowsStringConversionFlags.convertNewLines);
if(x2 == 0 && y2 == 0) {
TextOutW(hdc, x, y, buffer.ptr, cast(int) buffer.length);
} else {
RECT rect;
rect.left = x;
rect.top = y;
rect.right = x2;
rect.bottom = y2;
uint mode = DT_LEFT;
if(alignment & TextAlignment.Right)
mode = DT_RIGHT;
else if(alignment & TextAlignment.Center)
mode = DT_CENTER;
// FIXME: vcenter on windows only works with single line, but I want it to work in all cases
if(alignment & TextAlignment.VerticalCenter)
mode |= DT_VCENTER | DT_SINGLELINE;
DrawTextW(hdc, buffer.ptr, cast(int) buffer.length, &rect, mode | DT_NOPREFIX);
}
/*
uint mode;
if(alignment & TextAlignment.Center)
mode = TA_CENTER;
SetTextAlign(hdc, mode);
*/
}
int fontHeight() {
TEXTMETRIC metric;
if(GetTextMetricsW(hdc, &metric)) {
return metric.tmHeight;
}
return 16; // idk just guessing here, maybe we should throw
}
void drawPixel(int x, int y) {
SetPixel(hdc, x, y, RGB(_activePen.color.r, _activePen.color.g, _activePen.color.b));
}
// The basic shapes, outlined
void drawLine(int x1, int y1, int x2, int y2) {
MoveToEx(hdc, x1, y1, null);
LineTo(hdc, x2, y2);
}
void drawRectangle(int x, int y, int width, int height) {
// FIXME: with a wider pen this might not draw quite right. im not sure.
gdi.Rectangle(hdc, x, y, x + width, y + height);
}
/// Arguments are the points of the bounding rectangle
void drawEllipse(int x1, int y1, int x2, int y2) {
Ellipse(hdc, x1, y1, x2, y2);
}
void drawArc(int x1, int y1, int width, int height, int start, int finish) {
if((start % (360*64)) == (finish % (360*64)))
drawEllipse(x1, y1, x1 + width, y1 + height);
else {
import core.stdc.math;
float startAngle = cast(float) start / 64.0 / 180.0 * 3.14159265358979323;
float endAngle = cast(float) finish / 64.0 / 180.0 * 3.14159265358979323;
auto c1 = cast(int) roundf(cos(startAngle) * width / 2 + x1 + width / 2);
auto c2 = cast(int) roundf(-sin(startAngle) * height / 2 + y1 + height / 2);
auto c3 = cast(int) roundf(cos(endAngle) * width / 2 + x1 + width / 2);
auto c4 = cast(int) roundf(-sin(endAngle) * height / 2 + y1 + height / 2);
if(_activePen.color.a)
Arc(hdc, x1, y1, x1 + width + 1, y1 + height + 1, c1, c2, c3, c4);
if(_fillColor.a)
Pie(hdc, x1, y1, x1 + width + 1, y1 + height + 1, c1, c2, c3, c4);
}
}
void drawPolygon(Point[] vertexes) {
POINT[] points;
points.length = vertexes.length;
foreach(i, p; vertexes) {
points[i].x = p.x;
points[i].y = p.y;
}
Polygon(hdc, points.ptr, cast(int) points.length);
}
}
// Mix this into the SimpleWindow class
mixin template NativeSimpleWindowImplementation() {
int curHidden = 0; // counter
__gshared static bool[string] knownWinClasses;
static bool altPressed = false;
HANDLE oldCursor;
void hideCursor () {
if(curHidden == 0)
oldCursor = SetCursor(null);
++curHidden;
}
void showCursor () {
--curHidden;
if(curHidden == 0) {
SetCursor(currentCursor is null ? oldCursor : currentCursor); // show it immediately without waiting for mouse movement
}
}
int minWidth = 0, minHeight = 0, maxWidth = int.max, maxHeight = int.max;
void setMinSize (int minwidth, int minheight) {
minWidth = minwidth;
minHeight = minheight;
}
void setMaxSize (int maxwidth, int maxheight) {
maxWidth = maxwidth;
maxHeight = maxheight;
}
// FIXME i'm not sure that Windows has this functionality
// though it is nonessential anyway.
void setResizeGranularity (int granx, int grany) {}
ScreenPainter getPainter(bool manualInvalidations) {
return ScreenPainter(this, hwnd, manualInvalidations);
}
HBITMAP buffer;
void setTitle(string title) {
WCharzBuffer bfr = WCharzBuffer(title);
SetWindowTextW(hwnd, bfr.ptr);
}
string getTitle() {
auto len = GetWindowTextLengthW(hwnd);
if (!len)
return null;
wchar[256] tmpBuffer;
wchar[] buffer = (len <= tmpBuffer.length) ? tmpBuffer[] : new wchar[len];
auto len2 = GetWindowTextW(hwnd, buffer.ptr, cast(int) buffer.length);
auto str = buffer[0 .. len2];
return makeUtf8StringFromWindowsString(str);
}
void move(int x, int y) {
RECT rect;
GetWindowRect(hwnd, &rect);
// move it while maintaining the same size...
MoveWindow(hwnd, x, y, rect.right - rect.left, rect.bottom - rect.top, true);
}
void resize(int w, int h) {
RECT rect;
GetWindowRect(hwnd, &rect);
RECT client;
GetClientRect(hwnd, &client);
rect.right = rect.right - client.right + w;
rect.bottom = rect.bottom - client.bottom + h;
// same position, new size for the client rectangle
MoveWindow(hwnd, rect.left, rect.top, rect.right, rect.bottom, true);
updateOpenglViewportIfNeeded(w, h);
}
void moveResize (int x, int y, int w, int h) {
// what's given is the client rectangle, we need to adjust
RECT rect;
rect.left = x;
rect.top = y;
rect.right = w + x;
rect.bottom = h + y;
if(!AdjustWindowRect(&rect, GetWindowLong(hwnd, GWL_STYLE), GetMenu(hwnd) !is null))
throw new Exception("AdjustWindowRect");
MoveWindow(hwnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, true);
updateOpenglViewportIfNeeded(w, h);
if (windowResized !is null) windowResized(w, h);
}
version(without_opengl) {} else {
HGLRC ghRC;
HDC ghDC;
}
void createWindow(int width, int height, string title, OpenGlOptions opengl, SimpleWindow parent) {
string cnamec;
if (sdpyWindowClassStr is null) loadBinNameToWindowClassName();
if (sdpyWindowClassStr is null || sdpyWindowClassStr[0] == 0) {
cnamec = "DSimpleWindow";
} else {
cnamec = sdpyWindowClass;
}
WCharzBuffer cn = WCharzBuffer(cnamec);
HINSTANCE hInstance = cast(HINSTANCE) GetModuleHandle(null);
if(cnamec !in knownWinClasses) {
WNDCLASSEX wc;
// FIXME: I might be able to use cbWndExtra to hold the pointer back
// to the object. Maybe.
wc.cbSize = wc.sizeof;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hbrBackground = cast(HBRUSH) (COLOR_WINDOW+1); // GetStockObject(WHITE_BRUSH);
wc.hCursor = LoadCursorW(null, IDC_ARROW);
wc.hIcon = LoadIcon(hInstance, null);
wc.hInstance = hInstance;
wc.lpfnWndProc = &WndProc;
wc.lpszClassName = cn.ptr;
wc.hIconSm = null;
wc.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
if(!RegisterClassExW(&wc))
throw new WindowsApiException("RegisterClassExW");
knownWinClasses[cnamec] = true;
}
int style;
uint flags = WS_EX_ACCEPTFILES; // accept drag-drop files
// FIXME: windowType and customizationFlags
final switch(windowType) {
case WindowTypes.normal:
if(resizability == Resizability.fixedSize) {
style = WS_SYSMENU | WS_OVERLAPPED | WS_CAPTION;
} else {
style = WS_OVERLAPPEDWINDOW;
}
break;
case WindowTypes.undecorated:
style = WS_POPUP | WS_SYSMENU;
break;
case WindowTypes.eventOnly:
_hidden = true;
break;
case WindowTypes.dropdownMenu:
case WindowTypes.popupMenu:
case WindowTypes.notification:
style = WS_POPUP;
flags |= WS_EX_NOACTIVATE;
break;
case WindowTypes.nestedChild:
style = WS_CHILD;
break;
case WindowTypes.minimallyWrapped:
assert(0, "construct minimally wrapped through the other ctor overlad");
}
if ((customizationFlags & WindowFlags.extraComposite) != 0)
flags |= WS_EX_LAYERED; // composite window for better performance and effects support
hwnd = CreateWindowEx(flags, cn.ptr, toWStringz(title), style | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, // the clip children helps avoid flickering in minigui and doesn't seem to harm other use (mostly, sdpy is no child windows anyway) sooo i think it is ok
CW_USEDEFAULT, CW_USEDEFAULT, width, height,
parent is null ? null : parent.impl.hwnd, null, hInstance, null);
if ((customizationFlags & WindowFlags.extraComposite) != 0)
setOpacity(255);
SimpleWindow.nativeMapping[hwnd] = this;
CapableOfHandlingNativeEvent.nativeHandleMapping[hwnd] = this;
if(windowType == WindowTypes.eventOnly)
return;
HDC hdc = GetDC(hwnd);
version(without_opengl) {}
else {
if(opengl == OpenGlOptions.yes) {
if(!openGlLibrariesSuccessfullyLoaded) throw new Exception("OpenGL libraries did not load");
static if (SdpyIsUsingIVGLBinds) {if (glbindGetProcAddress("glHint") is null) assert(0, "GL: error loading OpenGL"); } // loads all necessary functions
static if (SdpyIsUsingIVGLBinds) import iv.glbinds; // override druntime windows imports
ghDC = hdc;
PIXELFORMATDESCRIPTOR pfd;
pfd.nSize = PIXELFORMATDESCRIPTOR.sizeof;
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.dwLayerMask = PFD_MAIN_PLANE;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 24;
pfd.cAccumBits = 0;
pfd.cStencilBits = 8; // any reasonable OpenGL implementation should support this anyway
auto pixelformat = ChoosePixelFormat(hdc, &pfd);
if (pixelformat == 0)
throw new WindowsApiException("ChoosePixelFormat");
if (SetPixelFormat(hdc, pixelformat, &pfd) == 0)
throw new WindowsApiException("SetPixelFormat");
if (sdpyOpenGLContextVersion && wglCreateContextAttribsARB is null) {
// windoze is idiotic: we have to have OpenGL context to get function addresses
// so we will create fake context to get that stupid address
auto tmpcc = wglCreateContext(ghDC);
if (tmpcc !is null) {
scope(exit) { wglMakeCurrent(ghDC, null); wglDeleteContext(tmpcc); }
wglMakeCurrent(ghDC, tmpcc);
wglInitOtherFunctions();
}
}
if (wglCreateContextAttribsARB !is null && sdpyOpenGLContextVersion) {
int[9] contextAttribs = [
WGL_CONTEXT_MAJOR_VERSION_ARB, (sdpyOpenGLContextVersion>>8),
WGL_CONTEXT_MINOR_VERSION_ARB, (sdpyOpenGLContextVersion&0xff),
WGL_CONTEXT_PROFILE_MASK_ARB, (sdpyOpenGLContextCompatible ? WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB : WGL_CONTEXT_CORE_PROFILE_BIT_ARB),
// for modern context, set "forward compatibility" flag too
(sdpyOpenGLContextCompatible ? 0/*None*/ : WGL_CONTEXT_FLAGS_ARB), WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
0/*None*/,
];
ghRC = wglCreateContextAttribsARB(ghDC, null, contextAttribs.ptr);
if (ghRC is null && sdpyOpenGLContextAllowFallback) {
// activate fallback mode
// sdpyOpenGLContextVeto-type focus management policy leads to race conditions because the window becoming unviewable may coincide with the window manager deciding to move the focus elsrsion = 0;
ghRC = wglCreateContext(ghDC);
}
if (ghRC is null)
throw new WindowsApiException("wglCreateContextAttribsARB");
} else {
// try to do at least something
if (sdpyOpenGLContextAllowFallback || sdpyOpenGLContextVersion == 0) {
sdpyOpenGLContextVersion = 0;
ghRC = wglCreateContext(ghDC);
}
if (ghRC is null)
throw new WindowsApiException("wglCreateContext");
}
}
}
if(opengl == OpenGlOptions.no) {
buffer = CreateCompatibleBitmap(hdc, width, height);
auto hdcBmp = CreateCompatibleDC(hdc);
// make sure it's filled with a blank slate
auto oldBmp = SelectObject(hdcBmp, buffer);
auto oldBrush = SelectObject(hdcBmp, GetStockObject(WHITE_BRUSH));
auto oldPen = SelectObject(hdcBmp, GetStockObject(WHITE_PEN));
gdi.Rectangle(hdcBmp, 0, 0, width, height);
SelectObject(hdcBmp, oldBmp);
SelectObject(hdcBmp, oldBrush);
SelectObject(hdcBmp, oldPen);
DeleteDC(hdcBmp);
bmpWidth = width;
bmpHeight = height;
ReleaseDC(hwnd, hdc); // we keep this in opengl mode since it is a class member now
}
// We want the window's client area to match the image size
RECT rcClient, rcWindow;
POINT ptDiff;
GetClientRect(hwnd, &rcClient);
GetWindowRect(hwnd, &rcWindow);
ptDiff.x = (rcWindow.right - rcWindow.left) - rcClient.right;
ptDiff.y = (rcWindow.bottom - rcWindow.top) - rcClient.bottom;
MoveWindow(hwnd,rcWindow.left, rcWindow.top, width + ptDiff.x, height + ptDiff.y, true);
if ((customizationFlags&WindowFlags.dontAutoShow) == 0) {
ShowWindow(hwnd, SW_SHOWNORMAL);
} else {
_hidden = true;
}
this._visibleForTheFirstTimeCalled = false; // hack!
}
void dispose() {
if(buffer)
DeleteObject(buffer);
}
void closeWindow() {
DestroyWindow(hwnd);
}
bool setOpacity(ubyte alpha) {
return SetLayeredWindowAttributes(hwnd, 0, alpha, LWA_ALPHA) == TRUE;
}
HANDLE currentCursor;
// returns zero if it recognized the event
static int triggerEvents(HWND hwnd, uint msg, WPARAM wParam, LPARAM lParam, int offsetX, int offsetY, SimpleWindow wind) {
MouseEvent mouse;
void mouseEvent(bool isScreen, ulong mods) {
auto x = LOWORD(lParam);
auto y = HIWORD(lParam);
if(isScreen) {
POINT p;
p.x = x;
p.y = y;
ScreenToClient(hwnd, &p);
x = cast(ushort) p.x;
y = cast(ushort) p.y;
}
if(wind.resizability == Resizability.automaticallyScaleIfPossible) {
x = cast(ushort)( x * wind._virtualWidth / wind._width );
y = cast(ushort)( y * wind._virtualHeight / wind._height );
}
mouse.x = x + offsetX;
mouse.y = y + offsetY;
wind.mdx(mouse);
mouse.modifierState = cast(int) mods;
mouse.window = wind;
if(wind.handleMouseEvent)
wind.handleMouseEvent(mouse);
}
switch(msg) {
case WM_GETMINMAXINFO:
MINMAXINFO* mmi = cast(MINMAXINFO*) lParam;
if(wind.minWidth > 0) {
RECT rect;
rect.left = 100;
rect.top = 100;
rect.right = wind.minWidth + 100;
rect.bottom = wind.minHeight + 100;
if(!AdjustWindowRect(&rect, GetWindowLong(wind.hwnd, GWL_STYLE), GetMenu(wind.hwnd) !is null))
throw new WindowsApiException("AdjustWindowRect");
mmi.ptMinTrackSize.x = rect.right - rect.left;
mmi.ptMinTrackSize.y = rect.bottom - rect.top;
}
if(wind.maxWidth < int.max) {
RECT rect;
rect.left = 100;
rect.top = 100;
rect.right = wind.maxWidth + 100;
rect.bottom = wind.maxHeight + 100;
if(!AdjustWindowRect(&rect, GetWindowLong(wind.hwnd, GWL_STYLE), GetMenu(wind.hwnd) !is null))
throw new WindowsApiException("AdjustWindowRect");
mmi.ptMaxTrackSize.x = rect.right - rect.left;
mmi.ptMaxTrackSize.y = rect.bottom - rect.top;
}
break;
case WM_CHAR:
wchar c = cast(wchar) wParam;
if(wind.handleCharEvent)
wind.handleCharEvent(cast(dchar) c);
break;
case WM_SETFOCUS:
case WM_KILLFOCUS:
wind._focused = (msg == WM_SETFOCUS);
if (msg == WM_SETFOCUS) altPressed = false; //k8: reset alt state on defocus (it is better than nothing...)
if(wind.onFocusChange)
wind.onFocusChange(msg == WM_SETFOCUS);
break;
case WM_SYSKEYDOWN:
goto case;
case WM_SYSKEYUP:
if(lParam & (1 << 29)) {
goto case;
} else {
// no window has keyboard focus
goto default;
}
case WM_KEYDOWN:
case WM_KEYUP:
KeyEvent ev;
ev.key = cast(Key) wParam;
ev.pressed = (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN);
if (wParam == 0x12) ev.key = Key.Alt; // windows does it this way
ev.hardwareCode = (lParam & 0xff0000) >> 16;
if(GetKeyState(Key.Shift)&0x8000 || GetKeyState(Key.Shift_r)&0x8000)
ev.modifierState |= ModifierState.shift;
//k8: this doesn't work; thanks for nothing, windows
/*if(GetKeyState(Key.Alt)&0x8000 || GetKeyState(Key.Alt_r)&0x8000)
ev.modifierState |= ModifierState.alt;*/
// this never seems to actually be set
// if (lParam & 0x2000 /* KF_ALTDOWN */) ev.modifierState |= ModifierState.alt; else ev.modifierState &= ~ModifierState.alt;
if (wParam == 0x12) {
altPressed = (msg == WM_SYSKEYDOWN);
}
if(msg == WM_KEYDOWN || msg == WM_KEYUP) {
altPressed = false;
}
// sdpyPrintDebugString(altPressed ? "alt down" : " up ");
if (altPressed) ev.modifierState |= ModifierState.alt; else ev.modifierState &= ~ModifierState.alt;
if(GetKeyState(Key.Ctrl)&0x8000 || GetKeyState(Key.Ctrl_r)&0x8000)
ev.modifierState |= ModifierState.ctrl;
if(GetKeyState(Key.Windows)&0x8000 || GetKeyState(Key.Windows_r)&0x8000)
ev.modifierState |= ModifierState.windows;
if(GetKeyState(Key.NumLock))
ev.modifierState |= ModifierState.numLock;
if(GetKeyState(Key.CapsLock))
ev.modifierState |= ModifierState.capsLock;
/+
// we always want to send the character too, so let's convert it
ubyte[256] state;
wchar[16] buffer;
GetKeyboardState(state.ptr);
ToUnicodeEx(wParam, lParam, state.ptr, buffer.ptr, buffer.length, 0, null);
foreach(dchar d; buffer) {
ev.character = d;
break;
}
+/
ev.window = wind;
if(wind.handleKeyEvent)
wind.handleKeyEvent(ev);
break;
case 0x020a /*WM_MOUSEWHEEL*/:
// send click
mouse.type = cast(MouseEventType) 1;
mouse.button = ((GET_WHEEL_DELTA_WPARAM(wParam) > 0) ? MouseButton.wheelUp : MouseButton.wheelDown);
mouseEvent(true, LOWORD(wParam));
// also send release
mouse.type = cast(MouseEventType) 2;
mouse.button = ((GET_WHEEL_DELTA_WPARAM(wParam) > 0) ? MouseButton.wheelUp : MouseButton.wheelDown);
mouseEvent(true, LOWORD(wParam));
break;
case WM_MOUSEMOVE:
mouse.type = cast(MouseEventType) 0;
mouseEvent(false, wParam);
break;
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK:
mouse.type = cast(MouseEventType) 1;
mouse.button = MouseButton.left;
mouse.doubleClick = msg == WM_LBUTTONDBLCLK;
mouseEvent(false, wParam);
break;
case WM_LBUTTONUP:
mouse.type = cast(MouseEventType) 2;
mouse.button = MouseButton.left;
mouseEvent(false, wParam);
break;
case WM_RBUTTONDOWN:
case WM_RBUTTONDBLCLK:
mouse.type = cast(MouseEventType) 1;
mouse.button = MouseButton.right;
mouse.doubleClick = msg == WM_RBUTTONDBLCLK;
mouseEvent(false, wParam);
break;
case WM_RBUTTONUP:
mouse.type = cast(MouseEventType) 2;
mouse.button = MouseButton.right;
mouseEvent(false, wParam);
break;
case WM_MBUTTONDOWN:
case WM_MBUTTONDBLCLK:
mouse.type = cast(MouseEventType) 1;
mouse.button = MouseButton.middle;
mouse.doubleClick = msg == WM_MBUTTONDBLCLK;
mouseEvent(false, wParam);
break;
case WM_MBUTTONUP:
mouse.type = cast(MouseEventType) 2;
mouse.button = MouseButton.middle;
mouseEvent(false, wParam);
break;
case WM_XBUTTONDOWN:
case WM_XBUTTONDBLCLK:
mouse.type = cast(MouseEventType) 1;
mouse.button = HIWORD(wParam) == 1 ? MouseButton.backButton : MouseButton.forwardButton;
mouse.doubleClick = msg == WM_XBUTTONDBLCLK;
mouseEvent(false, wParam);
return 1; // MSDN says special treatment here, return TRUE to bypass simulation programs
case WM_XBUTTONUP:
mouse.type = cast(MouseEventType) 2;
mouse.button = HIWORD(wParam) == 1 ? MouseButton.backButton : MouseButton.forwardButton;
mouseEvent(false, wParam);
return 1; // see: https://msdn.microsoft.com/en-us/library/windows/desktop/ms646246(v=vs.85).aspx
default: return 1;
}
return 0;
}
HWND hwnd;
private int oldWidth;
private int oldHeight;
private bool inSizeMove;
/++
If this is true, the live resize events will trigger all the size things as they drag. If false, those events only come when the size is complete; when the user lets go of the mouse button.
History:
Added November 23, 2021
Not fully stable, may be moved out of the impl struct.
Default value changed to `true` on February 15, 2021
+/
bool doLiveResizing = true;
package int bmpWidth;
package int bmpHeight;
// the extern(Windows) wndproc should just forward to this
LRESULT windowProcedure(HWND hwnd, uint msg, WPARAM wParam, LPARAM lParam) {
try {
assert(hwnd is this.hwnd);
if(triggerEvents(hwnd, msg, wParam, lParam, 0, 0, this))
switch(msg) {
case WM_MENUCHAR: // menu active but key not associated with a thing.
// you would ideally use this for like a search function but sdpy not that ideally designed. alas.
// The main things we can do are select, execute, close, or ignore
// the default is ignore, but it doesn't *just* ignore it - it also dings an audio alert to
// the user. This can be a bit annoying for sdpy things so instead im overriding and setting it
// to close, which can be really annoying when you hit the wrong button. but meh i think for sdpy
// that's the lesser bad choice rn. Can always override by returning true in triggerEvents....
// returns the value in the *high order word* of the return value
// hence the << 16
return 1 << 16; // MNC_CLOSE, close the menu without dinging at the user
case WM_SETCURSOR:
if(cast(HWND) wParam !is hwnd)
return 0; // further processing elsewhere
if(LOWORD(lParam) == HTCLIENT && (this.curHidden > 0 || currentCursor !is null)) {
SetCursor(this.curHidden > 0 ? null : currentCursor);
return 1;
} else {
return DefWindowProc(hwnd, msg, wParam, lParam);
}
//break;
case WM_CLOSE:
if (this.closeQuery !is null) this.closeQuery(); else this.close();
break;
case WM_DESTROY:
if (this.onDestroyed !is null) try { this.onDestroyed(); } catch (Exception e) {} // sorry
SimpleWindow.nativeMapping.remove(hwnd);
CapableOfHandlingNativeEvent.nativeHandleMapping.remove(hwnd);
bool anyImportant = false;
foreach(SimpleWindow w; SimpleWindow.nativeMapping)
if(w.beingOpenKeepsAppOpen) {
anyImportant = true;
break;
}
if(!anyImportant) {
PostQuitMessage(0);
}
break;
case 0x02E0 /*WM_DPICHANGED*/:
this.actualDpi_ = LOWORD(wParam); // hiword is the y param but it is the same per docs
RECT* prcNewWindow = cast(RECT*)lParam;
// docs say this is the recommended position and we should honor it
SetWindowPos(hwnd,
null,
prcNewWindow.left,
prcNewWindow.top,
prcNewWindow.right - prcNewWindow.left,
prcNewWindow.bottom - prcNewWindow.top,
SWP_NOZORDER | SWP_NOACTIVATE);
// doing this because of https://github.com/microsoft/Windows-classic-samples/blob/main/Samples/DPIAwarenessPerWindow/client/DpiAwarenessContext.cpp
// im not sure it is completely correct
// but without it the tabs and such do look weird as things change.
if(SystemParametersInfoForDpi) {
LOGFONT lfText;
SystemParametersInfoForDpi(SPI_GETICONTITLELOGFONT, lfText.sizeof, &lfText, FALSE, this.actualDpi_);
HFONT hFontNew = CreateFontIndirect(&lfText);
if (hFontNew)
{
//DeleteObject(hFontOld);
static extern(Windows) BOOL helper(HWND hWnd, LPARAM lParam) {
SendMessage(hWnd, WM_SETFONT, cast(WPARAM)lParam, MAKELPARAM(TRUE, 0));
return TRUE;
}
EnumChildWindows(hwnd, &helper, cast(LPARAM) hFontNew);
}
}
if(this.onDpiChanged)
this.onDpiChanged();
break;
case WM_ENTERIDLE:
// when a menu is up, it stops normal event processing (modal message loop)
// but this at least gives us a chance to SOMETIMES catch up
// FIXME: I can use SetTimer while idle to keep working i think... but idk when i'd destroy it.
SimpleWindow.processAllCustomEvents;
SimpleWindow.processAllCustomEvents;
SleepEx(0, true);
break;
case WM_SIZE:
if(wParam == 1 /* SIZE_MINIMIZED */)
break;
_width = LOWORD(lParam);
_height = HIWORD(lParam);
// I want to avoid tearing in the windows (my code is inefficient
// so this is a hack around that) so while sizing, we don't trigger,
// but we do want to trigger on events like mazimize.
if(!inSizeMove || doLiveResizing)
goto size_changed;
break;
/+
case WM_SIZING:
import std.stdio; writeln("size");
break;
+/
// I don't like the tearing I get when redrawing on WM_SIZE
// (I know there's other ways to fix that but I don't like that behavior anyway)
// so instead it is going to redraw only at the end of a size.
case 0x0231: /* WM_ENTERSIZEMOVE */
inSizeMove = true;
break;
case 0x0232: /* WM_EXITSIZEMOVE */
inSizeMove = false;
size_changed:
// nothing relevant changed, don't bother redrawing
if(oldWidth == _width && oldHeight == _height) {
break;
}
// note: OpenGL windows don't use a backing bmp, so no need to change them
// if resizability is anything other than allowResizing, it is meant to either stretch the one image or just do nothing
if(openglMode == OpenGlOptions.no) { // && resizability == Resizability.allowResizing) {
// gotta get the double buffer bmp to match the window
// FIXME: could this be more efficient? it never relinquishes a large bitmap
// if it is auto-scaled, we keep the backing bitmap the same size all the time
if(resizability != Resizability.automaticallyScaleIfPossible)
if(_width > bmpWidth || _height > bmpHeight) {
auto hdc = GetDC(hwnd);
auto oldBuffer = buffer;
buffer = CreateCompatibleBitmap(hdc, _width, _height);
auto hdcBmp = CreateCompatibleDC(hdc);
auto oldBmp = SelectObject(hdcBmp, buffer);
auto hdcOldBmp = CreateCompatibleDC(hdc);
auto oldOldBmp = SelectObject(hdcOldBmp, oldBuffer);
/+
RECT r;
r.left = 0;
r.top = 0;
r.right = width;
r.bottom = height;
auto c = Color.green;
auto brush = CreateSolidBrush(RGB(c.r, c.g, c.b));
FillRect(hdcBmp, &r, brush);
DeleteObject(brush);
+/
BitBlt(hdcBmp, 0, 0, bmpWidth, bmpHeight, hdcOldBmp, 0, 0, SRCCOPY);
bmpWidth = _width;
bmpHeight = _height;
SelectObject(hdcOldBmp, oldOldBmp);
DeleteDC(hdcOldBmp);
SelectObject(hdcBmp, oldBmp);
DeleteDC(hdcBmp);
ReleaseDC(hwnd, hdc);
DeleteObject(oldBuffer);
}
}
updateOpenglViewportIfNeeded(_width, _height);
if(resizability != Resizability.automaticallyScaleIfPossible)
if(windowResized !is null)
windowResized(_width, _height);
if(inSizeMove) {
SimpleWindow.processAllCustomEvents();
SimpleWindow.processAllCustomEvents();
} else {
// when it is all done, make sure everything is freshly drawn or there might be
// weird bugs left.
RedrawWindow(hwnd, null, null, RDW_ERASE | RDW_INVALIDATE | RDW_ALLCHILDREN);
}
oldWidth = this._width;
oldHeight = this._height;
break;
case WM_ERASEBKGND:
// call `visibleForTheFirstTime` here, so we can do initialization as early as possible
if (!this._visibleForTheFirstTimeCalled) {
this._visibleForTheFirstTimeCalled = true;
if (this.visibleForTheFirstTime !is null) {
this.visibleForTheFirstTime();
}
}
// block it in OpenGL mode, 'cause no sane person will (or should) draw windows controls over OpenGL scene
version(without_opengl) {} else {
if (openglMode == OpenGlOptions.yes) return 1;
}
// call windows default handler, so it can paint standard controls
goto default;
case WM_CTLCOLORBTN:
case WM_CTLCOLORSTATIC:
SetBkMode(cast(HDC) wParam, TRANSPARENT);
return cast(typeof(return)) //GetStockObject(NULL_BRUSH);
GetSysColorBrush(COLOR_3DFACE);
//break;
case WM_SHOWWINDOW:
this._visible = (wParam != 0);
if (!this._visibleForTheFirstTimeCalled && this._visible) {
this._visibleForTheFirstTimeCalled = true;
if (this.visibleForTheFirstTime !is null) {
this.visibleForTheFirstTime();
}
}
if (this.visibilityChanged !is null) this.visibilityChanged(this._visible);
break;
case WM_PAINT: {
if (!this._visibleForTheFirstTimeCalled) {
this._visibleForTheFirstTimeCalled = true;
if (this.visibleForTheFirstTime !is null) {
this.visibleForTheFirstTime();
}
}
BITMAP bm;
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
if(openglMode == OpenGlOptions.no) {
HDC hdcMem = CreateCompatibleDC(hdc);
HBITMAP hbmOld = SelectObject(hdcMem, buffer);
GetObject(buffer, bm.sizeof, &bm);
// FIXME: only BitBlt the invalidated rectangle, not the whole thing
if(resizability == Resizability.automaticallyScaleIfPossible)
StretchBlt(hdc, 0, 0, this._width, this._height, hdcMem, 0, 0, bm.bmWidth, bm.bmHeight, SRCCOPY);
else
BitBlt(hdc, 0, 0, bm.bmWidth, bm.bmHeight, hdcMem, 0, 0, SRCCOPY);
//BitBlt(hdc, ps.rcPaint.left, ps.rcPaint.top, ps.rcPaint.right - ps.rcPaint.left, ps.rcPaint.top - ps.rcPaint.bottom, hdcMem, 0, 0, SRCCOPY);
SelectObject(hdcMem, hbmOld);
DeleteDC(hdcMem);
EndPaint(hwnd, &ps);
} else {
EndPaint(hwnd, &ps);
version(without_opengl) {} else
redrawOpenGlSceneSoon();
}
} break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
catch(Throwable t) {
sdpyPrintDebugString(t.toString);
return 0;
}
}
}
mixin template NativeImageImplementation() {
HBITMAP handle;
ubyte* rawData;
final:
Color getPixel(int x, int y) {
auto itemsPerLine = ((cast(int) width * 3 + 3) / 4) * 4;
// remember, bmps are upside down
auto offset = itemsPerLine * (height - y - 1) + x * 3;
Color c;
if(enableAlpha)
c.a = rawData[offset + 3];
else
c.a = 255;
c.b = rawData[offset + 0];
c.g = rawData[offset + 1];
c.r = rawData[offset + 2];
c.unPremultiply();
return c;
}
void setPixel(int x, int y, Color c) {
auto itemsPerLine = ((cast(int) width * 3 + 3) / 4) * 4;
// remember, bmps are upside down
auto offset = itemsPerLine * (height - y - 1) + x * 3;
if(enableAlpha)
c.premultiply();
rawData[offset + 0] = c.b;
rawData[offset + 1] = c.g;
rawData[offset + 2] = c.r;
if(enableAlpha)
rawData[offset + 3] = c.a;
}
void convertToRgbaBytes(ubyte[] where) {
assert(where.length == this.width * this.height * 4);
auto itemsPerLine = ((cast(int) width * 3 + 3) / 4) * 4;
int idx = 0;
int offset = itemsPerLine * (height - 1);
// remember, bmps are upside down
for(int y = height - 1; y >= 0; y--) {
auto offsetStart = offset;
for(int x = 0; x < width; x++) {
where[idx + 0] = rawData[offset + 2]; // r
where[idx + 1] = rawData[offset + 1]; // g
where[idx + 2] = rawData[offset + 0]; // b
if(enableAlpha) {
where[idx + 3] = rawData[offset + 3]; // a
unPremultiplyRgba(where[idx .. idx + 4]);
offset++;
} else
where[idx + 3] = 255; // a
idx += 4;
offset += 3;
}
offset = offsetStart - itemsPerLine;
}
}
void setFromRgbaBytes(in ubyte[] what) {
assert(what.length == this.width * this.height * 4);
auto itemsPerLine = enableAlpha ? (width * 4) : (((cast(int) width * 3 + 3) / 4) * 4);
int idx = 0;
int offset = itemsPerLine * (height - 1);
// remember, bmps are upside down
for(int y = height - 1; y >= 0; y--) {
auto offsetStart = offset;
for(int x = 0; x < width; x++) {
if(enableAlpha) {
auto a = what[idx + 3];
rawData[offset + 2] = (a * what[idx + 0]) / 255; // r
rawData[offset + 1] = (a * what[idx + 1]) / 255; // g
rawData[offset + 0] = (a * what[idx + 2]) / 255; // b
rawData[offset + 3] = a; // a
//premultiplyBgra(rawData[offset .. offset + 4]);
offset++;
} else {
rawData[offset + 2] = what[idx + 0]; // r
rawData[offset + 1] = what[idx + 1]; // g
rawData[offset + 0] = what[idx + 2]; // b
}
idx += 4;
offset += 3;
}
offset = offsetStart - itemsPerLine;
}
}
void createImage(int width, int height, bool forcexshm=false, bool enableAlpha = false) {
BITMAPINFO infoheader;
infoheader.bmiHeader.biSize = infoheader.bmiHeader.sizeof;
infoheader.bmiHeader.biWidth = width;
infoheader.bmiHeader.biHeight = height;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biBitCount = enableAlpha ? 32: 24;
infoheader.bmiHeader.biCompression = BI_RGB;
handle = CreateDIBSection(
null,
&infoheader,
DIB_RGB_COLORS,
cast(void**) &rawData,
null,
0);
if(handle is null)
throw new WindowsApiException("create image failed");
}
void dispose() {
DeleteObject(handle);
}
}
enum KEY_ESCAPE = 27;
}
version(X11) {
/// This is the default font used. You might change this before doing anything else with
/// the library if you want to try something else. Surround that in `static if(UsingSimpledisplayX11)`
/// for cross-platform compatibility.
//__gshared string xfontstr = "-*-dejavu sans-medium-r-*-*-12-*-*-*-*-*-*-*";
//__gshared string xfontstr = "-*-dejavu sans-medium-r-*-*-12-*-*-*-*-*-*-*";
__gshared string xfontstr = "-*-lucida-medium-r-normal-sans-12-*-*-*-*-*-*-*";
//__gshared string xfontstr = "-*-fixed-medium-r-*-*-14-*-*-*-*-*-*-*";
alias int delegate(XEvent) NativeEventHandler;
alias Window NativeWindowHandle;
enum KEY_ESCAPE = 9;
mixin template NativeScreenPainterImplementation() {
Display* display;
Drawable d;
Drawable destiny;
// FIXME: should the gc be static too so it isn't recreated every time draw is called?
GC gc;
__gshared bool fontAttempted;
__gshared XFontStruct* defaultfont;
__gshared XFontSet defaultfontset;
XFontStruct* font;
XFontSet fontset;
void create(NativeWindowHandle window) {
this.display = XDisplayConnection.get();
Drawable buffer = None;
if(auto sw = cast(SimpleWindow) this.window) {
buffer = sw.impl.buffer;
this.destiny = cast(Drawable) window;
} else {
buffer = cast(Drawable) window;
this.destiny = None;
}
this.d = cast(Drawable) buffer;
auto dgc = DefaultGC(display, DefaultScreen(display));
this.gc = XCreateGC(display, d, 0, null);
XCopyGC(display, dgc, 0xffffffff, this.gc);
ensureDefaultFontLoaded();
font = defaultfont;
fontset = defaultfontset;
if(font) {
XSetFont(display, gc, font.fid);
}
}
static void ensureDefaultFontLoaded() {
if(!fontAttempted) {
auto display = XDisplayConnection.get;
auto font = XLoadQueryFont(display, xfontstr.ptr);
// if the user font choice fails, fixed is pretty reliable (required by X to start!) and not bad either
if(font is null) {
xfontstr = "-*-fixed-medium-r-*-*-13-*-*-*-*-*-*-*";
font = XLoadQueryFont(display, xfontstr.ptr);
}
char** lol;
int lol2;
char* lol3;
auto fontset = XCreateFontSet(display, xfontstr.ptr, &lol, &lol2, &lol3);
fontAttempted = true;
defaultfont = font;
defaultfontset = fontset;
}
}
arsd.color.Rectangle _clipRectangle;
void setClipRectangle(int x, int y, int width, int height) {
auto old = _clipRectangle;
_clipRectangle = arsd.color.Rectangle(Point(x, y), Size(width, height));
if(old == _clipRectangle)
return;
if(width == 0 || height == 0) {
XSetClipMask(display, gc, None);
if(xrenderPicturePainter) {
XRectangle[1] rects;
rects[0] = XRectangle(short.min, short.min, short.max, short.max);
XRenderSetPictureClipRectangles(display, xrenderPicturePainter, 0, 0, rects.ptr, cast(int) rects.length);
}
version(with_xft) {
if(xftFont is null || xftDraw is null)
return;
XftDrawSetClip(xftDraw, null);
}
} else {
XRectangle[1] rects;
rects[0] = XRectangle(cast(short)(x), cast(short)(y), cast(short) width, cast(short) height);
XSetClipRectangles(XDisplayConnection.get, gc, 0, 0, rects.ptr, 1, 0);
if(xrenderPicturePainter)
XRenderSetPictureClipRectangles(display, xrenderPicturePainter, 0, 0, rects.ptr, cast(int) rects.length);
version(with_xft) {
if(xftFont is null || xftDraw is null)
return;
XftDrawSetClipRectangles(xftDraw, 0, 0, rects.ptr, 1);
}
}
}
version(with_xft) {
XftFont* xftFont;
XftDraw* xftDraw;
XftColor xftColor;
void updateXftColor() {
if(xftFont is null)
return;
// not bothering with XftColorFree since p sure i don't need it on 24 bit displays....
XRenderColor colorIn = XRenderColor(_outlineColor.r * 255, _outlineColor.g * 255, _outlineColor.b * 255, _outlineColor.a * 255);
XftColorAllocValue(
display,
DefaultVisual(display, DefaultScreen(display)),
DefaultColormap(display, 0),
&colorIn,
&xftColor
);
}
}
private OperatingSystemFont _activeFont;
void setFont(OperatingSystemFont font) {
_activeFont = font;
version(with_xft) {
if(font && font.isXft && font.xftFont)
this.xftFont = font.xftFont;
else
this.xftFont = null;
if(this.xftFont) {
if(xftDraw is null) {
xftDraw = XftDrawCreate(
display,
d,
DefaultVisual(display, DefaultScreen(display)),
DefaultColormap(display, 0)
);
updateXftColor();
}
return;
}
}
if(font && font.font) {
this.font = font.font;
this.fontset = font.fontset;
XSetFont(display, gc, font.font.fid);
} else {
this.font = defaultfont;
this.fontset = defaultfontset;
}
}
private Picture xrenderPicturePainter;
bool manualInvalidations;
void invalidateRect(Rectangle invalidRect) {
// FIXME if manualInvalidations
}
void dispose() {
this.rasterOp = RasterOp.normal;
if(xrenderPicturePainter) {
XRenderFreePicture(display, xrenderPicturePainter);
xrenderPicturePainter = None;
}
// FIXME: this.window.width/height is probably wrong
// src x,y then dest x, y
if(destiny != None) {
// FIXME: if manual invalidations we can actually only copy some of the area.
// if(manualInvalidations)
XSetClipMask(display, gc, None);
XCopyArea(display, d, destiny, gc, 0, 0, this.window.width, this.window.height, 0, 0);
}
XFreeGC(display, gc);
version(with_xft)
if(xftDraw) {
XftDrawDestroy(xftDraw);
xftDraw = null;
}
/+
// this should prolly legit never be used since if it destroys the font handle from a OperatingSystemFont, it also ruins a reusable resource.
if(font && font !is defaultfont) {
XFreeFont(display, font);
font = null;
}
if(fontset && fontset !is defaultfontset) {
XFreeFontSet(display, fontset);
fontset = null;
}
+/
XFlush(display);
if(window.paintingFinishedDg !is null)
window.paintingFinishedDg()();
}
bool backgroundIsNotTransparent = true;
bool foregroundIsNotTransparent = true;
bool _penInitialized = false;
Pen _activePen;
Color _outlineColor;
Color _fillColor;
@property void pen(Pen p) {
if(_penInitialized && p == _activePen) {
return;
}
_penInitialized = true;
_activePen = p;
_outlineColor = p.color;
int style;
byte dashLength;
final switch(p.style) {
case Pen.Style.Solid:
style = 0 /*LineSolid*/;
break;
case Pen.Style.Dashed:
style = 1 /*LineOnOffDash*/;
dashLength = 4;
break;
case Pen.Style.Dotted:
style = 1 /*LineOnOffDash*/;
dashLength = 1;
break;
}
XSetLineAttributes(display, gc, p.width, style, 0, 0);
if(dashLength)
XSetDashes(display, gc, 0, &dashLength, 1);
if(p.color.a == 0) {
foregroundIsNotTransparent = false;
return;
}
foregroundIsNotTransparent = true;
XSetForeground(display, gc, colorToX(p.color, display));
version(with_xft)
updateXftColor();
}
RasterOp _currentRasterOp;
bool _currentRasterOpInitialized = false;
@property void rasterOp(RasterOp op) {
if(_currentRasterOpInitialized && _currentRasterOp == op)
return;
_currentRasterOp = op;
_currentRasterOpInitialized = true;
int mode;
final switch(op) {
case RasterOp.normal:
mode = GXcopy;
break;
case RasterOp.xor:
mode = GXxor;
break;
}
XSetFunction(display, gc, mode);
}
bool _fillColorInitialized = false;
@property void fillColor(Color c) {
if(_fillColorInitialized && _fillColor == c)
return; // already good, no need to waste time calling it
_fillColor = c;
_fillColorInitialized = true;
if(c.a == 0) {
backgroundIsNotTransparent = false;
return;
}
backgroundIsNotTransparent = true;
XSetBackground(display, gc, colorToX(c, display));
}
void swapColors() {
auto tmp = _fillColor;
fillColor = _outlineColor;
auto newPen = _activePen;
newPen.color = tmp;
pen(newPen);
}
uint colorToX(Color c, Display* display) {
auto visual = DefaultVisual(display, DefaultScreen(display));
import core.bitop;
uint color = 0;
{
auto startBit = bsf(visual.red_mask);
auto lastBit = bsr(visual.red_mask);
auto r = cast(uint) c.r;
r >>= 7 - (lastBit - startBit);
r <<= startBit;
color |= r;
}
{
auto startBit = bsf(visual.green_mask);
auto lastBit = bsr(visual.green_mask);
auto g = cast(uint) c.g;
g >>= 7 - (lastBit - startBit);
g <<= startBit;
color |= g;
}
{
auto startBit = bsf(visual.blue_mask);
auto lastBit = bsr(visual.blue_mask);
auto b = cast(uint) c.b;
b >>= 7 - (lastBit - startBit);
b <<= startBit;
color |= b;
}
return color;
}
void drawImage(int x, int y, Image i, int ix, int iy, int w, int h) {
// source x, source y
if(ix >= i.width) return;
if(iy >= i.height) return;
if(ix + w > i.width) w = i.width - ix;
if(iy + h > i.height) h = i.height - iy;
if(i.usingXshm)
XShmPutImage(display, d, gc, i.handle, ix, iy, x, y, w, h, false);
else
XPutImage(display, d, gc, i.handle, ix, iy, x, y, w, h);
}
void drawPixmap(Sprite s, int x, int y, int ix, int iy, int w, int h) {
if(s.enableAlpha) {
// the Sprite must be created first, meaning if we're here, XRender is already loaded
if(this.xrenderPicturePainter == None) {
XRenderPictureAttributes attrs;
// FIXME: I can prolly reuse this as long as the pixmap itself is valid.
xrenderPicturePainter = XRenderCreatePicture(display, d, Sprite.RGB24, 0, &attrs);
// need to initialize the clip
XRectangle[1] rects;
rects[0] = XRectangle(cast(short)(_clipRectangle.left), cast(short)(_clipRectangle.top), cast(short) _clipRectangle.width, cast(short) _clipRectangle.height);
if(_clipRectangle != Rectangle.init)
XRenderSetPictureClipRectangles(display, xrenderPicturePainter, 0, 0, rects.ptr, cast(int) rects.length);
}
XRenderComposite(
display,
3, // PicOpOver
s.xrenderPicture,
None,
this.xrenderPicturePainter,
ix,
iy,
0,
0,
x,
y,
w ? w : s.width,
h ? h : s.height
);
} else {
XCopyArea(display, s.handle, d, gc, ix, iy, w ? w : s.width, h ? h : s.height, x, y);
}
}
int fontHeight() {
version(with_xft)
if(xftFont !is null)
return xftFont.height;
if(font)
return font.max_bounds.ascent + font.max_bounds.descent;
return 12; // pretty common default...
}
int textWidth(in char[] line) {
version(with_xft)
if(xftFont) {
if(line.length == 0)
return 0;
XGlyphInfo extents;
XftTextExtentsUtf8(display, xftFont, line.ptr, cast(int) line.length, &extents);
return extents.width;
}
if(fontset) {
if(line.length == 0)
return 0;
XRectangle rect;
Xutf8TextExtents(fontset, line.ptr, cast(int) line.length, null, &rect);
return rect.width;
}
if(font)
// FIXME: unicode
return XTextWidth( font, line.ptr, cast(int) line.length);
else
return fontHeight / 2 * cast(int) line.length; // if no font is loaded, it is prolly Fixed, which is a 2:1 ratio
}
Size textSize(in char[] text) {
auto maxWidth = 0;
auto lineHeight = fontHeight;
int h = text.length ? 0 : lineHeight + 4; // if text is empty, it still gives the line height
foreach(line; text.split('\n')) {
int textWidth = this.textWidth(line);
if(textWidth > maxWidth)
maxWidth = textWidth;
h += lineHeight + 4;
}
return Size(maxWidth, h);
}
void drawText(in int x, in int y, in int x2, in int y2, in char[] originalText, in uint alignment) {
const(char)[] text;
version(with_xft)
if(xftFont) {
text = originalText;
goto loaded;
}
if(fontset)
text = originalText;
else {
text.reserve(originalText.length);
// the first 256 unicode codepoints are the same as ascii and latin-1, which is what X expects, so we can keep all those
// then strip the rest so there isn't garbage
foreach(dchar ch; originalText)
if(ch < 256)
text ~= cast(ubyte) ch;
else
text ~= 191; // FIXME: using a random character (upside down question mark) to fill the space
}
loaded:
if(text.length == 0)
return;
// FIXME: should we clip it to the bounding box?
int textHeight = fontHeight;
auto lines = text.split('\n');
const lineHeight = textHeight;
textHeight *= lines.length;
int cy = y;
if(alignment & TextAlignment.VerticalBottom) {
if(y2 <= 0)
return;
auto h = y2 - y;
if(h > textHeight) {
cy += h - textHeight;
cy -= lineHeight / 2;
}
} else if(alignment & TextAlignment.VerticalCenter) {
if(y2 <= 0)
return;
auto h = y2 - y;
if(textHeight < h) {
cy += (h - textHeight) / 2;
//cy -= lineHeight / 4;
}
}
foreach(line; text.split('\n')) {
int textWidth = this.textWidth(line);
int px = x, py = cy;
if(alignment & TextAlignment.Center) {
if(x2 <= 0)
return;
auto w = x2 - x;
if(w > textWidth)
px += (w - textWidth) / 2;
} else if(alignment & TextAlignment.Right) {
if(x2 <= 0)
return;
auto pos = x2 - textWidth;
if(pos > x)
px = pos;
}
version(with_xft)
if(xftFont) {
XftDrawStringUtf8(xftDraw, &xftColor, xftFont, px, py + xftFont.ascent, line.ptr, cast(int) line.length);
goto carry_on;
}
if(fontset)
Xutf8DrawString(display, d, fontset, gc, px, py + (font ? font.max_bounds.ascent : lineHeight), line.ptr, cast(int) line.length);
else
XDrawString(display, d, gc, px, py + (font ? font.max_bounds.ascent : lineHeight), line.ptr, cast(int) line.length);
carry_on:
cy += lineHeight + 4;
}
}
void drawPixel(int x, int y) {
XDrawPoint(display, d, gc, x, y);
}
// The basic shapes, outlined
void drawLine(int x1, int y1, int x2, int y2) {
if(foregroundIsNotTransparent)
XDrawLine(display, d, gc, x1, y1, x2, y2);
}
void drawRectangle(int x, int y, int width, int height) {
if(backgroundIsNotTransparent) {
swapColors();
XFillRectangle(display, d, gc, x+1, y+1, width-2, height-2); // Need to ensure pixels are only drawn once...
swapColors();
}
// since X centers the line on the coordinates, we try to undo that with the width/2 thing here so it is aligned in the rectangle's bounds
if(foregroundIsNotTransparent)
XDrawRectangle(display, d, gc, x + _activePen.width / 2, y + _activePen.width / 2, width - 1 - _activePen.width / 2, height - 1 - _activePen.width / 2);
}
/// Arguments are the points of the bounding rectangle
void drawEllipse(int x1, int y1, int x2, int y2) {
drawArc(x1, y1, x2 - x1, y2 - y1, 0, 360 * 64);
}
// NOTE: start and finish are in units of degrees * 64
void drawArc(int x1, int y1, int width, int height, int start, int finish) {
if(backgroundIsNotTransparent) {
swapColors();
XFillArc(display, d, gc, x1, y1, width, height, start, finish);
swapColors();
}
if(foregroundIsNotTransparent) {
XDrawArc(display, d, gc, x1, y1, width, height, start, finish);
// Windows draws the straight lines on the edges too so FIXME sort of
}
}
void drawPolygon(Point[] vertexes) {
XPoint[16] pointsBuffer;
XPoint[] points;
if(vertexes.length <= pointsBuffer.length)
points = pointsBuffer[0 .. vertexes.length];
else
points.length = vertexes.length;
foreach(i, p; vertexes) {
points[i].x = cast(short) p.x;
points[i].y = cast(short) p.y;
}
if(backgroundIsNotTransparent) {
swapColors();
XFillPolygon(display, d, gc, points.ptr, cast(int) points.length, PolygonShape.Complex, CoordMode.CoordModeOrigin);
swapColors();
}
if(foregroundIsNotTransparent) {
XDrawLines(display, d, gc, points.ptr, cast(int) points.length, CoordMode.CoordModeOrigin);
}
}
}
/* XRender { */
struct XRenderColor {
ushort red;
ushort green;
ushort blue;
ushort alpha;
}
alias Picture = XID;
alias PictFormat = XID;
struct XGlyphInfo {
ushort width;
ushort height;
short x;
short y;
short xOff;
short yOff;
}
struct XRenderDirectFormat {
short red;
short redMask;
short green;
short greenMask;
short blue;
short blueMask;
short alpha;
short alphaMask;
}
struct XRenderPictFormat {
PictFormat id;
int type;
int depth;
XRenderDirectFormat direct;
Colormap colormap;
}
enum PictFormatID = (1 << 0);
enum PictFormatType = (1 << 1);
enum PictFormatDepth = (1 << 2);
enum PictFormatRed = (1 << 3);
enum PictFormatRedMask =(1 << 4);
enum PictFormatGreen = (1 << 5);
enum PictFormatGreenMask=(1 << 6);
enum PictFormatBlue = (1 << 7);
enum PictFormatBlueMask =(1 << 8);
enum PictFormatAlpha = (1 << 9);
enum PictFormatAlphaMask=(1 << 10);
enum PictFormatColormap =(1 << 11);
struct XRenderPictureAttributes {
int repeat;
Picture alpha_map;
int alpha_x_origin;
int alpha_y_origin;
int clip_x_origin;
int clip_y_origin;
Pixmap clip_mask;
Bool graphics_exposures;
int subwindow_mode;
int poly_edge;
int poly_mode;
Atom dither;
Bool component_alpha;
}
alias int XFixed;
struct XPointFixed {
XFixed x, y;
}
struct XCircle {
XFixed x;
XFixed y;
XFixed radius;
}
struct XTransform {
XFixed[3][3] matrix;
}
struct XFilters {
int nfilter;
char **filter;
int nalias;
short *alias_;
}
struct XIndexValue {
c_ulong pixel;
ushort red, green, blue, alpha;
}
struct XAnimCursor {
Cursor cursor;
c_ulong delay;
}
struct XLinearGradient {
XPointFixed p1;
XPointFixed p2;
}
struct XRadialGradient {
XCircle inner;
XCircle outer;
}
struct XConicalGradient {
XPointFixed center;
XFixed angle; /* in degrees */
}
enum PictStandardARGB32 = 0;
enum PictStandardRGB24 = 1;
enum PictStandardA8 = 2;
enum PictStandardA4 = 3;
enum PictStandardA1 = 4;
enum PictStandardNUM = 5;
interface XRender {
extern(C) @nogc:
Bool XRenderQueryExtension (Display *dpy, int *event_basep, int *error_basep);
Status XRenderQueryVersion (Display *dpy,
int *major_versionp,
int *minor_versionp);
Status XRenderQueryFormats (Display *dpy);
int XRenderQuerySubpixelOrder (Display *dpy, int screen);
Bool XRenderSetSubpixelOrder (Display *dpy, int screen, int subpixel);
XRenderPictFormat *
XRenderFindVisualFormat (Display *dpy, const Visual *visual);
XRenderPictFormat *
XRenderFindFormat (Display *dpy,
c_ulong mask,
const XRenderPictFormat *templ,
int count);
XRenderPictFormat *
XRenderFindStandardFormat (Display *dpy,
int format);
XIndexValue *
XRenderQueryPictIndexValues(Display *dpy,
const XRenderPictFormat *format,
int *num);
Picture XRenderCreatePicture(
Display *dpy,
Drawable drawable,
const XRenderPictFormat *format,
c_ulong valuemask,
const XRenderPictureAttributes *attributes);
void XRenderChangePicture (Display *dpy,
Picture picture,
c_ulong valuemask,
const XRenderPictureAttributes *attributes);
void
XRenderSetPictureClipRectangles (Display *dpy,
Picture picture,
int xOrigin,
int yOrigin,
const XRectangle *rects,
int n);
void
XRenderSetPictureClipRegion (Display *dpy,
Picture picture,
Region r);
void
XRenderSetPictureTransform (Display *dpy,
Picture picture,
XTransform *transform);
void
XRenderFreePicture (Display *dpy,
Picture picture);
void
XRenderComposite (Display *dpy,
int op,
Picture src,
Picture mask,
Picture dst,
int src_x,
int src_y,
int mask_x,
int mask_y,
int dst_x,
int dst_y,
uint width,
uint height);
Picture XRenderCreateSolidFill (Display *dpy,
const XRenderColor *color);
Picture XRenderCreateLinearGradient (Display *dpy,
const XLinearGradient *gradient,
const XFixed *stops,
const XRenderColor *colors,
int nstops);
Picture XRenderCreateRadialGradient (Display *dpy,
const XRadialGradient *gradient,
const XFixed *stops,
const XRenderColor *colors,
int nstops);
Picture XRenderCreateConicalGradient (Display *dpy,
const XConicalGradient *gradient,
const XFixed *stops,
const XRenderColor *colors,
int nstops);
Cursor
XRenderCreateCursor (Display *dpy,
Picture source,
uint x,
uint y);
XFilters *
XRenderQueryFilters (Display *dpy, Drawable drawable);
void
XRenderSetPictureFilter (Display *dpy,
Picture picture,
const char *filter,
XFixed *params,
int nparams);
Cursor
XRenderCreateAnimCursor (Display *dpy,
int ncursor,
XAnimCursor *cursors);
}
__gshared bool XRenderLibrarySuccessfullyLoaded = true;
mixin DynamicLoad!(XRender, "Xrender", 1, XRenderLibrarySuccessfullyLoaded) XRenderLibrary;
/* XRender } */
/* Xrandr { */
struct XRRMonitorInfo {
Atom name;
Bool primary;
Bool automatic;
int noutput;
int x;
int y;
int width;
int height;
int mwidth;
int mheight;
/*RROutput*/ void *outputs;
}
struct XRRScreenChangeNotifyEvent {
int type; /* event base */
c_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window; /* window which selected for this event */
Window root; /* Root window for changed screen */
Time timestamp; /* when the screen change occurred */
Time config_timestamp; /* when the last configuration change */
ushort/*SizeID*/ size_index;
ushort/*SubpixelOrder*/ subpixel_order;
ushort/*Rotation*/ rotation;
int width;
int height;
int mwidth;
int mheight;
}
enum RRScreenChangeNotify = 0;
enum RRScreenChangeNotifyMask = 1;
__gshared int xrrEventBase = -1;
interface XRandr {
extern(C) @nogc:
Bool XRRQueryExtension (Display *dpy, int *event_base_return, int *error_base_return);
Status XRRQueryVersion (Display *dpy, int *major_version_return, int *minor_version_return);
XRRMonitorInfo * XRRGetMonitors(Display *dpy, Window window, Bool get_active, int *nmonitors);
void XRRFreeMonitors(XRRMonitorInfo *monitors);
void XRRSelectInput(Display *dpy, Window window, int mask);
}
__gshared bool XRandrLibrarySuccessfullyLoaded = true;
mixin DynamicLoad!(XRandr, "Xrandr", 2, XRandrLibrarySuccessfullyLoaded) XRandrLibrary;
/* Xrandr } */
/* Xft { */
// actually freetype
alias void FT_Face;
// actually fontconfig
private alias FcBool = int;
alias void FcCharSet;
alias void FcPattern;
alias void FcResult;
enum FcEndian { FcEndianBig, FcEndianLittle }
struct FcFontSet {
int nfont;
int sfont;
FcPattern** fonts;
}
// actually XRegion
struct BOX {
short x1, x2, y1, y2;
}
struct _XRegion {
c_long size;
c_long numRects;
BOX* rects;
BOX extents;
}
alias Region = _XRegion*;
// ok actually Xft
struct XftFontInfo;
struct XftFont {
int ascent;
int descent;
int height;
int max_advance_width;
FcCharSet* charset;
FcPattern* pattern;
}
struct XftDraw;
struct XftColor {
c_ulong pixel;
XRenderColor color;
}
struct XftCharSpec {
dchar ucs4;
short x;
short y;
}
struct XftCharFontSpec {
XftFont *font;
dchar ucs4;
short x;
short y;
}
struct XftGlyphSpec {
uint glyph;
short x;
short y;
}
struct XftGlyphFontSpec {
XftFont *font;
uint glyph;
short x;
short y;
}
interface Xft {
extern(C) @nogc pure:
Bool XftColorAllocName (Display *dpy,
const Visual *visual,
Colormap cmap,
const char *name,
XftColor *result);
Bool XftColorAllocValue (Display *dpy,
Visual *visual,
Colormap cmap,
const XRenderColor *color,
XftColor *result);
void XftColorFree (Display *dpy,
Visual *visual,
Colormap cmap,
XftColor *color);
Bool XftDefaultHasRender (Display *dpy);
Bool XftDefaultSet (Display *dpy, FcPattern *defaults);
void XftDefaultSubstitute (Display *dpy, int screen, FcPattern *pattern);
XftDraw * XftDrawCreate (Display *dpy,
Drawable drawable,
Visual *visual,
Colormap colormap);
XftDraw * XftDrawCreateBitmap (Display *dpy,
Pixmap bitmap);
XftDraw * XftDrawCreateAlpha (Display *dpy,
Pixmap pixmap,
int depth);
void XftDrawChange (XftDraw *draw,
Drawable drawable);
Display * XftDrawDisplay (XftDraw *draw);
Drawable XftDrawDrawable (XftDraw *draw);
Colormap XftDrawColormap (XftDraw *draw);
Visual * XftDrawVisual (XftDraw *draw);
void XftDrawDestroy (XftDraw *draw);
Picture XftDrawPicture (XftDraw *draw);
Picture XftDrawSrcPicture (XftDraw *draw, const XftColor *color);
void XftDrawGlyphs (XftDraw *draw,
const XftColor *color,
XftFont *pub,
int x,
int y,
const uint *glyphs,
int nglyphs);
void XftDrawString8 (XftDraw *draw,
const XftColor *color,
XftFont *pub,
int x,
int y,
const char *string,
int len);
void XftDrawString16 (XftDraw *draw,
const XftColor *color,
XftFont *pub,
int x,
int y,
const wchar *string,
int len);
void XftDrawString32 (XftDraw *draw,
const XftColor *color,
XftFont *pub,
int x,
int y,
const dchar *string,
int len);
void XftDrawStringUtf8 (XftDraw *draw,
const XftColor *color,
XftFont *pub,
int x,
int y,
const char *string,
int len);
void XftDrawStringUtf16 (XftDraw *draw,
const XftColor *color,
XftFont *pub,
int x,
int y,
const char *string,
FcEndian endian,
int len);
void XftDrawCharSpec (XftDraw *draw,
const XftColor *color,
XftFont *pub,
const XftCharSpec *chars,
int len);
void XftDrawCharFontSpec (XftDraw *draw,
const XftColor *color,
const XftCharFontSpec *chars,
int len);
void XftDrawGlyphSpec (XftDraw *draw,
const XftColor *color,
XftFont *pub,
const XftGlyphSpec *glyphs,
int len);
void XftDrawGlyphFontSpec (XftDraw *draw,
const XftColor *color,
const XftGlyphFontSpec *glyphs,
int len);
void XftDrawRect (XftDraw *draw,
const XftColor *color,
int x,
int y,
uint width,
uint height);
Bool XftDrawSetClip (XftDraw *draw,
Region r);
Bool XftDrawSetClipRectangles (XftDraw *draw,
int xOrigin,
int yOrigin,
const XRectangle *rects,
int n);
void XftDrawSetSubwindowMode (XftDraw *draw,
int mode);
void XftGlyphExtents (Display *dpy,
XftFont *pub,
const uint *glyphs,
int nglyphs,
XGlyphInfo *extents);
void XftTextExtents8 (Display *dpy,
XftFont *pub,
const char *string,
int len,
XGlyphInfo *extents);
void XftTextExtents16 (Display *dpy,
XftFont *pub,
const wchar *string,
int len,
XGlyphInfo *extents);
void XftTextExtents32 (Display *dpy,
XftFont *pub,
const dchar *string,
int len,
XGlyphInfo *extents);
void XftTextExtentsUtf8 (Display *dpy,
XftFont *pub,
const char *string,
int len,
XGlyphInfo *extents);
void XftTextExtentsUtf16 (Display *dpy,
XftFont *pub,
const char *string,
FcEndian endian,
int len,
XGlyphInfo *extents);
FcPattern * XftFontMatch (Display *dpy,
int screen,
const FcPattern *pattern,
FcResult *result);
XftFont * XftFontOpen (Display *dpy, int screen, ...);
XftFont * XftFontOpenName (Display *dpy, int screen, const char *name);
XftFont * XftFontOpenXlfd (Display *dpy, int screen, const char *xlfd);
FT_Face XftLockFace (XftFont *pub);
void XftUnlockFace (XftFont *pub);
XftFontInfo * XftFontInfoCreate (Display *dpy, const FcPattern *pattern);
void XftFontInfoDestroy (Display *dpy, XftFontInfo *fi);
dchar XftFontInfoHash (const XftFontInfo *fi);
FcBool XftFontInfoEqual (const XftFontInfo *a, const XftFontInfo *b);
XftFont * XftFontOpenInfo (Display *dpy,
FcPattern *pattern,
XftFontInfo *fi);
XftFont * XftFontOpenPattern (Display *dpy, FcPattern *pattern);
XftFont * XftFontCopy (Display *dpy, XftFont *pub);
void XftFontClose (Display *dpy, XftFont *pub);
FcBool XftInitFtLibrary();
void XftFontLoadGlyphs (Display *dpy,
XftFont *pub,
FcBool need_bitmaps,
const uint *glyphs,
int nglyph);
void XftFontUnloadGlyphs (Display *dpy,
XftFont *pub,
const uint *glyphs,
int nglyph);
FcBool XftFontCheckGlyph (Display *dpy,
XftFont *pub,
FcBool need_bitmaps,
uint glyph,
uint *missing,
int *nmissing);
FcBool XftCharExists (Display *dpy,
XftFont *pub,
dchar ucs4);
uint XftCharIndex (Display *dpy,
XftFont *pub,
dchar ucs4);
FcBool XftInit (const char *config);
int XftGetVersion ();
FcFontSet * XftListFonts (Display *dpy,
int screen,
...);
FcPattern *XftNameParse (const char *name);
void XftGlyphRender (Display *dpy,
int op,
Picture src,
XftFont *pub,
Picture dst,
int srcx,
int srcy,
int x,
int y,
const uint *glyphs,
int nglyphs);
void XftGlyphSpecRender (Display *dpy,
int op,
Picture src,
XftFont *pub,
Picture dst,
int srcx,
int srcy,
const XftGlyphSpec *glyphs,
int nglyphs);
void XftCharSpecRender (Display *dpy,
int op,
Picture src,
XftFont *pub,
Picture dst,
int srcx,
int srcy,
const XftCharSpec *chars,
int len);
void XftGlyphFontSpecRender (Display *dpy,
int op,
Picture src,
Picture dst,
int srcx,
int srcy,
const XftGlyphFontSpec *glyphs,
int nglyphs);
void XftCharFontSpecRender (Display *dpy,
int op,
Picture src,
Picture dst,
int srcx,
int srcy,
const XftCharFontSpec *chars,
int len);
void XftTextRender8 (Display *dpy,
int op,
Picture src,
XftFont *pub,
Picture dst,
int srcx,
int srcy,
int x,
int y,
const char *string,
int len);
void XftTextRender16 (Display *dpy,
int op,
Picture src,
XftFont *pub,
Picture dst,
int srcx,
int srcy,
int x,
int y,
const wchar *string,
int len);
void XftTextRender16BE (Display *dpy,
int op,
Picture src,
XftFont *pub,
Picture dst,
int srcx,
int srcy,
int x,
int y,
const char *string,
int len);
void XftTextRender16LE (Display *dpy,
int op,
Picture src,
XftFont *pub,
Picture dst,
int srcx,
int srcy,
int x,
int y,
const char *string,
int len);
void XftTextRender32 (Display *dpy,
int op,
Picture src,
XftFont *pub,
Picture dst,
int srcx,
int srcy,
int x,
int y,
const dchar *string,
int len);
void XftTextRender32BE (Display *dpy,
int op,
Picture src,
XftFont *pub,
Picture dst,
int srcx,
int srcy,
int x,
int y,
const char *string,
int len);
void XftTextRender32LE (Display *dpy,
int op,
Picture src,
XftFont *pub,
Picture dst,
int srcx,
int srcy,
int x,
int y,
const char *string,
int len);
void XftTextRenderUtf8 (Display *dpy,
int op,
Picture src,
XftFont *pub,
Picture dst,
int srcx,
int srcy,
int x,
int y,
const char *string,
int len);
void XftTextRenderUtf16 (Display *dpy,
int op,
Picture src,
XftFont *pub,
Picture dst,
int srcx,
int srcy,
int x,
int y,
const char *string,
FcEndian endian,
int len);
FcPattern * XftXlfdParse (const char *xlfd_orig, Bool ignore_scalable, Bool complete);
}
interface FontConfig {
extern(C) @nogc pure:
int FcPatternGetString(const FcPattern *p, const char *object, int n, char ** s);
void FcFontSetDestroy(FcFontSet*);
char* FcNameUnparse(const FcPattern *);
}
mixin DynamicLoad!(Xft, "Xft", 2, librariesSuccessfullyLoaded) XftLibrary;
mixin DynamicLoad!(FontConfig, "fontconfig", 1, librariesSuccessfullyLoaded) FontConfigLibrary;
/* Xft } */
class XDisconnectException : Exception {
bool userRequested;
this(bool userRequested = true) {
this.userRequested = userRequested;
super("X disconnected");
}
}
/++
Platform-specific for X11. Traps errors for the duration of `dg`. Avoid calling this from inside a call to this.
Please note that it returns
+/
XErrorEvent[] trapXErrors(scope void delegate() dg) {
static XErrorEvent[] errorBuffer;
static extern(C) int handler (Display* dpy, XErrorEvent* evt) nothrow {
errorBuffer ~= *evt;
return 0;
}
auto savedErrorHandler = XSetErrorHandler(&handler);
try {
dg();
} finally {
XSync(XDisplayConnection.get, 0/*False*/);
XSetErrorHandler(savedErrorHandler);
}
auto bfr = errorBuffer;
errorBuffer = null;
return bfr;
}
/// Platform-specific for X11. A singleton class (well, all its methods are actually static... so more like a namespace) wrapping a `Display*`.
class XDisplayConnection {
private __gshared Display* display;
private __gshared XIM xim;
private __gshared char* displayName;
private __gshared int connectionSequence_;
private __gshared bool isLocal_;
/// use this for lazy caching when reconnection
static int connectionSequenceNumber() { return connectionSequence_; }
/++
Guesses if the connection appears to be local.
History:
Added June 3, 2021
+/
static @property bool isLocal() nothrow @trusted @nogc {
return isLocal_;
}
/// Attempts recreation of state, may require application assistance
/// You MUST call this OUTSIDE the event loop. Let the exception kill the loop,
/// then call this, and if successful, reenter the loop.
static void discardAndRecreate(string newDisplayString = null) {
if(insideXEventLoop)
throw new Error("You MUST call discardAndRecreate from OUTSIDE the event loop");
// auto swnm = SimpleWindow.nativeMapping.dup; // this SHOULD be unnecessary because all simple windows are capable of handling native events, so the latter ought to do it all
auto chnenhm = CapableOfHandlingNativeEvent.nativeHandleMapping.dup;
foreach(handle; chnenhm) {
handle.discardConnectionState();
}
discardState();
if(newDisplayString !is null)
setDisplayName(newDisplayString);
auto display = get();
foreach(handle; chnenhm) {
handle.recreateAfterDisconnect();
}
}
private __gshared EventMask rootEventMask;
/++
Requests the specified input from the root window on the connection, in addition to any other request.
Since plain XSelectInput will replace the existing mask, adding input from multiple locations is tricky. This central function will combine all the masks for you.
$(WARNING it calls XSelectInput itself, which will override any other root window input you have!)
+/
static void addRootInput(EventMask mask) {
auto old = rootEventMask;
rootEventMask |= mask;
get(); // to ensure display connected
if(display !is null && rootEventMask != old)
XSelectInput(display, RootWindow(display, DefaultScreen(display)), rootEventMask);
}
static void discardState() {
freeImages();
foreach(atomPtr; interredAtoms)
*atomPtr = 0;
interredAtoms = null;
interredAtoms.assumeSafeAppend();
ScreenPainterImplementation.fontAttempted = false;
ScreenPainterImplementation.defaultfont = null;
ScreenPainterImplementation.defaultfontset = null;
Image.impl.xshmQueryCompleted = false;
Image.impl._xshmAvailable = false;
SimpleWindow.nativeMapping = null;
CapableOfHandlingNativeEvent.nativeHandleMapping = null;
// GlobalHotkeyManager
display = null;
xim = null;
}
// Do you want to know why do we need all this horrible-looking code? See comment at the bottom.
private static void createXIM () {
import core.stdc.locale : setlocale, LC_ALL;
import core.stdc.stdio : stderr, fprintf;
import core.stdc.stdlib : free;
import core.stdc.string : strdup;
static immutable string[3] mtry = [ "", "@im=local", "@im=" ];
auto olocale = strdup(setlocale(LC_ALL, null));
setlocale(LC_ALL, (sdx_isUTF8Locale ? "" : "en_US.UTF-8"));
scope(exit) { setlocale(LC_ALL, olocale); free(olocale); }
//fprintf(stderr, "opening IM...\n");
foreach (string s; mtry) {
XSetLocaleModifiers(s.ptr); // it's safe, as `s` is string literal
if ((xim = XOpenIM(display, null, null, null)) !is null) return;
}
fprintf(stderr, "createXIM: XOpenIM failed!\n");
}
// for X11 we will keep all XShm-allocated images in this list, so we can free 'em on connection closing.
// we'll use glibc malloc()/free(), 'cause `unregisterImage()` can be called from object dtor.
static struct ImgList {
size_t img; // class; hide it from GC
ImgList* next;
}
static __gshared ImgList* imglist = null;
static __gshared bool imglistLocked = false; // true: don't register and unregister images
static void registerImage (Image img) {
if (!imglistLocked && img !is null) {
import core.stdc.stdlib : malloc;
auto it = cast(ImgList*)malloc(ImgList.sizeof);
assert(it !is null); // do proper checks
it.img = cast(size_t)cast(void*)img;
it.next = imglist;
imglist = it;
version(sdpy_debug_xshm) { import core.stdc.stdio : printf; printf("registering image %p\n", cast(void*)img); }
}
}
static void unregisterImage (Image img) {
if (!imglistLocked && img !is null) {
import core.stdc.stdlib : free;
ImgList* prev = null;
ImgList* cur = imglist;
while (cur !is null) {
if (cur.img == cast(size_t)cast(void*)img) break; // i found her!
prev = cur;
cur = cur.next;
}
if (cur !is null) {
if (prev is null) imglist = cur.next; else prev.next = cur.next;
free(cur);
version(sdpy_debug_xshm) { import core.stdc.stdio : printf; printf("unregistering image %p\n", cast(void*)img); }
} else {
version(sdpy_debug_xshm) { import core.stdc.stdio : printf; printf("trying to unregister unknown image %p\n", cast(void*)img); }
}
}
}
static void freeImages () { // needed for discardAndRecreate
imglistLocked = true;
scope(exit) imglistLocked = false;
ImgList* cur = imglist;
ImgList* next = null;
while (cur !is null) {
import core.stdc.stdlib : free;
next = cur.next;
version(sdpy_debug_xshm) { import core.stdc.stdio : printf; printf("disposing image %p\n", cast(void*)cur.img); }
(cast(Image)cast(void*)cur.img).dispose();
free(cur);
cur = next;
}
imglist = null;
}
/// can be used to override normal handling of display name
/// from environment and/or command line
static setDisplayName(string newDisplayName) {
displayName = cast(char*) (newDisplayName ~ '\0');
}
/// resets to the default display string
static resetDisplayName() {
displayName = null;
}
///
static Display* get() {
if(display is null) {
if(!librariesSuccessfullyLoaded)
throw new Exception("Unable to load X11 client libraries");
display = XOpenDisplay(displayName);
isLocal_ = false;
connectionSequence_++;
if(display is null)
throw new Exception("Unable to open X display");
auto str = display.display_name;
// this is a bit of a hack but like if it looks like a unix socket we assume it is local
// and otherwise it probably isn't
if(str is null || (str[0] != ':' && str[0] != '/'))
isLocal_ = false;
else
isLocal_ = true;
debug(sdpy_x_errors) {
XSetErrorHandler(&adrlogger);
XSynchronize(display, true);
extern(C) int wtf() {
if(errorHappened) {
asm { int 3; }
errorHappened = false;
}
return 0;
}
XSetAfterFunction(display, &wtf);
}
XSetIOErrorHandler(&x11ioerrCB);
Bool sup;
XkbSetDetectableAutoRepeat(display, 1, &sup); // so we will not receive KeyRelease until key is really released
createXIM();
version(with_eventloop) {
import arsd.eventloop;
addFileEventListeners(display.fd, &eventListener, null, null);
}
}
return display;
}
extern(C)
static int x11ioerrCB(Display* dpy) {
throw new XDisconnectException(false);
}
version(with_eventloop) {
import arsd.eventloop;
static void eventListener(OsFileHandle fd) {
//this.mtLock();
//scope(exit) this.mtUnlock();
while(XPending(display))
doXNextEvent(display);
}
}
// close connection on program exit -- we need this to properly free all images
static ~this () {
// the gui thread must clean up after itself or else Xlib might deadlock
// using this flag on any thread destruction is the easiest way i know of
// (shared static this is run by the LAST thread to exit, which may not be
// the gui thread, and normal static this run by ALL threads, so we gotta check.)
if(thisIsGuiThread)
close();
}
///
static void close() {
if(display is null)
return;
version(with_eventloop) {
import arsd.eventloop;
removeFileEventListeners(display.fd);
}
// now remove all registered images to prevent shared memory leaks
freeImages();
// tbh I don't know why it is doing this but like if this happens to run
// from the other thread there's frequent hanging inside here.
if(thisIsGuiThread)
XCloseDisplay(display);
display = null;
}
}
mixin template NativeImageImplementation() {
XImage* handle;
ubyte* rawData;
XShmSegmentInfo shminfo;
__gshared bool xshmQueryCompleted;
__gshared bool _xshmAvailable;
public static @property bool xshmAvailable() {
if(!xshmQueryCompleted) {
int i1, i2, i3;
xshmQueryCompleted = true;
if(!XDisplayConnection.isLocal)
_xshmAvailable = false;
else
_xshmAvailable = XQueryExtension(XDisplayConnection.get(), "MIT-SHM", &i1, &i2, &i3) != 0;
}
return _xshmAvailable;
}
bool usingXshm;
final:
private __gshared bool xshmfailed;
void createImage(int width, int height, bool forcexshm=false, bool enableAlpha = false) {
auto display = XDisplayConnection.get();
assert(display !is null);
auto screen = DefaultScreen(display);
// it will only use shared memory for somewhat largish images,
// since otherwise we risk wasting shared memory handles on a lot of little ones
if (xshmAvailable && (forcexshm || (width > 100 && height > 100))) {
// it is possible for the query extension to return true, the DISPLAY check to pass, yet
// the actual use still fails. For example, if the program is in a container and permission denied
// on shared memory, or if it is a local thing forwarded to a remote server, etc.
//
// If it does fail, we need to detect it now, abort the xshm and fall back to core protocol.
// synchronize so preexisting buffers are clear
XSync(display, false);
xshmfailed = false;
auto oldErrorHandler = XSetErrorHandler(&XShmErrorHandler);
usingXshm = true;
handle = XShmCreateImage(
display,
DefaultVisual(display, screen),
enableAlpha ? 32: 24,
ImageFormat.ZPixmap,
null,
&shminfo,
width, height);
if(handle is null)
goto abortXshm1;
if(handle.bytes_per_line != 4 * width)
goto abortXshm2;
shminfo.shmid = shmget(IPC_PRIVATE, handle.bytes_per_line * height, IPC_CREAT | 511 /* 0777 */);
if(shminfo.shmid < 0)
goto abortXshm3;
handle.data = shminfo.shmaddr = rawData = cast(ubyte*) shmat(shminfo.shmid, null, 0);
if(rawData == cast(ubyte*) -1)
goto abortXshm4;
shminfo.readOnly = 0;
XShmAttach(display, &shminfo);
// and now to the final error check to ensure it actually worked.
XSync(display, false);
if(xshmfailed)
goto abortXshm5;
XSetErrorHandler(oldErrorHandler);
XDisplayConnection.registerImage(this);
// if I don't flush here there's a chance the dtor will run before the
// ctor and lead to a bad value X error. While this hurts the efficiency
// it is local anyway so prolly better to keep it simple
XFlush(display);
return;
abortXshm5:
shmdt(shminfo.shmaddr);
rawData = null;
abortXshm4:
shmctl(shminfo.shmid, IPC_RMID, null);
abortXshm3:
// nothing needed, the shmget failed so there's nothing to free
abortXshm2:
XDestroyImage(handle);
handle = null;
abortXshm1:
XSetErrorHandler(oldErrorHandler);
usingXshm = false;
handle = null;
shminfo = typeof(shminfo).init;
_xshmAvailable = false; // don't try again in the future
//import std.stdio; writeln("fallingback");
goto fallback;
} else {
fallback:
if (forcexshm) throw new Exception("can't create XShm Image");
// This actually needs to be malloc to avoid a double free error when XDestroyImage is called
import core.stdc.stdlib : malloc;
rawData = cast(ubyte*) malloc(width * height * 4);
handle = XCreateImage(
display,
DefaultVisual(display, screen),
enableAlpha ? 32 : 24, // bpp
ImageFormat.ZPixmap,
0, // offset
rawData,
width, height,
enableAlpha ? 32 : 8 /* FIXME */, 4 * width); // padding, bytes per line
}
}
void dispose() {
// note: this calls free(rawData) for us
if(handle) {
if (usingXshm) {
XDisplayConnection.unregisterImage(this);
if (XDisplayConnection.get()) XShmDetach(XDisplayConnection.get(), &shminfo);
}
XDestroyImage(handle);
if(usingXshm) {
shmdt(shminfo.shmaddr);
shmctl(shminfo.shmid, IPC_RMID, null);
}
handle = null;
}
}
Color getPixel(int x, int y) {
auto offset = (y * width + x) * 4;
Color c;
c.a = enableAlpha ? rawData[offset + 3] : 255;
c.b = rawData[offset + 0];
c.g = rawData[offset + 1];
c.r = rawData[offset + 2];
if(enableAlpha)
c.unPremultiply;
return c;
}
void setPixel(int x, int y, Color c) {
if(enableAlpha)
c.premultiply();
auto offset = (y * width + x) * 4;
rawData[offset + 0] = c.b;
rawData[offset + 1] = c.g;
rawData[offset + 2] = c.r;
if(enableAlpha)
rawData[offset + 3] = c.a;
}
void convertToRgbaBytes(ubyte[] where) {
assert(where.length == this.width * this.height * 4);
// if rawData had a length....
//assert(rawData.length == where.length);
for(int idx = 0; idx < where.length; idx += 4) {
where[idx + 0] = rawData[idx + 2]; // r
where[idx + 1] = rawData[idx + 1]; // g
where[idx + 2] = rawData[idx + 0]; // b
where[idx + 3] = enableAlpha ? rawData[idx + 3] : 255; // a
if(enableAlpha)
unPremultiplyRgba(where[idx .. idx + 4]);
}
}
void setFromRgbaBytes(in ubyte[] where) {
assert(where.length == this.width * this.height * 4);
// if rawData had a length....
//assert(rawData.length == where.length);
for(int idx = 0; idx < where.length; idx += 4) {
rawData[idx + 2] = where[idx + 0]; // r
rawData[idx + 1] = where[idx + 1]; // g
rawData[idx + 0] = where[idx + 2]; // b
if(enableAlpha) {
rawData[idx + 3] = where[idx + 3]; // a
premultiplyBgra(rawData[idx .. idx + 4]);
}
}
}
}
mixin template NativeSimpleWindowImplementation() {
GC gc;
Window window;
Display* display;
Pixmap buffer;
int bufferw, bufferh; // size of the buffer; can be bigger than window
XIC xic; // input context
int curHidden = 0; // counter
Cursor blankCurPtr = 0;
int cursorSequenceNumber = 0;
int warpEventCount = 0; // number of mouse movement events to eat
__gshared X11SetSelectionHandler[Atom] setSelectionHandlers;
X11GetSelectionHandler[Atom] getSelectionHandlers;
version(without_opengl) {} else
GLXContext glc;
private void fixFixedSize(bool forced=false) (int width, int height) {
if (forced || this.resizability == Resizability.fixedSize) {
//{ import core.stdc.stdio; printf("fixing size to: %dx%d\n", width, height); }
XSizeHints sh;
static if (!forced) {
c_long spr;
XGetWMNormalHints(display, window, &sh, &spr);
sh.flags |= PMaxSize | PMinSize;
} else {
sh.flags = PMaxSize | PMinSize;
}
sh.min_width = width;
sh.min_height = height;
sh.max_width = width;
sh.max_height = height;
XSetWMNormalHints(display, window, &sh);
//XFlush(display);
}
}
ScreenPainter getPainter(bool manualInvalidations) {
return ScreenPainter(this, window, manualInvalidations);
}
void move(int x, int y) {
XMoveWindow(display, window, x, y);
}
void resize(int w, int h) {
if (w < 1) w = 1;
if (h < 1) h = 1;
XResizeWindow(display, window, w, h);
// calling this now to avoid waiting for the server to
// acknowledge the resize; draws without returning to the
// event loop will thus actually work. the server's event
// btw might overrule this and resize it again
recordX11Resize(display, this, w, h);
updateOpenglViewportIfNeeded(w, h);
}
void moveResize (int x, int y, int w, int h) {
if (w < 1) w = 1;
if (h < 1) h = 1;
XMoveResizeWindow(display, window, x, y, w, h);
updateOpenglViewportIfNeeded(w, h);
}
void hideCursor () {
if (curHidden++ == 0) {
if (!blankCurPtr || cursorSequenceNumber != XDisplayConnection.connectionSequenceNumber) {
static const(char)[1] cmbmp = 0;
XColor blackcolor = { 0, 0, 0, 0, 0, 0 };
Pixmap pm = XCreateBitmapFromData(display, window, cmbmp.ptr, 1, 1);
blankCurPtr = XCreatePixmapCursor(display, pm, pm, &blackcolor, &blackcolor, 0, 0);
cursorSequenceNumber = XDisplayConnection.connectionSequenceNumber;
XFreePixmap(display, pm);
}
XDefineCursor(display, window, blankCurPtr);
}
}
void showCursor () {
if (--curHidden == 0) XUndefineCursor(display, window);
}
void warpMouse (int x, int y) {
// here i will send dummy "ignore next mouse motion" event,
// 'cause `XWarpPointer()` sends synthesised mouse motion,
// and we don't need to report it to the user (as warping is
// used when the user needs movement deltas).
//XClientMessageEvent xclient;
XEvent e;
e.xclient.type = EventType.ClientMessage;
e.xclient.window = window;
e.xclient.message_type = GetAtom!("_X11SDPY_INSMME_FLAG_EVENT_", true)(display); // let's hope nobody else will use such stupid name ;-)
e.xclient.format = 32;
e.xclient.data.l[0] = 0;
debug(x11sdpy_warp_debug) { import core.stdc.stdio : printf; printf("X11: sending \"INSMME\"...\n"); }
//{ import core.stdc.stdio : printf; printf("*X11 CLIENT: w=%u; type=%u; [0]=%u\n", cast(uint)e.xclient.window, cast(uint)e.xclient.message_type, cast(uint)e.xclient.data.l[0]); }
XSendEvent(display, window, false, EventMask.NoEventMask, /*cast(XEvent*)&xclient*/&e);
// now warp pointer...
debug(x11sdpy_warp_debug) { import core.stdc.stdio : printf; printf("X11: sending \"warp\"...\n"); }
XWarpPointer(display, None, window, 0, 0, 0, 0, x, y);
// ...and flush
debug(x11sdpy_warp_debug) { import core.stdc.stdio : printf; printf("X11: flushing...\n"); }
XFlush(display);
}
void sendDummyEvent () {
// here i will send dummy event to ping event queue
XEvent e;
e.xclient.type = EventType.ClientMessage;
e.xclient.window = window;
e.xclient.message_type = GetAtom!("_X11SDPY_DUMMY_EVENT_", true)(display); // let's hope nobody else will use such stupid name ;-)
e.xclient.format = 32;
e.xclient.data.l[0] = 0;
XSendEvent(display, window, false, EventMask.NoEventMask, /*cast(XEvent*)&xclient*/&e);
XFlush(display);
}
void setTitle(string title) {
if (title.ptr is null) title = "";
auto XA_UTF8 = XInternAtom(display, "UTF8_STRING".ptr, false);
auto XA_NETWM_NAME = XInternAtom(display, "_NET_WM_NAME".ptr, false);
XTextProperty windowName;
windowName.value = title.ptr;
windowName.encoding = XA_UTF8; //XA_STRING;
windowName.format = 8;
windowName.nitems = cast(uint)title.length;
XSetWMName(display, window, &windowName);
char[1024] namebuf = 0;
auto maxlen = namebuf.length-1;
if (maxlen > title.length) maxlen = title.length;
namebuf[0..maxlen] = title[0..maxlen];
XStoreName(display, window, namebuf.ptr);
XChangeProperty(display, window, XA_NETWM_NAME, XA_UTF8, 8, PropModeReplace, title.ptr, cast(uint)title.length);
flushGui(); // without this OpenGL windows has a LONG delay before changing title
}
string[] getTitles() {
auto XA_UTF8 = XInternAtom(display, "UTF8_STRING".ptr, false);
auto XA_NETWM_NAME = XInternAtom(display, "_NET_WM_NAME".ptr, false);
XTextProperty textProp;
if (XGetTextProperty(display, window, &textProp, XA_NETWM_NAME) != 0 || XGetWMName(display, window, &textProp) != 0) {
if ((textProp.encoding == XA_UTF8 || textProp.encoding == XA_STRING) && textProp.format == 8) {
return textProp.value[0 .. textProp.nitems].idup.split('\0');
} else
return [];
} else
return null;
}
string getTitle() {
auto titles = getTitles();
return titles.length ? titles[0] : null;
}
void setMinSize (int minwidth, int minheight) {
import core.stdc.config : c_long;
if (minwidth < 1) minwidth = 1;
if (minheight < 1) minheight = 1;
XSizeHints sh;
c_long spr;
XGetWMNormalHints(display, window, &sh, &spr);
sh.min_width = minwidth;
sh.min_height = minheight;
sh.flags |= PMinSize;
XSetWMNormalHints(display, window, &sh);
flushGui();
}
void setMaxSize (int maxwidth, int maxheight) {
import core.stdc.config : c_long;
if (maxwidth < 1) maxwidth = 1;
if (maxheight < 1) maxheight = 1;
XSizeHints sh;
c_long spr;
XGetWMNormalHints(display, window, &sh, &spr);
sh.max_width = maxwidth;
sh.max_height = maxheight;
sh.flags |= PMaxSize;
XSetWMNormalHints(display, window, &sh);
flushGui();
}
void setResizeGranularity (int granx, int grany) {
import core.stdc.config : c_long;
if (granx < 1) granx = 1;
if (grany < 1) grany = 1;
XSizeHints sh;
c_long spr;
XGetWMNormalHints(display, window, &sh, &spr);
sh.width_inc = granx;
sh.height_inc = grany;
sh.flags |= PResizeInc;
XSetWMNormalHints(display, window, &sh);
flushGui();
}
void setOpacity (uint opacity) {
arch_ulong o = opacity;
if (opacity == uint.max)
XDeleteProperty(display, window, XInternAtom(display, "_NET_WM_WINDOW_OPACITY".ptr, false));
else
XChangeProperty(display, window, XInternAtom(display, "_NET_WM_WINDOW_OPACITY".ptr, false),
XA_CARDINAL, 32, PropModeReplace, &o, 1);
}
void createWindow(int width, int height, string title, in OpenGlOptions opengl, SimpleWindow parent) {
version(without_opengl) {} else if(opengl == OpenGlOptions.yes && !openGlLibrariesSuccessfullyLoaded) throw new Exception("OpenGL libraries did not load");
display = XDisplayConnection.get();
auto screen = DefaultScreen(display);
bool overrideRedirect = false;
if(windowType == WindowTypes.dropdownMenu || windowType == WindowTypes.popupMenu || windowType == WindowTypes.notification)// || windowType == WindowTypes.nestedChild)
overrideRedirect = true;
version(without_opengl) {}
else {
if(opengl == OpenGlOptions.yes) {
GLXFBConfig fbconf = null;
XVisualInfo* vi = null;
bool useLegacy = false;
static if (SdpyIsUsingIVGLBinds) {if (glbindGetProcAddress("glHint") is null) assert(0, "GL: error loading OpenGL"); } // loads all necessary functions
if (sdpyOpenGLContextVersion != 0 && glXCreateContextAttribsARB_present()) {
int[23] visualAttribs = [
GLX_X_RENDERABLE , 1/*True*/,
GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
GLX_RENDER_TYPE , GLX_RGBA_BIT,
GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR,
GLX_RED_SIZE , 8,
GLX_GREEN_SIZE , 8,
GLX_BLUE_SIZE , 8,
GLX_ALPHA_SIZE , 8,
GLX_DEPTH_SIZE , 24,
GLX_STENCIL_SIZE , 8,
GLX_DOUBLEBUFFER , 1/*True*/,
0/*None*/,
];
int fbcount;
GLXFBConfig* fbc = glXChooseFBConfig(display, screen, visualAttribs.ptr, &fbcount);
if (fbcount == 0) {
useLegacy = true; // try to do at least something
} else {
// pick the FB config/visual with the most samples per pixel
int bestidx = -1, bestns = -1;
foreach (int fbi; 0..fbcount) {
int sb, samples;
glXGetFBConfigAttrib(display, fbc[fbi], GLX_SAMPLE_BUFFERS, &sb);
glXGetFBConfigAttrib(display, fbc[fbi], GLX_SAMPLES, &samples);
if (bestidx < 0 || sb && samples > bestns) { bestidx = fbi; bestns = samples; }
}
//{ import core.stdc.stdio; printf("found gl visual with %d samples\n", bestns); }
fbconf = fbc[bestidx];
// Be sure to free the FBConfig list allocated by glXChooseFBConfig()
XFree(fbc);
vi = cast(XVisualInfo*)glXGetVisualFromFBConfig(display, fbconf);
}
}
if (vi is null || useLegacy) {
static immutable GLint[5] attrs = [ GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None ];
vi = cast(XVisualInfo*)glXChooseVisual(display, 0, attrs.ptr);
useLegacy = true;
}
if (vi is null) throw new Exception("no open gl visual found");
XSetWindowAttributes swa;
auto root = RootWindow(display, screen);
swa.colormap = XCreateColormap(display, root, vi.visual, AllocNone);
swa.override_redirect = overrideRedirect;
window = XCreateWindow(display, (windowType != WindowTypes.nestedChild || parent is null) ? root : parent.impl.window,
0, 0, width, height,
0, vi.depth, 1 /* InputOutput */, vi.visual, CWColormap | CWOverrideRedirect, &swa);
// now try to use `glXCreateContextAttribsARB()` if it's here
if (!useLegacy) {
// request fairly advanced context, even with stencil buffer!
int[9] contextAttribs = [
GLX_CONTEXT_MAJOR_VERSION_ARB, (sdpyOpenGLContextVersion>>8),
GLX_CONTEXT_MINOR_VERSION_ARB, (sdpyOpenGLContextVersion&0xff),
/*GLX_CONTEXT_PROFILE_MASK_ARB*/0x9126, (sdpyOpenGLContextCompatible ? /*GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB*/0x02 : /*GLX_CONTEXT_CORE_PROFILE_BIT_ARB*/ 0x01),
// for modern context, set "forward compatibility" flag too
(sdpyOpenGLContextCompatible ? None : /*GLX_CONTEXT_FLAGS_ARB*/ 0x2094), /*GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB*/ 0x02,
0/*None*/,
];
glc = glXCreateContextAttribsARB(display, fbconf, null, 1/*True*/, contextAttribs.ptr);
if (glc is null && sdpyOpenGLContextAllowFallback) {
sdpyOpenGLContextVersion = 0;
glc = glXCreateContext(display, vi, null, /*GL_TRUE*/1);
}
//{ import core.stdc.stdio; printf("using modern ogl v%d.%d\n", contextAttribs[1], contextAttribs[3]); }
} else {
// fallback to old GLX call
if (sdpyOpenGLContextAllowFallback || sdpyOpenGLContextVersion == 0) {
sdpyOpenGLContextVersion = 0;
glc = glXCreateContext(display, vi, null, /*GL_TRUE*/1);
}
}
// sync to ensure any errors generated are processed
XSync(display, 0/*False*/);
//{ import core.stdc.stdio; printf("ogl is here\n"); }
if(glc is null)
throw new Exception("glc");
}
}
if(opengl == OpenGlOptions.no) {
XSetWindowAttributes swa;
swa.background_pixel = WhitePixel(display, screen);
swa.border_pixel = BlackPixel(display, screen);
swa.override_redirect = overrideRedirect;
auto root = RootWindow(display, screen);
swa.colormap = XCreateColormap(display, root, DefaultVisual(display, screen), AllocNone);
window = XCreateWindow(display, (windowType != WindowTypes.nestedChild || parent is null) ? root : parent.impl.window,
0, 0, width, height,
// I'm commenting that CWBackPixel thing just because it actually causes flicker for no apparent benefit.
0, CopyFromParent, 1 /* InputOutput */, cast(Visual*) CopyFromParent, CWColormap /*| CWBackPixel*/ | CWBorderPixel | CWOverrideRedirect, &swa);
/*
window = XCreateSimpleWindow(
display,
parent is null ? RootWindow(display, screen) : parent.impl.window,
0, 0, // x, y
width, height,
1, // border width
BlackPixel(display, screen), // border
WhitePixel(display, screen)); // background
*/
buffer = XCreatePixmap(display, cast(Drawable) window, width, height, DefaultDepthOfDisplay(display));
bufferw = width;
bufferh = height;
gc = DefaultGC(display, screen);
// clear out the buffer to get us started...
XSetForeground(display, gc, WhitePixel(display, screen));
XFillRectangle(display, cast(Drawable) buffer, gc, 0, 0, width, height);
XSetForeground(display, gc, BlackPixel(display, screen));
}
// input context
//TODO: create this only for top-level windows, and reuse that?
populateXic();
if (sdpyWindowClassStr is null) loadBinNameToWindowClassName();
if (sdpyWindowClassStr is null) sdpyWindowClass = "DSimpleWindow";
// window class
if (sdpyWindowClassStr !is null && sdpyWindowClassStr[0]) {
//{ import core.stdc.stdio; printf("winclass: [%s]\n", sdpyWindowClassStr); }
XClassHint klass;
XWMHints wh;
if(this.customizationFlags & WindowFlags.managesChildWindowFocus) {
wh.input = true;
wh.flags |= InputHint;
}
XSizeHints size;
klass.res_name = sdpyWindowClassStr;
klass.res_class = sdpyWindowClassStr;
XSetWMProperties(display, window, null, null, null, 0, &size, &wh, &klass);
}
setTitle(title);
SimpleWindow.nativeMapping[window] = this;
CapableOfHandlingNativeEvent.nativeHandleMapping[window] = this;
// This gives our window a close button
if (windowType != WindowTypes.eventOnly) {
Atom[2] atoms = [GetAtom!"WM_DELETE_WINDOW"(display), GetAtom!"WM_TAKE_FOCUS"(display)];
int useAtoms;
if(this.customizationFlags & WindowFlags.managesChildWindowFocus) {
useAtoms = 2;
} else {
useAtoms = 1;
}
assert(useAtoms <= atoms.length);
XSetWMProtocols(display, window, atoms.ptr, useAtoms);
}
// FIXME: windowType and customizationFlags
Atom[8] wsatoms; // here, due to goto
int wmsacount = 0; // here, due to goto
try
final switch(windowType) {
case WindowTypes.normal:
setNetWMWindowType(GetAtom!"_NET_WM_WINDOW_TYPE_NORMAL"(display));
break;
case WindowTypes.undecorated:
motifHideDecorations();
setNetWMWindowType(GetAtom!"_NET_WM_WINDOW_TYPE_NORMAL"(display));
break;
case WindowTypes.eventOnly:
_hidden = true;
XSelectInput(display, window, EventMask.StructureNotifyMask); // without this, we won't get destroy notification
goto hiddenWindow;
//break;
case WindowTypes.nestedChild:
// handled in XCreateWindow calls
break;
case WindowTypes.dropdownMenu:
motifHideDecorations();
setNetWMWindowType(GetAtom!"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU"(display));
customizationFlags |= WindowFlags.skipTaskbar | WindowFlags.alwaysOnTop;
break;
case WindowTypes.popupMenu:
motifHideDecorations();
setNetWMWindowType(GetAtom!"_NET_WM_WINDOW_TYPE_POPUP_MENU"(display));
customizationFlags |= WindowFlags.skipTaskbar | WindowFlags.alwaysOnTop;
break;
case WindowTypes.notification:
motifHideDecorations();
setNetWMWindowType(GetAtom!"_NET_WM_WINDOW_TYPE_NOTIFICATION"(display));
customizationFlags |= WindowFlags.skipTaskbar | WindowFlags.alwaysOnTop;
break;
case WindowTypes.minimallyWrapped:
assert(0, "don't create a minimallyWrapped thing explicitly!");
/+
case WindowTypes.menu:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_MENU"(display);
motifHideDecorations();
break;
case WindowTypes.desktop:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_DESKTOP"(display);
break;
case WindowTypes.dock:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_DOCK"(display);
break;
case WindowTypes.toolbar:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_TOOLBAR"(display);
break;
case WindowTypes.menu:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_MENU"(display);
break;
case WindowTypes.utility:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_UTILITY"(display);
break;
case WindowTypes.splash:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_SPLASH"(display);
break;
case WindowTypes.dialog:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_DIALOG"(display);
break;
case WindowTypes.tooltip:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_TOOLTIP"(display);
break;
case WindowTypes.notification:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_NOTIFICATION"(display);
break;
case WindowTypes.combo:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_COMBO"(display);
break;
case WindowTypes.dnd:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_DND"(display);
break;
+/
}
catch(Exception e) {
// XInternAtom failed, prolly a WM
// that doesn't support these things
}
if (customizationFlags&WindowFlags.skipTaskbar) wsatoms[wmsacount++] = GetAtom!("_NET_WM_STATE_SKIP_TASKBAR", true)(display);
// the two following flags may be ignored by WM
if (customizationFlags&WindowFlags.alwaysOnTop) wsatoms[wmsacount++] = GetAtom!("_NET_WM_STATE_ABOVE", true)(display);
if (customizationFlags&WindowFlags.alwaysOnBottom) wsatoms[wmsacount++] = GetAtom!("_NET_WM_STATE_BELOW", true)(display);
if (wmsacount != 0) XChangeProperty(display, window, GetAtom!("_NET_WM_STATE", true)(display), XA_ATOM, 32 /* bits */,0 /*PropModeReplace*/, wsatoms.ptr, wmsacount);
if (this.resizability == Resizability.fixedSize || (opengl == OpenGlOptions.no && this.resizability != Resizability.allowResizing)) fixFixedSize!true(width, height);
// What would be ideal here is if they only were
// selected if there was actually an event handler
// for them...
selectDefaultInput((customizationFlags & WindowFlags.alwaysRequestMouseMotionEvents)?true:false);
hiddenWindow:
// set the pid property for lookup later by window managers
// a standard convenience
import core.sys.posix.unistd;
arch_ulong pid = getpid();
XChangeProperty(
display,
impl.window,
GetAtom!("_NET_WM_PID", true)(display),
XA_CARDINAL,
32 /* bits */,
0 /*PropModeReplace*/,
&pid,
1);
if(isTransient && parent) { // customizationFlags & WindowFlags.transient) {
if(parent is null) assert(0);
XChangeProperty(
display,
impl.window,
GetAtom!("WM_TRANSIENT_FOR", true)(display),
XA_WINDOW,
32 /* bits */,
0 /*PropModeReplace*/,
&parent.impl.window,
1);
}
if(windowType != WindowTypes.eventOnly && (customizationFlags&WindowFlags.dontAutoShow) == 0) {
XMapWindow(display, window);
} else {
_hidden = true;
}
}
void populateXic() {
if (XDisplayConnection.xim !is null) {
xic = XCreateIC(XDisplayConnection.xim,
/*XNInputStyle*/"inputStyle".ptr, XIMPreeditNothing|XIMStatusNothing,
/*XNClientWindow*/"clientWindow".ptr, window,
/*XNFocusWindow*/"focusWindow".ptr, window,
null);
if (xic is null) {
import core.stdc.stdio : stderr, fprintf;
fprintf(stderr, "XCreateIC failed for window %u\n", cast(uint)window);
}
}
}
void selectDefaultInput(bool forceIncludeMouseMotion) {
auto mask = EventMask.ExposureMask |
EventMask.KeyPressMask |
EventMask.KeyReleaseMask |
EventMask.PropertyChangeMask |
EventMask.FocusChangeMask |
EventMask.StructureNotifyMask |
EventMask.SubstructureNotifyMask |
EventMask.VisibilityChangeMask
| EventMask.ButtonPressMask
| EventMask.ButtonReleaseMask
;
// xshm is our shortcut for local connections
if(XDisplayConnection.isLocal || forceIncludeMouseMotion)
mask |= EventMask.PointerMotionMask;
else
mask |= EventMask.ButtonMotionMask;
XSelectInput(display, window, mask);
}
void setNetWMWindowType(Atom type) {
Atom[2] atoms;
atoms[0] = type;
// generic fallback
atoms[1] = GetAtom!"_NET_WM_WINDOW_TYPE_NORMAL"(display);
XChangeProperty(
display,
impl.window,
GetAtom!"_NET_WM_WINDOW_TYPE"(display),
XA_ATOM,
32 /* bits */,
0 /*PropModeReplace*/,
atoms.ptr,
cast(int) atoms.length);
}
void motifHideDecorations(bool hide = true) {
MwmHints hints;
hints.flags = MWM_HINTS_DECORATIONS;
hints.decorations = hide ? 0 : 1;
XChangeProperty(
display,
impl.window,
GetAtom!"_MOTIF_WM_HINTS"(display),
GetAtom!"_MOTIF_WM_HINTS"(display),
32 /* bits */,
0 /*PropModeReplace*/,
&hints,
hints.sizeof / 4);
}
/*k8: unused
void createOpenGlContext() {
}
*/
void closeWindow() {
// I can't close this or a child window closing will
// break events for everyone. So I'm just leaking it right
// now and that is probably perfectly fine...
version(none)
if (customEventFDRead != -1) {
import core.sys.posix.unistd : close;
auto same = customEventFDRead == customEventFDWrite;
close(customEventFDRead);
if(!same)
close(customEventFDWrite);
customEventFDRead = -1;
customEventFDWrite = -1;
}
if(buffer)
XFreePixmap(display, buffer);
bufferw = bufferh = 0;
if (blankCurPtr && cursorSequenceNumber == XDisplayConnection.connectionSequenceNumber) XFreeCursor(display, blankCurPtr);
XDestroyWindow(display, window);
XFlush(display);
}
void dispose() {
}
bool destroyed = false;
}
bool insideXEventLoop;
}
version(X11) {
int mouseDoubleClickTimeout = 350; /// Double click timeout. X only, you probably shouldn't change this.
private class ResizeEvent {
int width, height;
}
void recordX11ResizeAsync(Display* display, SimpleWindow win, int width, int height) {
if(win.windowType == WindowTypes.minimallyWrapped)
return;
if(win.pendingResizeEvent is null) {
win.pendingResizeEvent = new ResizeEvent();
win.addEventListener((ResizeEvent re) {
recordX11Resize(XDisplayConnection.get, win, re.width, re.height);
});
}
win.pendingResizeEvent.width = width;
win.pendingResizeEvent.height = height;
if(!win.eventQueued!ResizeEvent) {
win.postEvent(win.pendingResizeEvent);
}
}
void recordX11Resize(Display* display, SimpleWindow win, int width, int height) {
if(win.windowType == WindowTypes.minimallyWrapped)
return;
if(win.closed)
return;
if(width != win.width || height != win.height) {
// import std.stdio; writeln("RESIZE: ", width, "x", height, " was ", win._width, "x", win._height, " window: ", win.windowType, "-", win.title, " ", win.window);
win._width = width;
win._height = height;
if(win.openglMode == OpenGlOptions.no) {
// FIXME: could this be more efficient?
if (win.bufferw < width || win.bufferh < height) {
//{ import core.stdc.stdio; printf("new buffer; old size: %dx%d; new size: %dx%d\n", win.bufferw, win.bufferh, cast(int)width, cast(int)height); }
// grow the internal buffer to match the window...
auto newPixmap = XCreatePixmap(display, cast(Drawable) win.window, width, height, DefaultDepthOfDisplay(display));
{
GC xgc = XCreateGC(win.display, cast(Drawable)win.window, 0, null);
XCopyGC(win.display, win.gc, 0xffffffff, xgc);
scope(exit) XFreeGC(win.display, xgc);
XSetClipMask(win.display, xgc, None);
XSetForeground(win.display, xgc, 0);
XFillRectangle(display, cast(Drawable)newPixmap, xgc, 0, 0, width, height);
}
XCopyArea(display,
cast(Drawable) win.buffer,
cast(Drawable) newPixmap,
win.gc, 0, 0,
win.bufferw < width ? win.bufferw : win.width,
win.bufferh < height ? win.bufferh : win.height,
0, 0);
XFreePixmap(display, win.buffer);
win.buffer = newPixmap;
win.bufferw = width;
win.bufferh = height;
}
// clear unused parts of the buffer
if (win.bufferw > width || win.bufferh > height) {
GC xgc = XCreateGC(win.display, cast(Drawable)win.window, 0, null);
XCopyGC(win.display, win.gc, 0xffffffff, xgc);
scope(exit) XFreeGC(win.display, xgc);
XSetClipMask(win.display, xgc, None);
XSetForeground(win.display, xgc, 0);
immutable int maxw = (win.bufferw > width ? win.bufferw : width);
immutable int maxh = (win.bufferh > height ? win.bufferh : height);
XFillRectangle(win.display, cast(Drawable)win.buffer, xgc, width, 0, maxw, maxh); // let X11 do clipping
XFillRectangle(win.display, cast(Drawable)win.buffer, xgc, 0, height, maxw, maxh); // let X11 do clipping
}
}
win.updateOpenglViewportIfNeeded(width, height);
win.fixFixedSize(width, height); //k8: this does nothing on my FluxBox; wtf?!
if(win.resizability != Resizability.automaticallyScaleIfPossible)
if(win.windowResized !is null) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
win.windowResized(width, height);
}
}
}
/// Platform-specific, you might use it when doing a custom event loop.
bool doXNextEvent(Display* display) {
bool done;
XEvent e;
XNextEvent(display, &e);
version(sddddd) {
import std.stdio, std.conv : to;
if(auto win = e.xany.window in CapableOfHandlingNativeEvent.nativeHandleMapping) {
if(typeid(cast(Object) *win) == NotificationAreaIcon.classinfo)
writeln("event for: ", e.xany.window, "; type is ", to!string(cast(EventType)e.type));
}
}
// filter out compose events
if (XFilterEvent(&e, None)) {
//{ import core.stdc.stdio : printf; printf("XFilterEvent filtered!\n"); }
//NOTE: we should ungrab keyboard here, but simpledisplay doesn't use keyboard grabbing (yet)
return false;
}
// process keyboard mapping changes
if (e.type == EventType.KeymapNotify) {
//{ import core.stdc.stdio : printf; printf("KeymapNotify processed!\n"); }
XRefreshKeyboardMapping(&e.xmapping);
return false;
}
version(with_eventloop)
import arsd.eventloop;
if(SimpleWindow.handleNativeGlobalEvent !is null) {
// see windows impl's comments
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
auto ret = SimpleWindow.handleNativeGlobalEvent(e);
if(ret == 0)
return done;
}
if(auto win = e.xany.window in CapableOfHandlingNativeEvent.nativeHandleMapping) {
if(win.getNativeEventHandler !is null) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
auto ret = win.getNativeEventHandler()(e);
if(ret == 0)
return done;
}
}
if(xrrEventBase != -1 && e.type == xrrEventBase + RRScreenChangeNotify) {
if(auto win = e.xany.window in SimpleWindow.nativeMapping) {
// we get this because of the RRScreenChangeNotifyMask
// this isn't actually an ideal way to do it since it wastes time
// but meh it is simple and it works.
win.actualDpiLoadAttempted = false;
SimpleWindow.xRandrInfoLoadAttemped = false;
win.updateActualDpi(); // trigger a reload
}
}
switch(e.type) {
case EventType.SelectionClear:
if(auto win = e.xselectionclear.window in SimpleWindow.nativeMapping) {
// FIXME so it is supposed to finish any in progress transfers... but idk...
//import std.stdio; writeln("SelectionClear");
SimpleWindow.impl.setSelectionHandlers.remove(e.xselectionclear.selection);
}
break;
case EventType.SelectionRequest:
if(auto win = e.xselectionrequest.owner in SimpleWindow.nativeMapping)
if(auto ssh = e.xselectionrequest.selection in SimpleWindow.impl.setSelectionHandlers) {
// import std.stdio; printf("SelectionRequest %s\n", XGetAtomName(e.xselectionrequest.display, e.xselectionrequest.target));
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
(*ssh).handleRequest(e);
}
break;
case EventType.PropertyNotify:
// import std.stdio; printf("PropertyNotify %s %d\n", XGetAtomName(e.xproperty.display, e.xproperty.atom), e.xproperty.state);
foreach(ssh; SimpleWindow.impl.setSelectionHandlers) {
if(ssh.matchesIncr(e.xproperty.window, e.xproperty.atom) && e.xproperty.state == PropertyNotification.PropertyDelete)
ssh.sendMoreIncr(&e.xproperty);
}
if(auto win = e.xproperty.window in SimpleWindow.nativeMapping)
if(auto handler = e.xproperty.atom in win.getSelectionHandlers) {
if(handler.matchesIncr(e.xproperty.window, e.xproperty.atom) && e.xproperty.state == PropertyNotification.PropertyNewValue) {
Atom target;
int format;
arch_ulong bytesafter, length;
void* value;
ubyte[] s;
Atom targetToKeep;
XGetWindowProperty(
e.xproperty.display,
e.xproperty.window,
e.xproperty.atom,
0,
100000 /* length */,
true, /* erase it to signal we got it and want more */
0 /*AnyPropertyType*/,
&target, &format, &length, &bytesafter, &value);
if(!targetToKeep)
targetToKeep = target;
auto id = (cast(ubyte*) value)[0 .. length];
handler.handleIncrData(targetToKeep, id);
XFree(value);
}
}
break;
case EventType.SelectionNotify:
if(auto win = e.xselection.requestor in SimpleWindow.nativeMapping)
if(auto handler = e.xproperty.atom in win.getSelectionHandlers) {
if(e.xselection.property == None) { // || e.xselection.property == GetAtom!("NULL", true)(e.xselection.display)) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
handler.handleData(None, null);
} else {
Atom target;
int format;
arch_ulong bytesafter, length;
void* value;
XGetWindowProperty(
e.xselection.display,
e.xselection.requestor,
e.xselection.property,
0,
100000 /* length */,
//false, /* don't erase it */
true, /* do erase it lol */
0 /*AnyPropertyType*/,
&target, &format, &length, &bytesafter, &value);
// FIXME: I don't have to copy it now since it is in char[] instead of string
{
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
if(target == XA_ATOM) {
// initial request, see what they are able to work with and request the best one
// we can handle, if available
Atom[] answer = (cast(Atom*) value)[0 .. length];
Atom best = handler.findBestFormat(answer);
/+
writeln("got ", answer);
foreach(a; answer)
printf("%s\n", XGetAtomName(display, a));
writeln("best ", best);
+/
if(best != None) {
// actually request the best format
XConvertSelection(e.xselection.display, e.xselection.selection, best, GetAtom!("SDD_DATA", true)(display), e.xselection.requestor, 0 /*CurrentTime*/);
}
} else if(target == GetAtom!"INCR"(display)) {
// incremental
handler.prepareIncremental(e.xselection.requestor, e.xselection.property);
// signal the sending program that we see
// the incr and are ready to receive more.
XDeleteProperty(
e.xselection.display,
e.xselection.requestor,
e.xselection.property);
} else {
// unsupported type... maybe, forward
handler.handleData(target, cast(ubyte[]) value[0 .. length]);
}
}
XFree(value);
/*
XDeleteProperty(
e.xselection.display,
e.xselection.requestor,
e.xselection.property);
*/
}
}
break;
case EventType.ConfigureNotify:
auto event = e.xconfigure;
if(auto win = event.window in SimpleWindow.nativeMapping) {
if(win.windowType == WindowTypes.minimallyWrapped)
break;
//version(sdddd) { import std.stdio; writeln(" w=", event.width, "; h=", event.height); }
/+
The ICCCM says window managers must send a synthetic event when the window
is moved but NOT when it is resized. In the resize case, an event is sent
with position (0, 0) which can be wrong and break the dpi calculations.
So we only consider the synthetic events from the WM and otherwise
need to wait for some other event to get the position which... sucks.
I'd rather not have windows changing their layout on mouse motion after
switching monitors... might be forced to but for now just ignoring it.
Easiest way to switch monitors without sending a size position is by
maximize or fullscreen in a setup like mine, but on most setups those
work on the monitor it is already living on, so it should be ok most the
time.
+/
if(event.send_event) {
win.screenPositionKnown = true;
win.screenPositionX = event.x;
win.screenPositionY = event.y;
win.updateActualDpi();
}
win.updateIMEPopupLocation();
recordX11ResizeAsync(display, *win, event.width, event.height);
}
break;
case EventType.Expose:
if(auto win = e.xexpose.window in SimpleWindow.nativeMapping) {
if(win.windowType == WindowTypes.minimallyWrapped)
break;
// if it is closing from a popup menu, it can get
// an Expose event right by the end and trigger a
// BadDrawable error ... we'll just check
// closed to handle that.
if((*win).closed) break;
if((*win).openglMode == OpenGlOptions.no) {
bool doCopy = true;// e.xexpose.count == 0; // the count is better if we copy all area but meh
if (win.handleExpose !is null) doCopy = !win.handleExpose(e.xexpose.x, e.xexpose.y, e.xexpose.width, e.xexpose.height, e.xexpose.count);
if (doCopy) XCopyArea(display, cast(Drawable) (*win).buffer, cast(Drawable) (*win).window, (*win).gc, e.xexpose.x, e.xexpose.y, e.xexpose.width, e.xexpose.height, e.xexpose.x, e.xexpose.y);
} else {
// need to redraw the scene somehow
if(e.xexpose.count == 0) { // only do the last one since redrawOpenGlSceneNow always does it all
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
version(without_opengl) {} else
win.redrawOpenGlSceneSoon();
}
}
}
break;
case EventType.FocusIn:
case EventType.FocusOut:
if(auto win = e.xfocus.window in SimpleWindow.nativeMapping) {
/+
void info(string detail) {
string s;
import std.conv;
import std.datetime;
s ~= to!string(Clock.currTime);
s ~= " ";
s ~= e.type == EventType.FocusIn ? "in " : "out";
s ~= " ";
s ~= win.windowType == WindowTypes.nestedChild ? "child " : "main ";
s ~= e.xfocus.mode == NotifyModes.NotifyNormal ? " normal ": " grabbed ";
s ~= detail;
s ~= " ";
sdpyPrintDebugString(s);
}
switch(e.xfocus.detail) {
case NotifyDetail.NotifyAncestor: info("Ancestor"); break;
case NotifyDetail.NotifyVirtual: info("Virtual"); break;
case NotifyDetail.NotifyInferior: info("Inferior"); break;
case NotifyDetail.NotifyNonlinear: info("Nonlinear"); break;
case NotifyDetail.NotifyNonlinearVirtual: info("nlinearvirtual"); break;
case NotifyDetail.NotifyPointer: info("pointer"); break;
case NotifyDetail.NotifyPointerRoot: info("pointerroot"); break;
case NotifyDetail.NotifyDetailNone: info("none"); break;
default:
}
+/
if(e.xfocus.detail == NotifyDetail.NotifyPointer)
break; // just ignore these they seem irrelevant
auto old = win._focused;
win._focused = e.type == EventType.FocusIn;
// yes, we are losing the focus, but to our own child. that's actually kinda keeping it.
if(e.type == EventType.FocusOut && e.xfocus.detail == NotifyDetail.NotifyInferior)
win._focused = true;
if(win.demandingAttention)
demandAttention(*win, false);
win.updateIMEFocused();
if(old != win._focused && win.onFocusChange) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
win.onFocusChange(win._focused);
}
}
break;
case EventType.VisibilityNotify:
if(auto win = e.xfocus.window in SimpleWindow.nativeMapping) {
if (e.xvisibility.state == VisibilityNotify.VisibilityFullyObscured) {
if (win.visibilityChanged !is null) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
win.visibilityChanged(false);
}
} else {
if (win.visibilityChanged !is null) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
win.visibilityChanged(true);
}
}
}
break;
case EventType.ClientMessage:
if (e.xclient.message_type == GetAtom!("_X11SDPY_INSMME_FLAG_EVENT_", true)(e.xany.display)) {
// "ignore next mouse motion" event, increment ignore counter for teh window
if (auto win = e.xclient.window in SimpleWindow.nativeMapping) {
++(*win).warpEventCount;
debug(x11sdpy_warp_debug) { import core.stdc.stdio : printf; printf("X11: got \"INSMME\" message, new count=%d\n", (*win).warpEventCount); }
} else {
debug(x11sdpy_warp_debug) { import core.stdc.stdio : printf; printf("X11: got \"INSMME\" WTF?!!\n"); }
}
} else if(e.xclient.data.l[0] == GetAtom!"WM_DELETE_WINDOW"(e.xany.display)) {
// user clicked the close button on the window manager
if(auto win = e.xclient.window in SimpleWindow.nativeMapping) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
if ((*win).closeQuery !is null) (*win).closeQuery(); else (*win).close();
}
} else if(e.xclient.data.l[0] == GetAtom!"WM_TAKE_FOCUS"(e.xany.display)) {
//import std.stdio; writeln("HAPPENED");
// user clicked the close button on the window manager
if(auto win = e.xclient.window in SimpleWindow.nativeMapping) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
auto setTo = *win;
if(win.setRequestedInputFocus !is null) {
auto s = win.setRequestedInputFocus();
if(s !is null) {
setTo = s;
}
}
assert(setTo !is null);
// FIXME: so this is actually supposed to focus to a relevant child window if appropriate
XSetInputFocus(display, setTo.impl.window, RevertToParent, e.xclient.data.l[1]);
}
} else if(e.xclient.message_type == GetAtom!"MANAGER"(e.xany.display)) {
foreach(nai; NotificationAreaIcon.activeIcons)
nai.newManager();
} else if(auto win = e.xclient.window in SimpleWindow.nativeMapping) {
bool xDragWindow = true;
if(xDragWindow && e.xclient.message_type == GetAtom!"XdndStatus"(e.xany.display)) {
//XDefineCursor(display, xDragWindow.impl.window,
//import std.stdio; writeln("XdndStatus ", e.xclient.data.l);
}
if(auto dh = win.dropHandler) {
static Atom[3] xFormatsBuffer;
static Atom[] xFormats;
void resetXFormats() {
xFormatsBuffer[] = 0;
xFormats = xFormatsBuffer[];
}
if(e.xclient.message_type == GetAtom!"XdndEnter"(e.xany.display)) {
// on Windows it is supposed to return the effect you actually do FIXME
auto sourceWindow = e.xclient.data.l[0];
xFormatsBuffer[0] = e.xclient.data.l[2];
xFormatsBuffer[1] = e.xclient.data.l[3];
xFormatsBuffer[2] = e.xclient.data.l[4];
if(e.xclient.data.l[1] & 1) {
// can just grab it all but like we don't necessarily need them...
xFormats = cast(Atom[]) getX11PropertyData(sourceWindow, GetAtom!"XdndTypeList"(display), XA_ATOM);
} else {
int len;
foreach(fmt; xFormatsBuffer)
if(fmt) len++;
xFormats = xFormatsBuffer[0 .. len];
}
auto pkg = DropPackage(*win, e.xclient.data.l[0], 0, xFormats);
dh.dragEnter(&pkg);
} else if(e.xclient.message_type == GetAtom!"XdndPosition"(e.xany.display)) {
auto pack = e.xclient.data.l[2];
auto result = dh.dragOver(Point((pack & 0xffff0000) >> 16, pack & 0xffff)); // FIXME: translate screen coordinates back to window coords
XClientMessageEvent xclient;
xclient.type = EventType.ClientMessage;
xclient.window = e.xclient.data.l[0];
xclient.message_type = GetAtom!"XdndStatus"(display);
xclient.format = 32;
xclient.data.l[0] = win.impl.window;
xclient.data.l[1] = (result.action != DragAndDropAction.none) ? 1 : 0; // will accept
auto r = result.consistentWithin;
xclient.data.l[2] = ((cast(short) r.left) << 16) | (cast(short) r.top);
xclient.data.l[3] = ((cast(short) r.width) << 16) | (cast(short) r.height);
xclient.data.l[4] = dndActionAtom(e.xany.display, result.action);
XSendEvent(
display,
e.xclient.data.l[0],
false,
EventMask.NoEventMask,
cast(XEvent*) &xclient
);
} else if(e.xclient.message_type == GetAtom!"XdndLeave"(e.xany.display)) {
//import std.stdio; writeln("XdndLeave");
// drop cancelled.
// data.l[0] is the source window
dh.dragLeave();
resetXFormats();
} else if(e.xclient.message_type == GetAtom!"XdndDrop"(e.xany.display)) {
// drop happening, should fetch data, then send finished
//import std.stdio; writeln("XdndDrop");
auto pkg = DropPackage(*win, e.xclient.data.l[0], e.xclient.data.l[2], xFormats);
dh.drop(&pkg);
resetXFormats();
} else if(e.xclient.message_type == GetAtom!"XdndFinished"(e.xany.display)) {
// import std.stdio; writeln("XdndFinished");
dh.finish();
}
}
}
break;
case EventType.MapNotify:
if(auto win = e.xmap.window in SimpleWindow.nativeMapping) {
(*win)._visible = true;
if (!(*win)._visibleForTheFirstTimeCalled) {
(*win)._visibleForTheFirstTimeCalled = true;
if ((*win).visibleForTheFirstTime !is null) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
(*win).visibleForTheFirstTime();
}
}
if ((*win).visibilityChanged !is null) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
(*win).visibilityChanged(true);
}
}
break;
case EventType.UnmapNotify:
if(auto win = e.xunmap.window in SimpleWindow.nativeMapping) {
win._visible = false;
if (win.visibilityChanged !is null) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
win.visibilityChanged(false);
}
}
break;
case EventType.DestroyNotify:
if(auto win = e.xdestroywindow.window in SimpleWindow.nativeMapping) {
if(win.destroyed)
break; // might get a notification both for itself and from its parent
if (win.onDestroyed !is null) try { win.onDestroyed(); } catch (Exception e) {} // sorry
win._closed = true; // just in case
win.destroyed = true;
if (win.xic !is null) {
XDestroyIC(win.xic);
win.xic = null; // just in case
}
SimpleWindow.nativeMapping.remove(e.xdestroywindow.window);
bool anyImportant = false;
foreach(SimpleWindow w; SimpleWindow.nativeMapping)
if(w.beingOpenKeepsAppOpen) {
anyImportant = true;
break;
}
if(!anyImportant) {
EventLoop.quitApplication();
done = true;
}
}
auto window = e.xdestroywindow.window;
if(window in CapableOfHandlingNativeEvent.nativeHandleMapping)
CapableOfHandlingNativeEvent.nativeHandleMapping.remove(window);
version(with_eventloop) {
if(done) exit();
}
break;
case EventType.MotionNotify:
MouseEvent mouse;
auto event = e.xmotion;
mouse.type = MouseEventType.motion;
mouse.x = event.x;
mouse.y = event.y;
mouse.modifierState = event.state;
mouse.timestamp = event.time;
if(auto win = e.xmotion.window in SimpleWindow.nativeMapping) {
mouse.window = *win;
if (win.warpEventCount > 0) {
debug(x11sdpy_warp_debug) { import core.stdc.stdio : printf; printf("X11: got \"warp motion\" message, current count=%d\n", (*win).warpEventCount); }
--(*win).warpEventCount;
(*win).mdx(mouse); // so deltas will be correctly updated
} else {
win.warpEventCount = 0; // just in case
(*win).mdx(mouse);
if((*win).handleMouseEvent) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
(*win).handleMouseEvent(mouse);
}
}
}
version(with_eventloop)
send(mouse);
break;
case EventType.ButtonPress:
case EventType.ButtonRelease:
MouseEvent mouse;
auto event = e.xbutton;
mouse.timestamp = event.time;
mouse.type = cast(MouseEventType) (e.type == EventType.ButtonPress ? 1 : 2);
mouse.x = event.x;
mouse.y = event.y;
static Time lastMouseDownTime = 0;
static int lastMouseDownButton = -1;
mouse.doubleClick = e.type == EventType.ButtonPress && event.button == lastMouseDownButton && (event.time - lastMouseDownTime) < mouseDoubleClickTimeout;
if(e.type == EventType.ButtonPress) {
lastMouseDownTime = event.time;
lastMouseDownButton = event.button;
}
switch(event.button) {
case 1: mouse.button = MouseButton.left; break; // left
case 2: mouse.button = MouseButton.middle; break; // middle
case 3: mouse.button = MouseButton.right; break; // right
case 4: mouse.button = MouseButton.wheelUp; break; // scroll up
case 5: mouse.button = MouseButton.wheelDown; break; // scroll down
case 6: break; // idk
case 7: break; // idk
case 8: mouse.button = MouseButton.backButton; break;
case 9: mouse.button = MouseButton.forwardButton; break;
default:
}
// FIXME: double check this
mouse.modifierState = event.state;
//mouse.modifierState = event.detail;
if(auto win = e.xbutton.window in SimpleWindow.nativeMapping) {
mouse.window = *win;
(*win).mdx(mouse);
if((*win).handleMouseEvent) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
(*win).handleMouseEvent(mouse);
}
}
version(with_eventloop)
send(mouse);
break;
case EventType.KeyPress:
case EventType.KeyRelease:
//if (e.type == EventType.KeyPress) { import core.stdc.stdio : stderr, fprintf; fprintf(stderr, "X11 keyboard event!\n"); }
KeyEvent ke;
ke.pressed = e.type == EventType.KeyPress;
ke.hardwareCode = cast(ubyte) e.xkey.keycode;
auto sym = XKeycodeToKeysym(
XDisplayConnection.get(),
e.xkey.keycode,
0);
ke.key = cast(Key) sym;//e.xkey.keycode;
ke.modifierState = e.xkey.state;
// import std.stdio; writefln("%x", sym);
wchar_t[128] charbuf = void; // buffer for XwcLookupString; composed value can consist of many chars!
int charbuflen = 0; // return value of XwcLookupString
if (ke.pressed) {
auto win = e.xkey.window in SimpleWindow.nativeMapping;
if (win !is null && win.xic !is null) {
//{ import core.stdc.stdio : printf; printf("using xic!\n"); }
Status status;
charbuflen = XwcLookupString(win.xic, &e.xkey, charbuf.ptr, cast(int)charbuf.length, &sym, &status);
//{ import core.stdc.stdio : printf; printf("charbuflen=%d\n", charbuflen); }
} else {
//{ import core.stdc.stdio : printf; printf("NOT using xic!\n"); }
// If XIM initialization failed, don't process intl chars. Sorry, boys and girls.
char[16] buffer;
auto res = XLookupString(&e.xkey, buffer.ptr, buffer.length, null, null);
if (res && buffer[0] < 128) charbuf[charbuflen++] = cast(wchar_t)buffer[0];
}
}
// if there's no char, subst one
if (charbuflen == 0) {
switch (sym) {
case 0xff09: charbuf[charbuflen++] = '\t'; break;
case 0xff8d: // keypad enter
case 0xff0d: charbuf[charbuflen++] = '\n'; break;
default : // ignore
}
}
if (auto win = e.xkey.window in SimpleWindow.nativeMapping) {
ke.window = *win;
if(win.inputProxy)
win = &win.inputProxy;
// char events are separate since they are on Windows too
// also, xcompose can generate long char sequences
// don't send char events if Meta and/or Hyper is pressed
// TODO: ctrl+char should only send control chars; not yet
if ((e.xkey.state&ModifierState.ctrl) != 0) {
if (charbuflen > 1 || charbuf[0] >= ' ') charbuflen = 0;
}
dchar[32] charsComingBuffer;
int charsComingPosition;
dchar[] charsComing = charsComingBuffer[];
if (ke.pressed && charbuflen > 0) {
// FIXME: I think Windows sends these on releases... we should try to match that, but idk about repeats.
foreach (immutable dchar ch; charbuf[0..charbuflen]) {
if(charsComingPosition >= charsComing.length)
charsComing.length = charsComingPosition + 8;
charsComing[charsComingPosition++] = ch;
}
charsComing = charsComing[0 .. charsComingPosition];
} else {
charsComing = null;
}
ke.charsPossible = charsComing;
if (win.handleKeyEvent) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
win.handleKeyEvent(ke);
}
// Super and alt modifier keys never actually send the chars, they are assumed to be special.
if ((e.xkey.state&(ModifierState.alt|ModifierState.windows)) == 0 && win.handleCharEvent) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
foreach(ch; charsComing)
win.handleCharEvent(ch);
}
}
version(with_eventloop)
send(ke);
break;
default:
}
return done;
}
}
/* *************************************** */
/* Done with simpledisplay stuff */
/* *************************************** */
// Necessary C library bindings follow
version(Windows) {} else
version(X11) {
extern(C) int eventfd (uint initval, int flags) nothrow @trusted @nogc;
// X11 bindings needed here
/*
A little of this is from the bindings project on
D Source and some of it is copy/paste from the C
header.
The DSource listing consistently used D's long
where C used long. That's wrong - C long is 32 bit, so
it should be int in D. I changed that here.
Note:
This isn't complete, just took what I needed for myself.
*/
import core.stdc.stddef : wchar_t;
interface XLib {
extern(C) nothrow @nogc {
char* XResourceManagerString(Display*);
void XrmInitialize();
XrmDatabase XrmGetStringDatabase(char* data);
bool XrmGetResource(XrmDatabase, const char*, const char*, char**, XrmValue*);
Cursor XCreateFontCursor(Display*, uint shape);
int XDefineCursor(Display* display, Window w, Cursor cursor);
int XUndefineCursor(Display* display, Window w);
Pixmap XCreateBitmapFromData(Display* display, Drawable d, const(char)* data, uint width, uint height);
Cursor XCreatePixmapCursor(Display* display, Pixmap source, Pixmap mask, XColor* foreground_color, XColor* background_color, uint x, uint y);
int XFreeCursor(Display* display, Cursor cursor);
int XLookupString(XKeyEvent *event_struct, char *buffer_return, int bytes_buffer, KeySym *keysym_return, void *status_in_out);
int XwcLookupString(XIC ic, XKeyPressedEvent* event, wchar_t* buffer_return, int wchars_buffer, KeySym* keysym_return, Status* status_return);
XVaNestedList XVaCreateNestedList(int unused, ...);
char *XKeysymToString(KeySym keysym);
KeySym XKeycodeToKeysym(
Display* /* display */,
KeyCode /* keycode */,
int /* index */
);
int XConvertSelection(Display *display, Atom selection, Atom target, Atom property, Window requestor, Time time);
int XFree(void*);
int XDeleteProperty(Display *display, Window w, Atom property);
int XChangeProperty(Display *display, Window w, Atom property, Atom type, int format, int mode, in void *data, int nelements);
int XGetWindowProperty(Display *display, Window w, Atom property, arch_long
long_offset, arch_long long_length, Bool del, Atom req_type, Atom
*actual_type_return, int *actual_format_return, arch_ulong
*nitems_return, arch_ulong *bytes_after_return, void** prop_return);
Atom* XListProperties(Display *display, Window w, int *num_prop_return);
Status XGetTextProperty(Display *display, Window w, XTextProperty *text_prop_return, Atom property);
Status XQueryTree(Display *display, Window w, Window *root_return, Window *parent_return, Window **children_return, uint *nchildren_return);
int XSetSelectionOwner(Display *display, Atom selection, Window owner, Time time);
Window XGetSelectionOwner(Display *display, Atom selection);
XVisualInfo* XGetVisualInfo(Display*, c_long, XVisualInfo*, int*);
char** XListFonts(Display*, const char*, int, int*);
void XFreeFontNames(char**);
Display* XOpenDisplay(const char*);
int XCloseDisplay(Display*);
int function() XSynchronize(Display*, bool);
int function() XSetAfterFunction(Display*, int function() proc);
Bool XQueryExtension(Display*, const char*, int*, int*, int*);
Bool XSupportsLocale();
char* XSetLocaleModifiers(const(char)* modifier_list);
XOM XOpenOM(Display* display, _XrmHashBucketRec* rdb, const(char)* res_name, const(char)* res_class);
Status XCloseOM(XOM om);
XIM XOpenIM(Display* dpy, _XrmHashBucketRec* rdb, const(char)* res_name, const(char)* res_class);
Status XCloseIM(XIM im);
char* XGetIMValues(XIM im, ...) /*_X_SENTINEL(0)*/;
char* XSetIMValues(XIM im, ...) /*_X_SENTINEL(0)*/;
Display* XDisplayOfIM(XIM im);
char* XLocaleOfIM(XIM im);
XIC XCreateIC(XIM im, ...) /*_X_SENTINEL(0)*/;
void XDestroyIC(XIC ic);
void XSetICFocus(XIC ic);
void XUnsetICFocus(XIC ic);
//wchar_t* XwcResetIC(XIC ic);
char* XmbResetIC(XIC ic);
char* Xutf8ResetIC(XIC ic);
char* XSetICValues(XIC ic, ...) /*_X_SENTINEL(0)*/;
char* XGetICValues(XIC ic, ...) /*_X_SENTINEL(0)*/;
XIM XIMOfIC(XIC ic);
uint XSendEvent(Display* display, Window w, Bool propagate, arch_long event_mask, XEvent* event_send);
XFontStruct *XLoadQueryFont(Display *display, in char *name);
int XFreeFont(Display *display, XFontStruct *font_struct);
int XSetFont(Display* display, GC gc, Font font);
int XTextWidth(XFontStruct*, in char*, int);
int XSetLineAttributes(Display *display, GC gc, uint line_width, int line_style, int cap_style, int join_style);
int XSetDashes(Display *display, GC gc, int dash_offset, in byte* dash_list, int n);
Window XCreateSimpleWindow(
Display* /* display */,
Window /* parent */,
int /* x */,
int /* y */,
uint /* width */,
uint /* height */,
uint /* border_width */,
uint /* border */,
uint /* background */
);
Window XCreateWindow(Display *display, Window parent, int x, int y, uint width, uint height, uint border_width, int depth, uint class_, Visual *visual, arch_ulong valuemask, XSetWindowAttributes *attributes);
int XReparentWindow(Display*, Window, Window, int, int);
int XClearWindow(Display*, Window);
int XMoveResizeWindow(Display*, Window, int, int, uint, uint);
int XMoveWindow(Display*, Window, int, int);
int XResizeWindow(Display *display, Window w, uint width, uint height);
Colormap XCreateColormap(Display *display, Window w, Visual *visual, int alloc);
Status XGetWindowAttributes(Display*, Window, XWindowAttributes*);
XImage *XCreateImage(
Display* /* display */,
Visual* /* visual */,
uint /* depth */,
int /* format */,
int /* offset */,
ubyte* /* data */,
uint /* width */,
uint /* height */,
int /* bitmap_pad */,
int /* bytes_per_line */
);
Status XInitImage (XImage* image);
Atom XInternAtom(
Display* /* display */,
const char* /* atom_name */,
Bool /* only_if_exists */
);
Status XInternAtoms(Display*, const char**, int, Bool, Atom*);
char* XGetAtomName(Display*, Atom);
Status XGetAtomNames(Display*, Atom*, int count, char**);
int XPutImage(
Display* /* display */,
Drawable /* d */,
GC /* gc */,
XImage* /* image */,
int /* src_x */,
int /* src_y */,
int /* dest_x */,
int /* dest_y */,
uint /* width */,
uint /* height */
);
XImage *XGetImage(Display *display, Drawable d, int x, int y, uint width, uint height, c_ulong plane_mask, int format);
int XDestroyWindow(
Display* /* display */,
Window /* w */
);
int XDestroyImage(XImage*);
int XSelectInput(
Display* /* display */,
Window /* w */,
EventMask /* event_mask */
);
int XMapWindow(
Display* /* display */,
Window /* w */
);
Status XIconifyWindow(Display*, Window, int);
int XMapRaised(Display*, Window);
int XMapSubwindows(Display*, Window);
int XNextEvent(
Display* /* display */,
XEvent* /* event_return */
);
int XMaskEvent(Display*, arch_long, XEvent*);
Bool XFilterEvent(XEvent *event, Window window);
int XRefreshKeyboardMapping(XMappingEvent *event_map);
Status XSetWMProtocols(
Display* /* display */,
Window /* w */,
Atom* /* protocols */,
int /* count */
);
void XSetWMNormalHints(Display *display, Window w, XSizeHints *hints);
Status XGetWMNormalHints(Display *display, Window w, XSizeHints *hints, c_long* supplied_return);
Status XInitThreads();
void XLockDisplay (Display* display);
void XUnlockDisplay (Display* display);
void XSetWMProperties(Display*, Window, XTextProperty*, XTextProperty*, char**, int, XSizeHints*, XWMHints*, XClassHint*);
int XSetWindowBackground (Display* display, Window w, c_ulong background_pixel);
int XSetWindowBackgroundPixmap (Display* display, Window w, Pixmap background_pixmap);
//int XSetWindowBorder (Display* display, Window w, c_ulong border_pixel);
//int XSetWindowBorderPixmap (Display* display, Window w, Pixmap border_pixmap);
//int XSetWindowBorderWidth (Display* display, Window w, uint width);
// check out Xft too: http://www.keithp.com/~keithp/render/Xft.tutorial
int XDrawString(Display*, Drawable, GC, int, int, in char*, int);
int XDrawLine(Display*, Drawable, GC, int, int, int, int);
int XDrawRectangle(Display*, Drawable, GC, int, int, uint, uint);
int XDrawArc(Display*, Drawable, GC, int, int, uint, uint, int, int);
int XFillRectangle(Display*, Drawable, GC, int, int, uint, uint);
int XFillArc(Display*, Drawable, GC, int, int, uint, uint, int, int);
int XDrawPoint(Display*, Drawable, GC, int, int);
int XSetForeground(Display*, GC, uint);
int XSetBackground(Display*, GC, uint);
XFontSet XCreateFontSet(Display*, const char*, char***, int*, char**);
void XFreeFontSet(Display*, XFontSet);
void Xutf8DrawString(Display*, Drawable, XFontSet, GC, int, int, in char*, int);
void Xutf8DrawText(Display*, Drawable, GC, int, int, XmbTextItem*, int);
int Xutf8TextExtents(XFontSet font_set, const char *, int num_bytes, XRectangle *overall_ink_return, XRectangle *overall_logical_return);
//Status Xutf8TextPerCharExtents(XFontSet font_set, char *string, int num_bytes, XRectangle *ink_array_return, XRectangle *logical_array_return, int array_size, int *num_chars_return, XRectangle *overall_ink_return, XRectangle *overall_logical_return);
void XDrawText(Display*, Drawable, GC, int, int, XTextItem*, int);
int XSetFunction(Display*, GC, int);
GC XCreateGC(Display*, Drawable, uint, void*);
int XCopyGC(Display*, GC, uint, GC);
int XFreeGC(Display*, GC);
bool XCheckWindowEvent(Display*, Window, int, XEvent*);
bool XCheckMaskEvent(Display*, int, XEvent*);
int XPending(Display*);
int XEventsQueued(Display* display, int mode);
Pixmap XCreatePixmap(Display*, Drawable, uint, uint, uint);
int XFreePixmap(Display*, Pixmap);
int XCopyArea(Display*, Drawable, Drawable, GC, int, int, uint, uint, int, int);
int XFlush(Display*);
int XBell(Display*, int);
int XSync(Display*, bool);
int XGrabKey (Display* display, int keycode, uint modifiers, Window grab_window, Bool owner_events, int pointer_mode, int keyboard_mode);
int XUngrabKey (Display* display, int keycode, uint modifiers, Window grab_window);
int XGrabKeyboard(Display*, Window, Bool, int, int, Time);
int XUngrabKeyboard(Display*, Time);
KeyCode XKeysymToKeycode (Display* display, KeySym keysym);
KeySym XStringToKeysym(const char *string);
Bool XCheckTypedEvent(Display *display, int event_type, XEvent *event_return);
Window XDefaultRootWindow(Display*);
int XGrabButton(Display *display, uint button, uint modifiers, Window grab_window, Bool owner_events, uint event_mask, int pointer_mode, int keyboard_mode, Window confine_to, Cursor cursor);
int XUngrabButton(Display *display, uint button, uint modifiers, Window grab_window);
int XDrawLines(Display*, Drawable, GC, XPoint*, int, CoordMode);
int XFillPolygon(Display*, Drawable, GC, XPoint*, int, PolygonShape, CoordMode);
Status XAllocColor(Display*, Colormap, XColor*);
int XWithdrawWindow(Display*, Window, int);
int XUnmapWindow(Display*, Window);
int XLowerWindow(Display*, Window);
int XRaiseWindow(Display*, Window);
int XWarpPointer(Display *display, Window src_w, Window dest_w, int src_x, int src_y, uint src_width, uint src_height, int dest_x, int dest_y);
Bool XTranslateCoordinates(Display *display, Window src_w, Window dest_w, int src_x, int src_y, int *dest_x_return, int *dest_y_return, Window *child_return);
int XGetInputFocus(Display*, Window*, int*);
int XSetInputFocus(Display*, Window, int, Time);
XErrorHandler XSetErrorHandler(XErrorHandler);
int XGetErrorText(Display*, int, char*, int);
Bool XkbSetDetectableAutoRepeat(Display* dpy, Bool detectable, Bool* supported);
int XGrabPointer(Display *display, Window grab_window, Bool owner_events, uint event_mask, int pointer_mode, int keyboard_mode, Window confine_to, Cursor cursor, Time time);
int XUngrabPointer(Display *display, Time time);
int XChangeActivePointerGrab(Display *display, uint event_mask, Cursor cursor, Time time);
int XCopyPlane(Display*, Drawable, Drawable, GC, int, int, uint, uint, int, int, arch_ulong);
Status XGetGeometry(Display*, Drawable, Window*, int*, int*, uint*, uint*, uint*, uint*);
int XSetClipMask(Display*, GC, Pixmap);
int XSetClipOrigin(Display*, GC, int, int);
void XSetClipRectangles(Display*, GC, int, int, XRectangle*, int, int);
void XSetWMName(Display*, Window, XTextProperty*);
Status XGetWMName(Display*, Window, XTextProperty*);
int XStoreName(Display* display, Window w, const(char)* window_name);
XIOErrorHandler XSetIOErrorHandler (XIOErrorHandler handler);
}
}
interface Xext {
extern(C) nothrow @nogc {
Status XShmAttach(Display*, XShmSegmentInfo*);
Status XShmDetach(Display*, XShmSegmentInfo*);
Status XShmPutImage(
Display* /* dpy */,
Drawable /* d */,
GC /* gc */,
XImage* /* image */,
int /* src_x */,
int /* src_y */,
int /* dst_x */,
int /* dst_y */,
uint /* src_width */,
uint /* src_height */,
Bool /* send_event */
);
Status XShmQueryExtension(Display*);
XImage *XShmCreateImage(
Display* /* dpy */,
Visual* /* visual */,
uint /* depth */,
int /* format */,
char* /* data */,
XShmSegmentInfo* /* shminfo */,
uint /* width */,
uint /* height */
);
Pixmap XShmCreatePixmap(
Display* /* dpy */,
Drawable /* d */,
char* /* data */,
XShmSegmentInfo* /* shminfo */,
uint /* width */,
uint /* height */,
uint /* depth */
);
}
}
// this requires -lXpm
//int XpmCreatePixmapFromData(Display*, Drawable, in char**, Pixmap*, Pixmap*, void*); // FIXME: void* should be XpmAttributes
mixin DynamicLoad!(XLib, "X11", 6, librariesSuccessfullyLoaded) xlib;
mixin DynamicLoad!(Xext, "Xext", 6, librariesSuccessfullyLoaded) xext;
shared static this() {
xlib.loadDynamicLibrary();
xext.loadDynamicLibrary();
}
extern(C) nothrow @nogc {
alias XrmDatabase = void*;
struct XrmValue {
uint size;
void* addr;
}
struct XVisualInfo {
Visual* visual;
VisualID visualid;
int screen;
uint depth;
int c_class;
c_ulong red_mask;
c_ulong green_mask;
c_ulong blue_mask;
int colormap_size;
int bits_per_rgb;
}
enum VisualNoMask= 0x0;
enum VisualIDMask= 0x1;
enum VisualScreenMask=0x2;
enum VisualDepthMask= 0x4;
enum VisualClassMask= 0x8;
enum VisualRedMaskMask=0x10;
enum VisualGreenMaskMask=0x20;
enum VisualBlueMaskMask=0x40;
enum VisualColormapSizeMask=0x80;
enum VisualBitsPerRGBMask=0x100;
enum VisualAllMask= 0x1FF;
enum AnyKey = 0;
enum AnyModifier = 1 << 15;
// XIM and other crap
struct _XOM {}
struct _XIM {}
struct _XIC {}
alias XOM = _XOM*;
alias XIM = _XIM*;
alias XIC = _XIC*;
alias XVaNestedList = void*;
alias XIMStyle = arch_ulong;
enum : arch_ulong {
XIMPreeditArea = 0x0001,
XIMPreeditCallbacks = 0x0002,
XIMPreeditPosition = 0x0004,
XIMPreeditNothing = 0x0008,
XIMPreeditNone = 0x0010,
XIMStatusArea = 0x0100,
XIMStatusCallbacks = 0x0200,
XIMStatusNothing = 0x0400,
XIMStatusNone = 0x0800,
}
/* X Shared Memory Extension functions */
//pragma(lib, "Xshm");
alias arch_ulong ShmSeg;
struct XShmSegmentInfo {
ShmSeg shmseg;
int shmid;
ubyte* shmaddr;
Bool readOnly;
}
// and the necessary OS functions
int shmget(int, size_t, int);
void* shmat(int, in void*, int);
int shmdt(in void*);
int shmctl (int shmid, int cmd, void* ptr /*struct shmid_ds *buf*/);
enum IPC_PRIVATE = 0;
enum IPC_CREAT = 512;
enum IPC_RMID = 0;
/* MIT-SHM end */
enum MappingType:int {
MappingModifier =0,
MappingKeyboard =1,
MappingPointer =2
}
/* ImageFormat -- PutImage, GetImage */
enum ImageFormat:int {
XYBitmap =0, /* depth 1, XYFormat */
XYPixmap =1, /* depth == drawable depth */
ZPixmap =2 /* depth == drawable depth */
}
enum ModifierName:int {
ShiftMapIndex =0,
LockMapIndex =1,
ControlMapIndex =2,
Mod1MapIndex =3,
Mod2MapIndex =4,
Mod3MapIndex =5,
Mod4MapIndex =6,
Mod5MapIndex =7
}
enum ButtonMask:int {
Button1Mask =1<<8,
Button2Mask =1<<9,
Button3Mask =1<<10,
Button4Mask =1<<11,
Button5Mask =1<<12,
AnyModifier =1<<15/* used in GrabButton, GrabKey */
}
enum KeyOrButtonMask:uint {
ShiftMask =1<<0,
LockMask =1<<1,
ControlMask =1<<2,
Mod1Mask =1<<3,
Mod2Mask =1<<4,
Mod3Mask =1<<5,
Mod4Mask =1<<6,
Mod5Mask =1<<7,
Button1Mask =1<<8,
Button2Mask =1<<9,
Button3Mask =1<<10,
Button4Mask =1<<11,
Button5Mask =1<<12,
AnyModifier =1<<15/* used in GrabButton, GrabKey */
}
enum ButtonName:int {
Button1 =1,
Button2 =2,
Button3 =3,
Button4 =4,
Button5 =5
}
/* Notify modes */
enum NotifyModes:int
{
NotifyNormal =0,
NotifyGrab =1,
NotifyUngrab =2,
NotifyWhileGrabbed =3
}
enum NotifyHint = 1; /* for MotionNotify events */
/* Notify detail */
enum NotifyDetail:int
{
NotifyAncestor =0,
NotifyVirtual =1,
NotifyInferior =2,
NotifyNonlinear =3,
NotifyNonlinearVirtual =4,
NotifyPointer =5,
NotifyPointerRoot =6,
NotifyDetailNone =7
}
/* Visibility notify */
enum VisibilityNotify:int
{
VisibilityUnobscured =0,
VisibilityPartiallyObscured =1,
VisibilityFullyObscured =2
}
enum WindowStackingMethod:int
{
Above =0,
Below =1,
TopIf =2,
BottomIf =3,
Opposite =4
}
/* Circulation request */
enum CirculationRequest:int
{
PlaceOnTop =0,
PlaceOnBottom =1
}
enum PropertyNotification:int
{
PropertyNewValue =0,
PropertyDelete =1
}
enum ColorMapNotification:int
{
ColormapUninstalled =0,
ColormapInstalled =1
}
struct _XPrivate {}
struct _XrmHashBucketRec {}
alias void* XPointer;
alias void* XExtData;
version( X86_64 ) {
alias ulong XID;
alias ulong arch_ulong;
alias long arch_long;
} else version (AArch64) {
alias ulong XID;
alias ulong arch_ulong;
alias long arch_long;
} else {
alias uint XID;
alias uint arch_ulong;
alias int arch_long;
}
alias XID Window;
alias XID Drawable;
alias XID Pixmap;
alias arch_ulong Atom;
alias int Bool;
alias Display XDisplay;
alias int ByteOrder;
alias arch_ulong Time;
alias void ScreenFormat;
struct XImage {
int width, height; /* size of image */
int xoffset; /* number of pixels offset in X direction */
ImageFormat format; /* XYBitmap, XYPixmap, ZPixmap */
void *data; /* pointer to image data */
ByteOrder byte_order; /* data byte order, LSBFirst, MSBFirst */
int bitmap_unit; /* quant. of scanline 8, 16, 32 */
int bitmap_bit_order; /* LSBFirst, MSBFirst */
int bitmap_pad; /* 8, 16, 32 either XY or ZPixmap */
int depth; /* depth of image */
int bytes_per_line; /* accelarator to next line */
int bits_per_pixel; /* bits per pixel (ZPixmap) */
arch_ulong red_mask; /* bits in z arrangment */
arch_ulong green_mask;
arch_ulong blue_mask;
XPointer obdata; /* hook for the object routines to hang on */
static struct F { /* image manipulation routines */
XImage* function(
XDisplay* /* display */,
Visual* /* visual */,
uint /* depth */,
int /* format */,
int /* offset */,
ubyte* /* data */,
uint /* width */,
uint /* height */,
int /* bitmap_pad */,
int /* bytes_per_line */) create_image;
int function(XImage *) destroy_image;
arch_ulong function(XImage *, int, int) get_pixel;
int function(XImage *, int, int, arch_ulong) put_pixel;
XImage* function(XImage *, int, int, uint, uint) sub_image;
int function(XImage *, arch_long) add_pixel;
}
F f;
}
version(X86_64) static assert(XImage.sizeof == 136);
else version(X86) static assert(XImage.sizeof == 88);
struct XCharStruct {
short lbearing; /* origin to left edge of raster */
short rbearing; /* origin to right edge of raster */
short width; /* advance to next char's origin */
short ascent; /* baseline to top edge of raster */
short descent; /* baseline to bottom edge of raster */
ushort attributes; /* per char flags (not predefined) */
}
/*
* To allow arbitrary information with fonts, there are additional properties
* returned.
*/
struct XFontProp {
Atom name;
arch_ulong card32;
}
alias Atom Font;
struct XFontStruct {
XExtData *ext_data; /* Hook for extension to hang data */
Font fid; /* Font ID for this font */
uint direction; /* Direction the font is painted */
uint min_char_or_byte2; /* First character */
uint max_char_or_byte2; /* Last character */
uint min_byte1; /* First row that exists (for two-byte fonts) */
uint max_byte1; /* Last row that exists (for two-byte fonts) */
Bool all_chars_exist; /* Flag if all characters have nonzero size */
uint default_char; /* Char to print for undefined character */
int n_properties; /* How many properties there are */
XFontProp *properties; /* Pointer to array of additional properties*/
XCharStruct min_bounds; /* Minimum bounds over all existing char*/
XCharStruct max_bounds; /* Maximum bounds over all existing char*/
XCharStruct *per_char; /* first_char to last_char information */
int ascent; /* Max extent above baseline for spacing */
int descent; /* Max descent below baseline for spacing */
}
/*
* Definitions of specific events.
*/
struct XKeyEvent
{
int type; /* of event */
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window; /* "event" window it is reported relative to */
Window root; /* root window that the event occurred on */
Window subwindow; /* child window */
Time time; /* milliseconds */
int x, y; /* pointer x, y coordinates in event window */
int x_root, y_root; /* coordinates relative to root */
KeyOrButtonMask state; /* key or button mask */
uint keycode; /* detail */
Bool same_screen; /* same screen flag */
}
version(X86_64) static assert(XKeyEvent.sizeof == 96);
alias XKeyEvent XKeyPressedEvent;
alias XKeyEvent XKeyReleasedEvent;
struct XButtonEvent
{
int type; /* of event */
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window; /* "event" window it is reported relative to */
Window root; /* root window that the event occurred on */
Window subwindow; /* child window */
Time time; /* milliseconds */
int x, y; /* pointer x, y coordinates in event window */
int x_root, y_root; /* coordinates relative to root */
KeyOrButtonMask state; /* key or button mask */
uint button; /* detail */
Bool same_screen; /* same screen flag */
}
alias XButtonEvent XButtonPressedEvent;
alias XButtonEvent XButtonReleasedEvent;
struct XMotionEvent{
int type; /* of event */
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window; /* "event" window reported relative to */
Window root; /* root window that the event occurred on */
Window subwindow; /* child window */
Time time; /* milliseconds */
int x, y; /* pointer x, y coordinates in event window */
int x_root, y_root; /* coordinates relative to root */
KeyOrButtonMask state; /* key or button mask */
byte is_hint; /* detail */
Bool same_screen; /* same screen flag */
}
alias XMotionEvent XPointerMovedEvent;
struct XCrossingEvent{
int type; /* of event */
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window; /* "event" window reported relative to */
Window root; /* root window that the event occurred on */
Window subwindow; /* child window */
Time time; /* milliseconds */
int x, y; /* pointer x, y coordinates in event window */
int x_root, y_root; /* coordinates relative to root */
NotifyModes mode; /* NotifyNormal, NotifyGrab, NotifyUngrab */
NotifyDetail detail;
/*
* NotifyAncestor, NotifyVirtual, NotifyInferior,
* NotifyNonlinear,NotifyNonlinearVirtual
*/
Bool same_screen; /* same screen flag */
Bool focus; /* Boolean focus */
KeyOrButtonMask state; /* key or button mask */
}
alias XCrossingEvent XEnterWindowEvent;
alias XCrossingEvent XLeaveWindowEvent;
struct XFocusChangeEvent{
int type; /* FocusIn or FocusOut */
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window; /* window of event */
NotifyModes mode; /* NotifyNormal, NotifyWhileGrabbed,
NotifyGrab, NotifyUngrab */
NotifyDetail detail;
/*
* NotifyAncestor, NotifyVirtual, NotifyInferior,
* NotifyNonlinear,NotifyNonlinearVirtual, NotifyPointer,
* NotifyPointerRoot, NotifyDetailNone
*/
}
alias XFocusChangeEvent XFocusInEvent;
alias XFocusChangeEvent XFocusOutEvent;
enum CWBackPixmap = (1L<<0);
enum CWBackPixel = (1L<<1);
enum CWBorderPixmap = (1L<<2);
enum CWBorderPixel = (1L<<3);
enum CWBitGravity = (1L<<4);
enum CWWinGravity = (1L<<5);
enum CWBackingStore = (1L<<6);
enum CWBackingPlanes = (1L<<7);
enum CWBackingPixel = (1L<<8);
enum CWOverrideRedirect = (1L<<9);
enum CWSaveUnder = (1L<<10);
enum CWEventMask = (1L<<11);
enum CWDontPropagate = (1L<<12);
enum CWColormap = (1L<<13);
enum CWCursor = (1L<<14);
struct XWindowAttributes {
int x, y; /* location of window */
int width, height; /* width and height of window */
int border_width; /* border width of window */
int depth; /* depth of window */
Visual *visual; /* the associated visual structure */
Window root; /* root of screen containing window */
int class_; /* InputOutput, InputOnly*/
int bit_gravity; /* one of the bit gravity values */
int win_gravity; /* one of the window gravity values */
int backing_store; /* NotUseful, WhenMapped, Always */
arch_ulong backing_planes; /* planes to be preserved if possible */
arch_ulong backing_pixel; /* value to be used when restoring planes */
Bool save_under; /* boolean, should bits under be saved? */
Colormap colormap; /* color map to be associated with window */
Bool map_installed; /* boolean, is color map currently installed*/
int map_state; /* IsUnmapped, IsUnviewable, IsViewable */
arch_long all_event_masks; /* set of events all people have interest in*/
arch_long your_event_mask; /* my event mask */
arch_long do_not_propagate_mask; /* set of events that should not propagate */
Bool override_redirect; /* boolean value for override-redirect */
Screen *screen; /* back pointer to correct screen */
}
enum IsUnmapped = 0;
enum IsUnviewable = 1;
enum IsViewable = 2;
struct XSetWindowAttributes {
Pixmap background_pixmap;/* background, None, or ParentRelative */
arch_ulong background_pixel;/* background pixel */
Pixmap border_pixmap; /* border of the window or CopyFromParent */
arch_ulong border_pixel;/* border pixel value */
int bit_gravity; /* one of bit gravity values */
int win_gravity; /* one of the window gravity values */
int backing_store; /* NotUseful, WhenMapped, Always */
arch_ulong backing_planes;/* planes to be preserved if possible */
arch_ulong backing_pixel;/* value to use in restoring planes */
Bool save_under; /* should bits under be saved? (popups) */
arch_long event_mask; /* set of events that should be saved */
arch_long do_not_propagate_mask;/* set of events that should not propagate */
Bool override_redirect; /* boolean value for override_redirect */
Colormap colormap; /* color map to be associated with window */
Cursor cursor; /* cursor to be displayed (or None) */
}
alias int Status;
enum EventMask:int
{
NoEventMask =0,
KeyPressMask =1<<0,
KeyReleaseMask =1<<1,
ButtonPressMask =1<<2,
ButtonReleaseMask =1<<3,
EnterWindowMask =1<<4,
LeaveWindowMask =1<<5,
PointerMotionMask =1<<6,
PointerMotionHintMask =1<<7,
Button1MotionMask =1<<8,
Button2MotionMask =1<<9,
Button3MotionMask =1<<10,
Button4MotionMask =1<<11,
Button5MotionMask =1<<12,
ButtonMotionMask =1<<13,
KeymapStateMask =1<<14,
ExposureMask =1<<15,
VisibilityChangeMask =1<<16,
StructureNotifyMask =1<<17,
ResizeRedirectMask =1<<18,
SubstructureNotifyMask =1<<19,
SubstructureRedirectMask=1<<20,
FocusChangeMask =1<<21,
PropertyChangeMask =1<<22,
ColormapChangeMask =1<<23,
OwnerGrabButtonMask =1<<24
}
struct MwmHints {
c_ulong flags;
c_ulong functions;
c_ulong decorations;
c_long input_mode;
c_ulong status;
}
enum {
MWM_HINTS_FUNCTIONS = (1L << 0),
MWM_HINTS_DECORATIONS = (1L << 1),
MWM_FUNC_ALL = (1L << 0),
MWM_FUNC_RESIZE = (1L << 1),
MWM_FUNC_MOVE = (1L << 2),
MWM_FUNC_MINIMIZE = (1L << 3),
MWM_FUNC_MAXIMIZE = (1L << 4),
MWM_FUNC_CLOSE = (1L << 5),
MWM_DECOR_ALL = (1L << 0),
MWM_DECOR_BORDER = (1L << 1),
MWM_DECOR_RESIZEH = (1L << 2),
MWM_DECOR_TITLE = (1L << 3),
MWM_DECOR_MENU = (1L << 4),
MWM_DECOR_MINIMIZE = (1L << 5),
MWM_DECOR_MAXIMIZE = (1L << 6),
}
import core.stdc.config : c_long, c_ulong;
/* Size hints mask bits */
enum USPosition = (1L << 0) /* user specified x, y */;
enum USSize = (1L << 1) /* user specified width, height */;
enum PPosition = (1L << 2) /* program specified position */;
enum PSize = (1L << 3) /* program specified size */;
enum PMinSize = (1L << 4) /* program specified minimum size */;
enum PMaxSize = (1L << 5) /* program specified maximum size */;
enum PResizeInc = (1L << 6) /* program specified resize increments */;
enum PAspect = (1L << 7) /* program specified min and max aspect ratios */;
enum PBaseSize = (1L << 8);
enum PWinGravity = (1L << 9);
enum PAllHints = (PPosition|PSize| PMinSize|PMaxSize| PResizeInc|PAspect);
struct XSizeHints {
arch_long flags; /* marks which fields in this structure are defined */
int x, y; /* Obsolete */
int width, height; /* Obsolete */
int min_width, min_height;
int max_width, max_height;
int width_inc, height_inc;
struct Aspect {
int x; /* numerator */
int y; /* denominator */
}
Aspect min_aspect;
Aspect max_aspect;
int base_width, base_height;
int win_gravity;
/* this structure may be extended in the future */
}
enum EventType:int
{
KeyPress =2,
KeyRelease =3,
ButtonPress =4,
ButtonRelease =5,
MotionNotify =6,
EnterNotify =7,
LeaveNotify =8,
FocusIn =9,
FocusOut =10,
KeymapNotify =11,
Expose =12,
GraphicsExpose =13,
NoExpose =14,
VisibilityNotify =15,
CreateNotify =16,
DestroyNotify =17,
UnmapNotify =18,
MapNotify =19,
MapRequest =20,
ReparentNotify =21,
ConfigureNotify =22,
ConfigureRequest =23,
GravityNotify =24,
ResizeRequest =25,
CirculateNotify =26,
CirculateRequest =27,
PropertyNotify =28,
SelectionClear =29,
SelectionRequest =30,
SelectionNotify =31,
ColormapNotify =32,
ClientMessage =33,
MappingNotify =34,
LASTEvent =35 /* must be bigger than any event # */
}
/* generated on EnterWindow and FocusIn when KeyMapState selected */
struct XKeymapEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
byte[32] key_vector;
}
struct XExposeEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
int x, y;
int width, height;
int count; /* if non-zero, at least this many more */
}
struct XGraphicsExposeEvent{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Drawable drawable;
int x, y;
int width, height;
int count; /* if non-zero, at least this many more */
int major_code; /* core is CopyArea or CopyPlane */
int minor_code; /* not defined in the core */
}
struct XNoExposeEvent{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Drawable drawable;
int major_code; /* core is CopyArea or CopyPlane */
int minor_code; /* not defined in the core */
}
struct XVisibilityEvent{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
VisibilityNotify state; /* Visibility state */
}
struct XCreateWindowEvent{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window parent; /* parent of the window */
Window window; /* window id of window created */
int x, y; /* window location */
int width, height; /* size of window */
int border_width; /* border width */
Bool override_redirect; /* creation should be overridden */
}
struct XDestroyWindowEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
}
struct XUnmapEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
Bool from_configure;
}
struct XMapEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
Bool override_redirect; /* Boolean, is override set... */
}
struct XMapRequestEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window parent;
Window window;
}
struct XReparentEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
Window parent;
int x, y;
Bool override_redirect;
}
struct XConfigureEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
int x, y;
int width, height;
int border_width;
Window above;
Bool override_redirect;
}
struct XGravityEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
int x, y;
}
struct XResizeRequestEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
int width, height;
}
struct XConfigureRequestEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window parent;
Window window;
int x, y;
int width, height;
int border_width;
Window above;
WindowStackingMethod detail; /* Above, Below, TopIf, BottomIf, Opposite */
arch_ulong value_mask;
}
struct XCirculateEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
CirculationRequest place; /* PlaceOnTop, PlaceOnBottom */
}
struct XCirculateRequestEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window parent;
Window window;
CirculationRequest place; /* PlaceOnTop, PlaceOnBottom */
}
struct XPropertyEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
Atom atom;
Time time;
PropertyNotification state; /* NewValue, Deleted */
}
struct XSelectionClearEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
Atom selection;
Time time;
}
struct XSelectionRequestEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window owner;
Window requestor;
Atom selection;
Atom target;
Atom property;
Time time;
}
struct XSelectionEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window requestor;
Atom selection;
Atom target;
Atom property; /* ATOM or None */
Time time;
}
version(X86_64) static assert(XSelectionClearEvent.sizeof == 56);
struct XColormapEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
Colormap colormap; /* COLORMAP or None */
Bool new_; /* C++ */
ColorMapNotification state; /* ColormapInstalled, ColormapUninstalled */
}
version(X86_64) static assert(XColormapEvent.sizeof == 56);
struct XClientMessageEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
Atom message_type;
int format;
union Data{
byte[20] b;
short[10] s;
arch_ulong[5] l;
}
Data data;
}
version(X86_64) static assert(XClientMessageEvent.sizeof == 96);
struct XMappingEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window; /* unused */
MappingType request; /* one of MappingModifier, MappingKeyboard,
MappingPointer */
int first_keycode; /* first keycode */
int count; /* defines range of change w. first_keycode*/
}
struct XErrorEvent
{
int type;
Display *display; /* Display the event was read from */
XID resourceid; /* resource id */
arch_ulong serial; /* serial number of failed request */
ubyte error_code; /* error code of failed request */
ubyte request_code; /* Major op-code of failed request */
ubyte minor_code; /* Minor op-code of failed request */
}
struct XAnyEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display;/* Display the event was read from */
Window window; /* window on which event was requested in event mask */
}
union XEvent{
int type; /* must not be changed; first element */
XAnyEvent xany;
XKeyEvent xkey;
XButtonEvent xbutton;
XMotionEvent xmotion;
XCrossingEvent xcrossing;
XFocusChangeEvent xfocus;
XExposeEvent xexpose;
XGraphicsExposeEvent xgraphicsexpose;
XNoExposeEvent xnoexpose;
XVisibilityEvent xvisibility;
XCreateWindowEvent xcreatewindow;
XDestroyWindowEvent xdestroywindow;
XUnmapEvent xunmap;
XMapEvent xmap;
XMapRequestEvent xmaprequest;
XReparentEvent xreparent;
XConfigureEvent xconfigure;
XGravityEvent xgravity;
XResizeRequestEvent xresizerequest;
XConfigureRequestEvent xconfigurerequest;
XCirculateEvent xcirculate;
XCirculateRequestEvent xcirculaterequest;
XPropertyEvent xproperty;
XSelectionClearEvent xselectionclear;
XSelectionRequestEvent xselectionrequest;
XSelectionEvent xselection;
XColormapEvent xcolormap;
XClientMessageEvent xclient;
XMappingEvent xmapping;
XErrorEvent xerror;
XKeymapEvent xkeymap;
arch_ulong[24] pad;
}
struct Display {
XExtData *ext_data; /* hook for extension to hang data */
_XPrivate *private1;
int fd; /* Network socket. */
int private2;
int proto_major_version;/* major version of server's X protocol */
int proto_minor_version;/* minor version of servers X protocol */
char *vendor; /* vendor of the server hardware */
XID private3;
XID private4;
XID private5;
int private6;
XID function(Display*)resource_alloc;/* allocator function */
ByteOrder byte_order; /* screen byte order, LSBFirst, MSBFirst */
int bitmap_unit; /* padding and data requirements */
int bitmap_pad; /* padding requirements on bitmaps */
ByteOrder bitmap_bit_order; /* LeastSignificant or MostSignificant */
int nformats; /* number of pixmap formats in list */
ScreenFormat *pixmap_format; /* pixmap format list */
int private8;
int release; /* release of the server */
_XPrivate *private9;
_XPrivate *private10;
int qlen; /* Length of input event queue */
arch_ulong last_request_read; /* seq number of last event read */
arch_ulong request; /* sequence number of last request. */
XPointer private11;
XPointer private12;
XPointer private13;
XPointer private14;
uint max_request_size; /* maximum number 32 bit words in request*/
_XrmHashBucketRec *db;
int function (Display*)private15;
char *display_name; /* "host:display" string used on this connect*/
int default_screen; /* default screen for operations */
int nscreens; /* number of screens on this server*/
Screen *screens; /* pointer to list of screens */
arch_ulong motion_buffer; /* size of motion buffer */
arch_ulong private16;
int min_keycode; /* minimum defined keycode */
int max_keycode; /* maximum defined keycode */
XPointer private17;
XPointer private18;
int private19;
byte *xdefaults; /* contents of defaults from server */
/* there is more to this structure, but it is private to Xlib */
}
// I got these numbers from a C program as a sanity test
version(X86_64) {
static assert(Display.sizeof == 296);
static assert(XPointer.sizeof == 8);
static assert(XErrorEvent.sizeof == 40);
static assert(XAnyEvent.sizeof == 40);
static assert(XMappingEvent.sizeof == 56);
static assert(XEvent.sizeof == 192);
} else version (AArch64) {
// omit check for aarch64
} else {
static assert(Display.sizeof == 176);
static assert(XPointer.sizeof == 4);
static assert(XEvent.sizeof == 96);
}
struct Depth
{
int depth; /* this depth (Z) of the depth */
int nvisuals; /* number of Visual types at this depth */
Visual *visuals; /* list of visuals possible at this depth */
}
alias void* GC;
alias c_ulong VisualID;
alias XID Colormap;
alias XID Cursor;
alias XID KeySym;
alias uint KeyCode;
enum None = 0;
}
version(without_opengl) {}
else {
extern(C) nothrow @nogc {
static if(!SdpyIsUsingIVGLBinds) {
enum GLX_USE_GL= 1; /* support GLX rendering */
enum GLX_BUFFER_SIZE= 2; /* depth of the color buffer */
enum GLX_LEVEL= 3; /* level in plane stacking */
enum GLX_RGBA= 4; /* true if RGBA mode */
enum GLX_DOUBLEBUFFER= 5; /* double buffering supported */
enum GLX_STEREO= 6; /* stereo buffering supported */
enum GLX_AUX_BUFFERS= 7; /* number of aux buffers */
enum GLX_RED_SIZE= 8; /* number of red component bits */
enum GLX_GREEN_SIZE= 9; /* number of green component bits */
enum GLX_BLUE_SIZE= 10; /* number of blue component bits */
enum GLX_ALPHA_SIZE= 11; /* number of alpha component bits */
enum GLX_DEPTH_SIZE= 12; /* number of depth bits */
enum GLX_STENCIL_SIZE= 13; /* number of stencil bits */
enum GLX_ACCUM_RED_SIZE= 14; /* number of red accum bits */
enum GLX_ACCUM_GREEN_SIZE= 15; /* number of green accum bits */
enum GLX_ACCUM_BLUE_SIZE= 16; /* number of blue accum bits */
enum GLX_ACCUM_ALPHA_SIZE= 17; /* number of alpha accum bits */
//XVisualInfo* glXChooseVisual(Display *dpy, int screen, in int *attrib_list);
enum GL_TRUE = 1;
enum GL_FALSE = 0;
alias int GLint;
}
alias XID GLXContextID;
alias XID GLXPixmap;
alias XID GLXDrawable;
alias XID GLXPbuffer;
alias XID GLXWindow;
alias XID GLXFBConfigID;
alias void* GLXContext;
}
}
enum AllocNone = 0;
extern(C) {
/* WARNING, this type not in Xlib spec */
extern(C) alias XIOErrorHandler = int function (Display* display);
}
extern(C) nothrow
alias XErrorHandler = int function(Display*, XErrorEvent*);
extern(C) nothrow @nogc {
struct Screen{
XExtData *ext_data; /* hook for extension to hang data */
Display *display; /* back pointer to display structure */
Window root; /* Root window id. */
int width, height; /* width and height of screen */
int mwidth, mheight; /* width and height of in millimeters */
int ndepths; /* number of depths possible */
Depth *depths; /* list of allowable depths on the screen */
int root_depth; /* bits per pixel */
Visual *root_visual; /* root visual */
GC default_gc; /* GC for the root root visual */
Colormap cmap; /* default color map */
uint white_pixel;
uint black_pixel; /* White and Black pixel values */
int max_maps, min_maps; /* max and min color maps */
int backing_store; /* Never, WhenMapped, Always */
bool save_unders;
int root_input_mask; /* initial root input mask */
}
struct Visual
{
XExtData *ext_data; /* hook for extension to hang data */
VisualID visualid; /* visual id of this visual */
int class_; /* class of screen (monochrome, etc.) */
c_ulong red_mask, green_mask, blue_mask; /* mask values */
int bits_per_rgb; /* log base 2 of distinct color values */
int map_entries; /* color map entries */
}
alias Display* _XPrivDisplay;
extern(D) Screen* ScreenOfDisplay(Display* dpy, int scr) {
assert(dpy !is null);
return &dpy.screens[scr];
}
extern(D) Window RootWindow(Display *dpy,int scr) {
return ScreenOfDisplay(dpy,scr).root;
}
struct XWMHints {
arch_long flags;
Bool input;
int initial_state;
Pixmap icon_pixmap;
Window icon_window;
int icon_x, icon_y;
Pixmap icon_mask;
XID window_group;
}
struct XClassHint {
char* res_name;
char* res_class;
}
extern(D) int DefaultScreen(Display *dpy) {
return dpy.default_screen;
}
extern(D) int DefaultDepth(Display* dpy, int scr) { return ScreenOfDisplay(dpy, scr).root_depth; }
extern(D) int DisplayWidth(Display* dpy, int scr) { return ScreenOfDisplay(dpy, scr).width; }
extern(D) int DisplayHeight(Display* dpy, int scr) { return ScreenOfDisplay(dpy, scr).height; }
extern(D) int DisplayWidthMM(Display* dpy, int scr) { return ScreenOfDisplay(dpy, scr).mwidth; }
extern(D) int DisplayHeightMM(Display* dpy, int scr) { return ScreenOfDisplay(dpy, scr).mheight; }
extern(D) auto DefaultColormap(Display* dpy, int scr) { return ScreenOfDisplay(dpy, scr).cmap; }
extern(D) int ConnectionNumber(Display* dpy) { return dpy.fd; }
enum int AnyPropertyType = 0;
enum int Success = 0;
enum int RevertToNone = None;
enum int PointerRoot = 1;
enum Time CurrentTime = 0;
enum int RevertToPointerRoot = PointerRoot;
enum int RevertToParent = 2;
extern(D) int DefaultDepthOfDisplay(Display* dpy) {
return ScreenOfDisplay(dpy, DefaultScreen(dpy)).root_depth;
}
extern(D) Visual* DefaultVisual(Display *dpy,int scr) {
return ScreenOfDisplay(dpy,scr).root_visual;
}
extern(D) GC DefaultGC(Display *dpy,int scr) {
return ScreenOfDisplay(dpy,scr).default_gc;
}
extern(D) uint BlackPixel(Display *dpy,int scr) {
return ScreenOfDisplay(dpy,scr).black_pixel;
}
extern(D) uint WhitePixel(Display *dpy,int scr) {
return ScreenOfDisplay(dpy,scr).white_pixel;
}
alias void* XFontSet; // i think
struct XmbTextItem {
char* chars;
int nchars;
int delta;
XFontSet font_set;
}
struct XTextItem {
char* chars;
int nchars;
int delta;
Font font;
}
enum {
GXclear = 0x0, /* 0 */
GXand = 0x1, /* src AND dst */
GXandReverse = 0x2, /* src AND NOT dst */
GXcopy = 0x3, /* src */
GXandInverted = 0x4, /* NOT src AND dst */
GXnoop = 0x5, /* dst */
GXxor = 0x6, /* src XOR dst */
GXor = 0x7, /* src OR dst */
GXnor = 0x8, /* NOT src AND NOT dst */
GXequiv = 0x9, /* NOT src XOR dst */
GXinvert = 0xa, /* NOT dst */
GXorReverse = 0xb, /* src OR NOT dst */
GXcopyInverted = 0xc, /* NOT src */
GXorInverted = 0xd, /* NOT src OR dst */
GXnand = 0xe, /* NOT src OR NOT dst */
GXset = 0xf, /* 1 */
}
enum QueueMode : int {
QueuedAlready,
QueuedAfterReading,
QueuedAfterFlush
}
enum GrabMode { GrabModeSync = 0, GrabModeAsync = 1 }
struct XPoint {
short x;
short y;
}
enum CoordMode:int {
CoordModeOrigin = 0,
CoordModePrevious = 1
}
enum PolygonShape:int {
Complex = 0,
Nonconvex = 1,
Convex = 2
}
struct XTextProperty {
const(char)* value; /* same as Property routines */
Atom encoding; /* prop type */
int format; /* prop data format: 8, 16, or 32 */
arch_ulong nitems; /* number of data items in value */
}
version( X86_64 ) {
static assert(XTextProperty.sizeof == 32);
}
struct XGCValues {
int function_; /* logical operation */
arch_ulong plane_mask;/* plane mask */
arch_ulong foreground;/* foreground pixel */
arch_ulong background;/* background pixel */
int line_width; /* line width */
int line_style; /* LineSolid, LineOnOffDash, LineDoubleDash */
int cap_style; /* CapNotLast, CapButt,
CapRound, CapProjecting */
int join_style; /* JoinMiter, JoinRound, JoinBevel */
int fill_style; /* FillSolid, FillTiled,
FillStippled, FillOpaeueStippled */
int fill_rule; /* EvenOddRule, WindingRule */
int arc_mode; /* ArcChord, ArcPieSlice */
Pixmap tile; /* tile pixmap for tiling operations */
Pixmap stipple; /* stipple 1 plane pixmap for stipping */
int ts_x_origin; /* offset for tile or stipple operations */
int ts_y_origin;
Font font; /* default text font for text operations */
int subwindow_mode; /* ClipByChildren, IncludeInferiors */
Bool graphics_exposures;/* boolean, should exposures be generated */
int clip_x_origin; /* origin for clipping */
int clip_y_origin;
Pixmap clip_mask; /* bitmap clipping; other calls for rects */
int dash_offset; /* patterned/dashed line information */
char dashes;
}
struct XColor {
arch_ulong pixel;
ushort red, green, blue;
byte flags;
byte pad;
}
struct XRectangle {
short x;
short y;
ushort width;
ushort height;
}
enum ClipByChildren = 0;
enum IncludeInferiors = 1;
enum Atom XA_PRIMARY = 1;
enum Atom XA_SECONDARY = 2;
enum Atom XA_STRING = 31;
enum Atom XA_CARDINAL = 6;
enum Atom XA_WM_NAME = 39;
enum Atom XA_ATOM = 4;
enum Atom XA_WINDOW = 33;
enum Atom XA_WM_HINTS = 35;
enum int PropModeAppend = 2;
enum int PropModeReplace = 0;
enum int PropModePrepend = 1;
enum int CopyFromParent = 0;
enum int InputOutput = 1;
// XWMHints
enum InputHint = 1 << 0;
enum StateHint = 1 << 1;
enum IconPixmapHint = (1L << 2);
enum IconWindowHint = (1L << 3);
enum IconPositionHint = (1L << 4);
enum IconMaskHint = (1L << 5);
enum WindowGroupHint = (1L << 6);
enum AllHints = (InputHint|StateHint|IconPixmapHint|IconWindowHint|IconPositionHint|IconMaskHint|WindowGroupHint);
enum XUrgencyHint = (1L << 8);
// GC Components
enum GCFunction = (1L<<0);
enum GCPlaneMask = (1L<<1);
enum GCForeground = (1L<<2);
enum GCBackground = (1L<<3);
enum GCLineWidth = (1L<<4);
enum GCLineStyle = (1L<<5);
enum GCCapStyle = (1L<<6);
enum GCJoinStyle = (1L<<7);
enum GCFillStyle = (1L<<8);
enum GCFillRule = (1L<<9);
enum GCTile = (1L<<10);
enum GCStipple = (1L<<11);
enum GCTileStipXOrigin = (1L<<12);
enum GCTileStipYOrigin = (1L<<13);
enum GCFont = (1L<<14);
enum GCSubwindowMode = (1L<<15);
enum GCGraphicsExposures= (1L<<16);
enum GCClipXOrigin = (1L<<17);
enum GCClipYOrigin = (1L<<18);
enum GCClipMask = (1L<<19);
enum GCDashOffset = (1L<<20);
enum GCDashList = (1L<<21);
enum GCArcMode = (1L<<22);
enum GCLastBit = 22;
enum int WithdrawnState = 0;
enum int NormalState = 1;
enum int IconicState = 3;
}
} else version (OSXCocoa) {
private:
alias void* id;
alias void* Class;
alias void* SEL;
alias void* IMP;
alias void* Ivar;
alias byte BOOL;
alias const(void)* CFStringRef;
alias const(void)* CFAllocatorRef;
alias const(void)* CFTypeRef;
alias const(void)* CGContextRef;
alias const(void)* CGColorSpaceRef;
alias const(void)* CGImageRef;
alias ulong CGBitmapInfo;
struct objc_super {
id self;
Class superclass;
}
struct CFRange {
long location, length;
}
struct NSPoint {
double x, y;
static fromTuple(T)(T tupl) {
return NSPoint(tupl.tupleof);
}
}
struct NSSize {
double width, height;
}
struct NSRect {
NSPoint origin;
NSSize size;
}
alias NSPoint CGPoint;
alias NSSize CGSize;
alias NSRect CGRect;
struct CGAffineTransform {
double a, b, c, d, tx, ty;
}
enum NSApplicationActivationPolicyRegular = 0;
enum NSBackingStoreBuffered = 2;
enum kCFStringEncodingUTF8 = 0x08000100;
enum : size_t {
NSBorderlessWindowMask = 0,
NSTitledWindowMask = 1 << 0,
NSClosableWindowMask = 1 << 1,
NSMiniaturizableWindowMask = 1 << 2,
NSResizableWindowMask = 1 << 3,
NSTexturedBackgroundWindowMask = 1 << 8
}
enum : ulong {
kCGImageAlphaNone,
kCGImageAlphaPremultipliedLast,
kCGImageAlphaPremultipliedFirst,
kCGImageAlphaLast,
kCGImageAlphaFirst,
kCGImageAlphaNoneSkipLast,
kCGImageAlphaNoneSkipFirst
}
enum : ulong {
kCGBitmapAlphaInfoMask = 0x1F,
kCGBitmapFloatComponents = (1 << 8),
kCGBitmapByteOrderMask = 0x7000,
kCGBitmapByteOrderDefault = (0 << 12),
kCGBitmapByteOrder16Little = (1 << 12),
kCGBitmapByteOrder32Little = (2 << 12),
kCGBitmapByteOrder16Big = (3 << 12),
kCGBitmapByteOrder32Big = (4 << 12)
}
enum CGPathDrawingMode {
kCGPathFill,
kCGPathEOFill,
kCGPathStroke,
kCGPathFillStroke,
kCGPathEOFillStroke
}
enum objc_AssociationPolicy : size_t {
OBJC_ASSOCIATION_ASSIGN = 0,
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,
OBJC_ASSOCIATION_COPY_NONATOMIC = 3,
OBJC_ASSOCIATION_RETAIN = 0x301, //01401,
OBJC_ASSOCIATION_COPY = 0x303 //01403
}
extern(C) {
id objc_msgSend(id receiver, SEL selector, ...);
id objc_msgSendSuper(objc_super* superStruct, SEL selector, ...);
id objc_getClass(const(char)* name);
SEL sel_registerName(const(char)* str);
Class objc_allocateClassPair(Class superclass, const(char)* name,
size_t extra_bytes);
void objc_registerClassPair(Class cls);
BOOL class_addMethod(Class cls, SEL name, IMP imp, const(char)* types);
id objc_getAssociatedObject(id object, void* key);
void objc_setAssociatedObject(id object, void* key, id value,
objc_AssociationPolicy policy);
Ivar class_getInstanceVariable(Class cls, const(char)* name);
id object_getIvar(id object, Ivar ivar);
void object_setIvar(id object, Ivar ivar, id value);
BOOL class_addIvar(Class cls, const(char)* name,
size_t size, ubyte alignment, const(char)* types);
extern __gshared id NSApp;
void CFRelease(CFTypeRef obj);
CFStringRef CFStringCreateWithBytes(CFAllocatorRef allocator,
const(char)* bytes, long numBytes,
long encoding,
BOOL isExternalRepresentation);
long CFStringGetBytes(CFStringRef theString, CFRange range, long encoding,
char lossByte, bool isExternalRepresentation,
char* buffer, long maxBufLen, long* usedBufLen);
long CFStringGetLength(CFStringRef theString);
CGContextRef CGBitmapContextCreate(void* data,
size_t width, size_t height,
size_t bitsPerComponent,
size_t bytesPerRow,
CGColorSpaceRef colorspace,
CGBitmapInfo bitmapInfo);
void CGContextRelease(CGContextRef c);
ubyte* CGBitmapContextGetData(CGContextRef c);
CGImageRef CGBitmapContextCreateImage(CGContextRef c);
size_t CGBitmapContextGetWidth(CGContextRef c);
size_t CGBitmapContextGetHeight(CGContextRef c);
CGColorSpaceRef CGColorSpaceCreateDeviceRGB();
void CGColorSpaceRelease(CGColorSpaceRef cs);
void CGContextSetRGBStrokeColor(CGContextRef c,
double red, double green, double blue,
double alpha);
void CGContextSetRGBFillColor(CGContextRef c,
double red, double green, double blue,
double alpha);
void CGContextDrawImage(CGContextRef c, CGRect rect, CGImageRef image);
void CGContextShowTextAtPoint(CGContextRef c, double x, double y,
const(char)* str, size_t length);
void CGContextStrokeLineSegments(CGContextRef c,
const(CGPoint)* points, size_t count);
void CGContextBeginPath(CGContextRef c);
void CGContextDrawPath(CGContextRef c, CGPathDrawingMode mode);
void CGContextAddEllipseInRect(CGContextRef c, CGRect rect);
void CGContextAddArc(CGContextRef c, double x, double y, double radius,
double startAngle, double endAngle, long clockwise);
void CGContextAddRect(CGContextRef c, CGRect rect);
void CGContextAddLines(CGContextRef c,
const(CGPoint)* points, size_t count);
void CGContextSaveGState(CGContextRef c);
void CGContextRestoreGState(CGContextRef c);
void CGContextSelectFont(CGContextRef c, const(char)* name, double size,
ulong textEncoding);
CGAffineTransform CGContextGetTextMatrix(CGContextRef c);
void CGContextSetTextMatrix(CGContextRef c, CGAffineTransform t);
void CGImageRelease(CGImageRef image);
}
private:
// A convenient method to create a CFString (=NSString) from a D string.
CFStringRef createCFString(string str) {
return CFStringCreateWithBytes(null, str.ptr, cast(long) str.length,
kCFStringEncodingUTF8, false);
}
// Objective-C calls.
RetType objc_msgSend_specialized(string selector, RetType, T...)(id self, T args) {
auto _cmd = sel_registerName(selector.ptr);
alias extern(C) RetType function(id, SEL, T) ExpectedType;
return (cast(ExpectedType)&objc_msgSend)(self, _cmd, args);
}
RetType objc_msgSend_classMethod(string selector, RetType, T...)(const(char)* className, T args) {
auto _cmd = sel_registerName(selector.ptr);
auto cls = objc_getClass(className);
alias extern(C) RetType function(id, SEL, T) ExpectedType;
return (cast(ExpectedType)&objc_msgSend)(cls, _cmd, args);
}
RetType objc_msgSend_classMethod(string className, string selector, RetType, T...)(T args) {
return objc_msgSend_classMethod!(selector, RetType, T)(className.ptr, args);
}
alias objc_msgSend_specialized!("setNeedsDisplay:", void, BOOL) setNeedsDisplay;
alias objc_msgSend_classMethod!("alloc", id) alloc;
alias objc_msgSend_specialized!("initWithContentRect:styleMask:backing:defer:",
id, NSRect, size_t, size_t, BOOL) initWithContentRect;
alias objc_msgSend_specialized!("setTitle:", void, CFStringRef) setTitle;
alias objc_msgSend_specialized!("center", void) center;
alias objc_msgSend_specialized!("initWithFrame:", id, NSRect) initWithFrame;
alias objc_msgSend_specialized!("setContentView:", void, id) setContentView;
alias objc_msgSend_specialized!("release", void) release;
alias objc_msgSend_classMethod!("NSColor", "whiteColor", id) whiteNSColor;
alias objc_msgSend_specialized!("setBackgroundColor:", void, id) setBackgroundColor;
alias objc_msgSend_specialized!("makeKeyAndOrderFront:", void, id) makeKeyAndOrderFront;
alias objc_msgSend_specialized!("invalidate", void) invalidate;
alias objc_msgSend_specialized!("close", void) close;
alias objc_msgSend_classMethod!("NSTimer", "scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:",
id, double, id, SEL, id, BOOL) scheduledTimer;
alias objc_msgSend_specialized!("run", void) run;
alias objc_msgSend_classMethod!("NSGraphicsContext", "currentContext",
id) currentNSGraphicsContext;
alias objc_msgSend_specialized!("graphicsPort", CGContextRef) graphicsPort;
alias objc_msgSend_specialized!("characters", CFStringRef) characters;
alias objc_msgSend_specialized!("superclass", Class) superclass;
alias objc_msgSend_specialized!("init", id) init;
alias objc_msgSend_specialized!("addItem:", void, id) addItem;
alias objc_msgSend_specialized!("setMainMenu:", void, id) setMainMenu;
alias objc_msgSend_specialized!("initWithTitle:action:keyEquivalent:",
id, CFStringRef, SEL, CFStringRef) initWithTitle;
alias objc_msgSend_specialized!("setSubmenu:", void, id) setSubmenu;
alias objc_msgSend_specialized!("setDelegate:", void, id) setDelegate;
alias objc_msgSend_specialized!("activateIgnoringOtherApps:",
void, BOOL) activateIgnoringOtherApps;
alias objc_msgSend_classMethod!("NSApplication", "sharedApplication",
id) sharedNSApplication;
alias objc_msgSend_specialized!("setActivationPolicy:", void, ptrdiff_t) setActivationPolicy;
} else static assert(0, "Unsupported operating system");
version(OSXCocoa) {
// I don't know anything about the Mac, but a couple years ago, KennyTM on the newsgroup wrote this for me
//
// http://forum.dlang.org/thread/innr0v$1deh$1@digitalmars.com?page=4#post-int88l:24uaf:241:40digitalmars.com
// https://github.com/kennytm/simpledisplay.d/blob/osx/simpledisplay.d
//
// and it is about time I merged it in here. It is available with -version=OSXCocoa until someone tests it for me!
// Probably won't even fully compile right now
import std.math : PI;
import std.algorithm : map;
import std.array : array;
alias SimpleWindow NativeWindowHandle;
alias void delegate(id) NativeEventHandler;
__gshared Ivar simpleWindowIvar;
enum KEY_ESCAPE = 27;
mixin template NativeImageImplementation() {
CGContextRef context;
ubyte* rawData;
final:
void convertToRgbaBytes(ubyte[] where) {
assert(where.length == this.width * this.height * 4);
// if rawData had a length....
//assert(rawData.length == where.length);
for(long idx = 0; idx < where.length; idx += 4) {
auto alpha = rawData[idx + 3];
if(alpha == 255) {
where[idx + 0] = rawData[idx + 0]; // r
where[idx + 1] = rawData[idx + 1]; // g
where[idx + 2] = rawData[idx + 2]; // b
where[idx + 3] = rawData[idx + 3]; // a
} else {
where[idx + 0] = cast(ubyte)(rawData[idx + 0] * 255 / alpha); // r
where[idx + 1] = cast(ubyte)(rawData[idx + 1] * 255 / alpha); // g
where[idx + 2] = cast(ubyte)(rawData[idx + 2] * 255 / alpha); // b
where[idx + 3] = rawData[idx + 3]; // a
}
}
}
void setFromRgbaBytes(in ubyte[] where) {
// FIXME: this is probably wrong
assert(where.length == this.width * this.height * 4);
// if rawData had a length....
//assert(rawData.length == where.length);
for(long idx = 0; idx < where.length; idx += 4) {
auto alpha = rawData[idx + 3];
if(alpha == 255) {
rawData[idx + 0] = where[idx + 0]; // r
rawData[idx + 1] = where[idx + 1]; // g
rawData[idx + 2] = where[idx + 2]; // b
rawData[idx + 3] = where[idx + 3]; // a
} else {
rawData[idx + 0] = cast(ubyte)(where[idx + 0] * 255 / alpha); // r
rawData[idx + 1] = cast(ubyte)(where[idx + 1] * 255 / alpha); // g
rawData[idx + 2] = cast(ubyte)(where[idx + 2] * 255 / alpha); // b
rawData[idx + 3] = where[idx + 3]; // a
}
}
}
void createImage(int width, int height, bool forcexshm=false) {
auto colorSpace = CGColorSpaceCreateDeviceRGB();
context = CGBitmapContextCreate(null, width, height, 8, 4*width,
colorSpace,
kCGImageAlphaPremultipliedLast
|kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
rawData = CGBitmapContextGetData(context);
}
void dispose() {
CGContextRelease(context);
}
void setPixel(int x, int y, Color c) {
auto offset = (y * width + x) * 4;
if (c.a == 255) {
rawData[offset + 0] = c.r;
rawData[offset + 1] = c.g;
rawData[offset + 2] = c.b;
rawData[offset + 3] = c.a;
} else {
rawData[offset + 0] = cast(ubyte)(c.r*c.a/255);
rawData[offset + 1] = cast(ubyte)(c.g*c.a/255);
rawData[offset + 2] = cast(ubyte)(c.b*c.a/255);
rawData[offset + 3] = c.a;
}
}
}
mixin template NativeScreenPainterImplementation() {
CGContextRef context;
ubyte[4] _outlineComponents;
id view;
void create(NativeWindowHandle window) {
context = window.drawingContext;
view = window.view;
}
void dispose() {
setNeedsDisplay(view, true);
}
bool manualInvalidations;
void invalidateRect(Rectangle invalidRect) { }
// NotYetImplementedException
Size textSize(in char[] txt) { return Size(32, 16); throw new NotYetImplementedException(); }
void rasterOp(RasterOp op) {}
Pen _activePen;
Color _fillColor;
Rectangle _clipRectangle;
void setClipRectangle(int, int, int, int) {}
void setFont(OperatingSystemFont) {}
int fontHeight() { return 14; }
// end
void pen(Pen pen) {
_activePen = pen;
auto color = pen.color; // FIXME
double alphaComponent = color.a/255.0f;
CGContextSetRGBStrokeColor(context,
color.r/255.0f, color.g/255.0f, color.b/255.0f, alphaComponent);
if (color.a != 255) {
_outlineComponents[0] = cast(ubyte)(color.r*color.a/255);
_outlineComponents[1] = cast(ubyte)(color.g*color.a/255);
_outlineComponents[2] = cast(ubyte)(color.b*color.a/255);
_outlineComponents[3] = color.a;
} else {
_outlineComponents[0] = color.r;
_outlineComponents[1] = color.g;
_outlineComponents[2] = color.b;
_outlineComponents[3] = color.a;
}
}
@property void fillColor(Color color) {
CGContextSetRGBFillColor(context,
color.r/255.0f, color.g/255.0f, color.b/255.0f, color.a/255.0f);
}
void drawImage(int x, int y, Image image, int ulx, int upy, int width, int height) {
// NotYetImplementedException for upper left/width/height
auto cgImage = CGBitmapContextCreateImage(image.context);
auto size = CGSize(CGBitmapContextGetWidth(image.context),
CGBitmapContextGetHeight(image.context));
CGContextDrawImage(context, CGRect(CGPoint(x, y), size), cgImage);
CGImageRelease(cgImage);
}
version(OSXCocoa) {} else // NotYetImplementedException
void drawPixmap(Sprite image, int x, int y) {
// FIXME: is this efficient?
auto cgImage = CGBitmapContextCreateImage(image.context);
auto size = CGSize(CGBitmapContextGetWidth(image.context),
CGBitmapContextGetHeight(image.context));
CGContextDrawImage(context, CGRect(CGPoint(x, y), size), cgImage);
CGImageRelease(cgImage);
}
void drawText(int x, int y, int x2, int y2, in char[] text, uint alignment) {
// FIXME: alignment
if (_outlineComponents[3] != 0) {
CGContextSaveGState(context);
auto invAlpha = 1.0f/_outlineComponents[3];
CGContextSetRGBFillColor(context, _outlineComponents[0]*invAlpha,
_outlineComponents[1]*invAlpha,
_outlineComponents[2]*invAlpha,
_outlineComponents[3]/255.0f);
CGContextShowTextAtPoint(context, x, y + 12 /* this is cuz this picks baseline but i want bounding box */, text.ptr, text.length);
// auto cfstr = cast(id)createCFString(text);
// objc_msgSend(cfstr, sel_registerName("drawAtPoint:withAttributes:"),
// NSPoint(x, y), null);
// CFRelease(cfstr);
CGContextRestoreGState(context);
}
}
void drawPixel(int x, int y) {
auto rawData = CGBitmapContextGetData(context);
auto width = CGBitmapContextGetWidth(context);
auto height = CGBitmapContextGetHeight(context);
auto offset = ((height - y - 1) * width + x) * 4;
rawData[offset .. offset+4] = _outlineComponents;
}
void drawLine(int x1, int y1, int x2, int y2) {
CGPoint[2] linePoints;
linePoints[0] = CGPoint(x1, y1);
linePoints[1] = CGPoint(x2, y2);
CGContextStrokeLineSegments(context, linePoints.ptr, linePoints.length);
}
void drawRectangle(int x, int y, int width, int height) {
CGContextBeginPath(context);
auto rect = CGRect(CGPoint(x, y), CGSize(width, height));
CGContextAddRect(context, rect);
CGContextDrawPath(context, CGPathDrawingMode.kCGPathFillStroke);
}
void drawEllipse(int x1, int y1, int x2, int y2) {
CGContextBeginPath(context);
auto rect = CGRect(CGPoint(x1, y1), CGSize(x2-x1, y2-y1));
CGContextAddEllipseInRect(context, rect);
CGContextDrawPath(context, CGPathDrawingMode.kCGPathFillStroke);
}
void drawArc(int x1, int y1, int width, int height, int start, int finish) {
// @@@BUG@@@ Does not support elliptic arc (width != height).
CGContextBeginPath(context);
CGContextAddArc(context, x1+width*0.5f, y1+height*0.5f, width,
start*PI/(180*64), finish*PI/(180*64), 0);
CGContextDrawPath(context, CGPathDrawingMode.kCGPathFillStroke);
}
void drawPolygon(Point[] intPoints) {
CGContextBeginPath(context);
auto points = array(map!(CGPoint.fromTuple)(intPoints));
CGContextAddLines(context, points.ptr, points.length);
CGContextDrawPath(context, CGPathDrawingMode.kCGPathFillStroke);
}
}
mixin template NativeSimpleWindowImplementation() {
void createWindow(int width, int height, string title, OpenGlOptions opengl, SimpleWindow parent) {
synchronized {
if (NSApp == null) initializeApp();
}
auto contentRect = NSRect(NSPoint(0, 0), NSSize(width, height));
// create the window.
window = initWithContentRect(alloc("NSWindow"),
contentRect,
NSTitledWindowMask
|NSClosableWindowMask
|NSMiniaturizableWindowMask
|NSResizableWindowMask,
NSBackingStoreBuffered,
true);
// set the title & move the window to center.
auto windowTitle = createCFString(title);
setTitle(window, windowTitle);
CFRelease(windowTitle);
center(window);
// create area to draw on.
auto colorSpace = CGColorSpaceCreateDeviceRGB();
drawingContext = CGBitmapContextCreate(null, width, height,
8, 4*width, colorSpace,
kCGImageAlphaPremultipliedLast
|kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextSelectFont(drawingContext, "Lucida Grande", 12.0f, 1);
auto matrix = CGContextGetTextMatrix(drawingContext);
matrix.c = -matrix.c;
matrix.d = -matrix.d;
CGContextSetTextMatrix(drawingContext, matrix);
// create the subview that things will be drawn on.
view = initWithFrame(alloc("SDGraphicsView"), contentRect);
setContentView(window, view);
object_setIvar(view, simpleWindowIvar, cast(id)this);
release(view);
setBackgroundColor(window, whiteNSColor);
makeKeyAndOrderFront(window, null);
}
void dispose() {
closeWindow();
release(window);
}
void closeWindow() {
invalidate(timer);
.close(window);
}
ScreenPainter getPainter(bool manualInvalidations) {
return ScreenPainter(this, this, manualInvalidations);
}
id window;
id timer;
id view;
CGContextRef drawingContext;
}
extern(C) {
private:
BOOL returnTrue3(id self, SEL _cmd, id app) {
return true;
}
BOOL returnTrue2(id self, SEL _cmd) {
return true;
}
void pulse(id self, SEL _cmd) {
auto simpleWindow = cast(SimpleWindow)object_getIvar(self, simpleWindowIvar);
simpleWindow.handlePulse();
setNeedsDisplay(self, true);
}
void drawRect(id self, SEL _cmd, NSRect rect) {
auto simpleWindow = cast(SimpleWindow)object_getIvar(self, simpleWindowIvar);
auto curCtx = graphicsPort(currentNSGraphicsContext);
auto cgImage = CGBitmapContextCreateImage(simpleWindow.drawingContext);
auto size = CGSize(CGBitmapContextGetWidth(simpleWindow.drawingContext),
CGBitmapContextGetHeight(simpleWindow.drawingContext));
CGContextDrawImage(curCtx, CGRect(CGPoint(0, 0), size), cgImage);
CGImageRelease(cgImage);
}
void keyDown(id self, SEL _cmd, id event) {
auto simpleWindow = cast(SimpleWindow)object_getIvar(self, simpleWindowIvar);
// the event may have multiple characters, and we send them all at
// once.
if (simpleWindow.handleCharEvent || simpleWindow.handleKeyEvent) {
auto chars = characters(event);
auto range = CFRange(0, CFStringGetLength(chars));
auto buffer = new char[range.length*3];
long actualLength;
CFStringGetBytes(chars, range, kCFStringEncodingUTF8, 0, false,
buffer.ptr, cast(int) buffer.length, &actualLength);
foreach (dchar dc; buffer[0..actualLength]) {
if (simpleWindow.handleCharEvent)
simpleWindow.handleCharEvent(dc);
// NotYetImplementedException
//if (simpleWindow.handleKeyEvent)
//simpleWindow.handleKeyEvent(KeyEvent(dc)); // FIXME: what about keyUp?
}
}
// the event's 'keyCode' is hardware-dependent. I don't think people
// will like it. Let's leave it to the native handler.
// perform the default action.
// so the default action is to make a bomp sound and i dont want that
// sooooooooo yeah not gonna do that.
//auto superData = objc_super(self, superclass(self));
//alias extern(C) void function(objc_super*, SEL, id) T;
//(cast(T)&objc_msgSendSuper)(&superData, _cmd, event);
}
}
// initialize the app so that it can be interacted with the user.
// based on http://cocoawithlove.com/2010/09/minimalist-cocoa-programming.html
private void initializeApp() {
// push an autorelease pool to avoid leaking.
init(alloc("NSAutoreleasePool"));
// create a new NSApp instance
sharedNSApplication;
setActivationPolicy(NSApp, NSApplicationActivationPolicyRegular);
// create the "Quit" menu.
auto menuBar = init(alloc("NSMenu"));
auto appMenuItem = init(alloc("NSMenuItem"));
addItem(menuBar, appMenuItem);
setMainMenu(NSApp, menuBar);
release(appMenuItem);
release(menuBar);
auto appMenu = init(alloc("NSMenu"));
auto quitTitle = createCFString("Quit");
auto q = createCFString("q");
auto quitItem = initWithTitle(alloc("NSMenuItem"),
quitTitle, sel_registerName("terminate:"), q);
addItem(appMenu, quitItem);
setSubmenu(appMenuItem, appMenu);
release(quitItem);
release(appMenu);
CFRelease(q);
CFRelease(quitTitle);
// assign a delegate for the application, allow it to quit when the last
// window is closed.
auto delegateClass = objc_allocateClassPair(objc_getClass("NSObject"),
"SDWindowCloseDelegate", 0);
class_addMethod(delegateClass,
sel_registerName("applicationShouldTerminateAfterLastWindowClosed:"),
&returnTrue3, "c@:@");
objc_registerClassPair(delegateClass);
auto appDelegate = init(alloc("SDWindowCloseDelegate"));
setDelegate(NSApp, appDelegate);
activateIgnoringOtherApps(NSApp, true);
// create a new view that draws the graphics and respond to keyDown
// events.
auto viewClass = objc_allocateClassPair(objc_getClass("NSView"),
"SDGraphicsView", (void*).sizeof);
class_addIvar(viewClass, "simpledisplay_simpleWindow",
(void*).sizeof, (void*).alignof, "^v");
class_addMethod(viewClass, sel_registerName("simpledisplay_pulse"),
&pulse, "v@:");
class_addMethod(viewClass, sel_registerName("drawRect:"),
&drawRect, "v@:{NSRect={NSPoint=ff}{NSSize=ff}}");
class_addMethod(viewClass, sel_registerName("isFlipped"),
&returnTrue2, "c@:");
class_addMethod(viewClass, sel_registerName("acceptsFirstResponder"),
&returnTrue2, "c@:");
class_addMethod(viewClass, sel_registerName("keyDown:"),
&keyDown, "v@:@");
objc_registerClassPair(viewClass);
simpleWindowIvar = class_getInstanceVariable(viewClass,
"simpledisplay_simpleWindow");
}
}
version(without_opengl) {} else
extern(System) nothrow @nogc {
//enum uint GL_VERSION = 0x1F02;
//const(char)* glGetString (/*GLenum*/uint);
version(X11) {
static if (!SdpyIsUsingIVGLBinds) {
enum GLX_X_RENDERABLE = 0x8012;
enum GLX_DRAWABLE_TYPE = 0x8010;
enum GLX_RENDER_TYPE = 0x8011;
enum GLX_X_VISUAL_TYPE = 0x22;
enum GLX_TRUE_COLOR = 0x8002;
enum GLX_WINDOW_BIT = 0x00000001;
enum GLX_RGBA_BIT = 0x00000001;
enum GLX_COLOR_INDEX_BIT = 0x00000002;
enum GLX_SAMPLE_BUFFERS = 0x186a0;
enum GLX_SAMPLES = 0x186a1;
enum GLX_CONTEXT_MAJOR_VERSION_ARB = 0x2091;
enum GLX_CONTEXT_MINOR_VERSION_ARB = 0x2092;
}
// GLX_EXT_swap_control
alias glXSwapIntervalEXT = void function (Display* dpy, /*GLXDrawable*/Drawable drawable, int interval);
private __gshared glXSwapIntervalEXT _glx_swapInterval_fn = null;
//k8: ugly code to prevent warnings when sdpy is compiled into .a
extern(System) {
alias glXCreateContextAttribsARB_fna = GLXContext function (Display *dpy, GLXFBConfig config, GLXContext share_context, /*Bool*/int direct, const(int)* attrib_list);
}
private __gshared /*glXCreateContextAttribsARB_fna*/void* glXCreateContextAttribsARBFn = cast(void*)1; //HACK!
// this made public so we don't have to get it again and again
public bool glXCreateContextAttribsARB_present () {
if (glXCreateContextAttribsARBFn is cast(void*)1) {
// get it
glXCreateContextAttribsARBFn = cast(void*)glbindGetProcAddress("glXCreateContextAttribsARB");
//{ import core.stdc.stdio; printf("checking glXCreateContextAttribsARB: %shere\n", (glXCreateContextAttribsARBFn !is null ? "".ptr : "not ".ptr)); }
}
return (glXCreateContextAttribsARBFn !is null);
}
// this made public so we don't have to get it again and again
public GLXContext glXCreateContextAttribsARB (Display *dpy, GLXFBConfig config, GLXContext share_context, /*Bool*/int direct, const(int)* attrib_list) {
if (!glXCreateContextAttribsARB_present()) assert(0, "glXCreateContextAttribsARB is not present");
return (cast(glXCreateContextAttribsARB_fna)glXCreateContextAttribsARBFn)(dpy, config, share_context, direct, attrib_list);
}
// extern(C) private __gshared int function(int) glXSwapIntervalSGI; // seems totally redundant to the tohers
extern(C) private __gshared int function(int) glXSwapIntervalMESA;
void glxSetVSync (Display* dpy, /*GLXDrawable*/Drawable drawable, bool wait) {
if (cast(void*)_glx_swapInterval_fn is cast(void*)1) return;
if (_glx_swapInterval_fn is null) {
_glx_swapInterval_fn = cast(glXSwapIntervalEXT)glXGetProcAddress("glXSwapIntervalEXT");
if (_glx_swapInterval_fn is null) {
_glx_swapInterval_fn = cast(glXSwapIntervalEXT)1;
return;
}
version(sdddd) { import std.stdio; debug writeln("glXSwapIntervalEXT found!"); }
}
if(glXSwapIntervalMESA is null) {
// it seems to require both to actually take effect on many computers
// idk why
glXSwapIntervalMESA = cast(typeof(glXSwapIntervalMESA)) glXGetProcAddress("glXSwapIntervalMESA");
if(glXSwapIntervalMESA is null)
glXSwapIntervalMESA = cast(typeof(glXSwapIntervalMESA)) 1;
}
if(cast(void*) glXSwapIntervalMESA > cast(void*) 1)
glXSwapIntervalMESA(wait ? 1 : 0);
_glx_swapInterval_fn(dpy, drawable, (wait ? 1 : 0));
}
} else version(Windows) {
static if (!SdpyIsUsingIVGLBinds) {
enum GL_TRUE = 1;
enum GL_FALSE = 0;
alias int GLint;
public void* glbindGetProcAddress (const(char)* name) {
void* res = wglGetProcAddress(name);
if (res is null) {
/+
//{ import core.stdc.stdio; printf("GL: '%s' not found (0)\n", name); }
import core.sys.windows.windef, core.sys.windows.winbase;
__gshared HINSTANCE dll = null;
if (dll is null) {
dll = LoadLibraryA("opengl32.dll");
if (dll is null) return null; // <32, but idc
}
res = GetProcAddress(dll, name);
+/
res = GetProcAddress(gl.libHandle, name);
}
//{ import core.stdc.stdio; printf(" GL: '%s' is 0x%08x\n", name, cast(uint)res); }
return res;
}
}
private __gshared extern(System) BOOL function(int) wglSwapIntervalEXT;
void wglSetVSync(bool wait) {
if(wglSwapIntervalEXT is null) {
wglSwapIntervalEXT = cast(typeof(wglSwapIntervalEXT)) wglGetProcAddress("wglSwapIntervalEXT");
if(wglSwapIntervalEXT is null)
wglSwapIntervalEXT = cast(typeof(wglSwapIntervalEXT)) 1;
}
if(cast(void*) wglSwapIntervalEXT is cast(void*) 1)
return;
wglSwapIntervalEXT(wait ? 1 : 0);
}
enum WGL_CONTEXT_MAJOR_VERSION_ARB = 0x2091;
enum WGL_CONTEXT_MINOR_VERSION_ARB = 0x2092;
enum WGL_CONTEXT_LAYER_PLANE_ARB = 0x2093;
enum WGL_CONTEXT_FLAGS_ARB = 0x2094;
enum WGL_CONTEXT_PROFILE_MASK_ARB = 0x9126;
enum WGL_CONTEXT_DEBUG_BIT_ARB = 0x0001;
enum WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB = 0x0002;
enum WGL_CONTEXT_CORE_PROFILE_BIT_ARB = 0x00000001;
enum WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB = 0x00000002;
alias wglCreateContextAttribsARB_fna = HGLRC function (HDC hDC, HGLRC hShareContext, const(int)* attribList);
__gshared wglCreateContextAttribsARB_fna wglCreateContextAttribsARB = null;
void wglInitOtherFunctions () {
if (wglCreateContextAttribsARB is null) {
wglCreateContextAttribsARB = cast(wglCreateContextAttribsARB_fna)glbindGetProcAddress("wglCreateContextAttribsARB");
}
}
}
static if (!SdpyIsUsingIVGLBinds) {
interface GL {
extern(System) @nogc nothrow:
void glGetIntegerv(int, void*);
void glMatrixMode(int);
void glPushMatrix();
void glLoadIdentity();
void glOrtho(double, double, double, double, double, double);
void glFrustum(double, double, double, double, double, double);
void glPopMatrix();
void glEnable(int);
void glDisable(int);
void glClear(int);
void glBegin(int);
void glVertex2f(float, float);
void glVertex3f(float, float, float);
void glEnd();
void glColor3b(byte, byte, byte);
void glColor3ub(ubyte, ubyte, ubyte);
void glColor4b(byte, byte, byte, byte);
void glColor4ub(ubyte, ubyte, ubyte, ubyte);
void glColor3i(int, int, int);
void glColor3ui(uint, uint, uint);
void glColor4i(int, int, int, int);
void glColor4ui(uint, uint, uint, uint);
void glColor3f(float, float, float);
void glColor4f(float, float, float, float);
void glTranslatef(float, float, float);
void glScalef(float, float, float);
version(X11) {
void glSecondaryColor3b(byte, byte, byte);
void glSecondaryColor3ub(ubyte, ubyte, ubyte);
void glSecondaryColor3i(int, int, int);
void glSecondaryColor3ui(uint, uint, uint);
void glSecondaryColor3f(float, float, float);
}
void glDrawElements(int, int, int, void*);
void glRotatef(float, float, float, float);
uint glGetError();
void glDeleteTextures(int, uint*);
void glRasterPos2i(int, int);
void glDrawPixels(int, int, uint, uint, void*);
void glClearColor(float, float, float, float);
void glPixelStorei(uint, int);
void glGenTextures(uint, uint*);
void glBindTexture(int, int);
void glTexParameteri(uint, uint, int);
void glTexParameterf(uint/*GLenum*/ target, uint/*GLenum*/ pname, float param);
void glTexImage2D(int, int, int, int, int, int, int, int, in void*);
void glTexSubImage2D(uint/*GLenum*/ target, int level, int xoffset, int yoffset,
/*GLsizei*/int width, /*GLsizei*/int height,
uint/*GLenum*/ format, uint/*GLenum*/ type, in void* pixels);
void glTexEnvf(uint/*GLenum*/ target, uint/*GLenum*/ pname, float param);
void glLineWidth(int);
void glTexCoord2f(float, float);
void glVertex2i(int, int);
void glBlendFunc (int, int);
void glDepthFunc (int);
void glViewport(int, int, int, int);
void glClearDepth(double);
void glReadBuffer(uint);
void glReadPixels(int, int, int, int, int, int, void*);
void glFlush();
void glFinish();
version(Windows) {
BOOL wglCopyContext(HGLRC, HGLRC, UINT);
HGLRC wglCreateContext(HDC);
HGLRC wglCreateLayerContext(HDC, int);
BOOL wglDeleteContext(HGLRC);
BOOL wglDescribeLayerPlane(HDC, int, int, UINT, LPLAYERPLANEDESCRIPTOR);
HGLRC wglGetCurrentContext();
HDC wglGetCurrentDC();
int wglGetLayerPaletteEntries(HDC, int, int, int, COLORREF*);
PROC wglGetProcAddress(LPCSTR);
BOOL wglMakeCurrent(HDC, HGLRC);
BOOL wglRealizeLayerPalette(HDC, int, BOOL);
int wglSetLayerPaletteEntries(HDC, int, int, int, const(COLORREF)*);
BOOL wglShareLists(HGLRC, HGLRC);
BOOL wglSwapLayerBuffers(HDC, UINT);
BOOL wglUseFontBitmapsA(HDC, DWORD, DWORD, DWORD);
BOOL wglUseFontBitmapsW(HDC, DWORD, DWORD, DWORD);
BOOL wglUseFontOutlinesA(HDC, DWORD, DWORD, DWORD, FLOAT, FLOAT, int, LPGLYPHMETRICSFLOAT);
BOOL wglUseFontOutlinesW(HDC, DWORD, DWORD, DWORD, FLOAT, FLOAT, int, LPGLYPHMETRICSFLOAT);
}
}
interface GL3 {
extern(System) @nogc nothrow:
void glGenVertexArrays(GLsizei, GLuint*);
void glBindVertexArray(GLuint);
void glDeleteVertexArrays(GLsizei, const(GLuint)*);
void glGenerateMipmap(GLenum);
void glBufferSubData(GLenum, GLintptr, GLsizeiptr, const(GLvoid)*);
void glStencilMask(GLuint);
void glStencilFunc(GLenum, GLint, GLuint);
void glGetShaderInfoLog(GLuint, GLsizei, GLsizei*, GLchar*);
void glGetProgramInfoLog(GLuint, GLsizei, GLsizei*, GLchar*);
GLuint glCreateProgram();
GLuint glCreateShader(GLenum);
void glShaderSource(GLuint, GLsizei, const(GLchar*)*, const(GLint)*);
void glCompileShader(GLuint);
void glGetShaderiv(GLuint, GLenum, GLint*);
void glAttachShader(GLuint, GLuint);
void glBindAttribLocation(GLuint, GLuint, const(GLchar)*);
void glLinkProgram(GLuint);
void glGetProgramiv(GLuint, GLenum, GLint*);
void glDeleteProgram(GLuint);
void glDeleteShader(GLuint);
GLint glGetUniformLocation(GLuint, const(GLchar)*);
void glGenBuffers(GLsizei, GLuint*);
void glUniform1f(GLint location, GLfloat v0);
void glUniform2f(GLint location, GLfloat v0, GLfloat v1);
void glUniform3f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
void glUniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
void glUniform1i(GLint location, GLint v0);
void glUniform2i(GLint location, GLint v0, GLint v1);
void glUniform3i(GLint location, GLint v0, GLint v1, GLint v2);
void glUniform4i(GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
void glUniform1ui(GLint location, GLuint v0);
void glUniform2ui(GLint location, GLuint v0, GLuint v1);
void glUniform3ui(GLint location, GLuint v0, GLuint v1, GLuint v2);
void glUniform4ui(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
void glUniform1fv(GLint location, GLsizei count, const GLfloat *value);
void glUniform2fv(GLint location, GLsizei count, const GLfloat *value);
void glUniform3fv(GLint location, GLsizei count, const GLfloat *value);
void glUniform4fv(GLint location, GLsizei count, const GLfloat *value);
void glUniform1iv(GLint location, GLsizei count, const GLint *value);
void glUniform2iv(GLint location, GLsizei count, const GLint *value);
void glUniform3iv(GLint location, GLsizei count, const GLint *value);
void glUniform4iv(GLint location, GLsizei count, const GLint *value);
void glUniform1uiv(GLint location, GLsizei count, const GLuint *value);
void glUniform2uiv(GLint location, GLsizei count, const GLuint *value);
void glUniform3uiv(GLint location, GLsizei count, const GLuint *value);
void glUniform4uiv(GLint location, GLsizei count, const GLuint *value);
void glUniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
void glUniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
void glUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
void glUniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
void glUniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
void glUniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
void glUniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
void glUniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
void glUniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
void glColorMask(GLboolean, GLboolean, GLboolean, GLboolean);
void glStencilOpSeparate(GLenum, GLenum, GLenum, GLenum);
void glDrawArrays(GLenum, GLint, GLsizei);
void glStencilOp(GLenum, GLenum, GLenum);
void glUseProgram(GLuint);
void glCullFace(GLenum);
void glFrontFace(GLenum);
void glActiveTexture(GLenum);
void glBindBuffer(GLenum, GLuint);
void glBufferData(GLenum, GLsizeiptr, const(void)*, GLenum);
void glEnableVertexAttribArray(GLuint);
void glVertexAttribPointer(GLuint, GLint, GLenum, GLboolean, GLsizei, const(void)*);
void glUniform1i(GLint, GLint);
void glUniform2fv(GLint, GLsizei, const(GLfloat)*);
void glDisableVertexAttribArray(GLuint);
void glDeleteBuffers(GLsizei, const(GLuint)*);
void glBlendFuncSeparate(GLenum, GLenum, GLenum, GLenum);
void glLogicOp (GLenum opcode);
void glFramebufferTexture2D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
void glDeleteFramebuffers (GLsizei n, const(GLuint)* framebuffers);
void glGenFramebuffers (GLsizei n, GLuint* framebuffers);
GLenum glCheckFramebufferStatus (GLenum target);
void glBindFramebuffer (GLenum target, GLuint framebuffer);
}
interface GL4 {
extern(System) @nogc nothrow:
void glTextureSubImage2D(uint texture, int level, int xoffset, int yoffset,
/*GLsizei*/int width, /*GLsizei*/int height,
uint/*GLenum*/ format, uint/*GLenum*/ type, in void* pixels);
}
interface GLU {
extern(System) @nogc nothrow:
void gluLookAt(double, double, double, double, double, double, double, double, double);
void gluPerspective(double, double, double, double);
char* gluErrorString(uint);
}
enum GL_RED = 0x1903;
enum GL_ALPHA = 0x1906;
enum uint GL_FRONT = 0x0404;
enum uint GL_BLEND = 0x0be2;
enum uint GL_LEQUAL = 0x0203;
enum uint GL_RGB = 0x1907;
enum uint GL_BGRA = 0x80e1;
enum uint GL_RGBA = 0x1908;
enum uint GL_TEXTURE_2D = 0x0DE1;
enum uint GL_TEXTURE_MIN_FILTER = 0x2801;
enum uint GL_NEAREST = 0x2600;
enum uint GL_LINEAR = 0x2601;
enum uint GL_TEXTURE_MAG_FILTER = 0x2800;
enum uint GL_TEXTURE_WRAP_S = 0x2802;
enum uint GL_TEXTURE_WRAP_T = 0x2803;
enum uint GL_REPEAT = 0x2901;
enum uint GL_CLAMP = 0x2900;
enum uint GL_CLAMP_TO_EDGE = 0x812F;
enum uint GL_CLAMP_TO_BORDER = 0x812D;
enum uint GL_DECAL = 0x2101;
enum uint GL_MODULATE = 0x2100;
enum uint GL_TEXTURE_ENV = 0x2300;
enum uint GL_TEXTURE_ENV_MODE = 0x2200;
enum uint GL_REPLACE = 0x1E01;
enum uint GL_LIGHTING = 0x0B50;
enum uint GL_DITHER = 0x0BD0;
enum uint GL_NO_ERROR = 0;
enum int GL_VIEWPORT = 0x0BA2;
enum int GL_MODELVIEW = 0x1700;
enum int GL_TEXTURE = 0x1702;
enum int GL_PROJECTION = 0x1701;
enum int GL_DEPTH_TEST = 0x0B71;
enum int GL_COLOR_BUFFER_BIT = 0x00004000;
enum int GL_ACCUM_BUFFER_BIT = 0x00000200;
enum int GL_DEPTH_BUFFER_BIT = 0x00000100;
enum uint GL_STENCIL_BUFFER_BIT = 0x00000400;
enum int GL_POINTS = 0x0000;
enum int GL_LINES = 0x0001;
enum int GL_LINE_LOOP = 0x0002;
enum int GL_LINE_STRIP = 0x0003;
enum int GL_TRIANGLES = 0x0004;
enum int GL_TRIANGLE_STRIP = 5;
enum int GL_TRIANGLE_FAN = 6;
enum int GL_QUADS = 7;
enum int GL_QUAD_STRIP = 8;
enum int GL_POLYGON = 9;
alias GLvoid = void;
alias GLboolean = ubyte;
alias GLuint = uint;
alias GLenum = uint;
alias GLchar = char;
alias GLsizei = int;
alias GLfloat = float;
alias GLintptr = size_t;
alias GLsizeiptr = ptrdiff_t;
enum uint GL_INVALID_ENUM = 0x0500;
enum uint GL_ZERO = 0;
enum uint GL_ONE = 1;
enum uint GL_BYTE = 0x1400;
enum uint GL_UNSIGNED_BYTE = 0x1401;
enum uint GL_SHORT = 0x1402;
enum uint GL_UNSIGNED_SHORT = 0x1403;
enum uint GL_INT = 0x1404;
enum uint GL_UNSIGNED_INT = 0x1405;
enum uint GL_FLOAT = 0x1406;
enum uint GL_2_BYTES = 0x1407;
enum uint GL_3_BYTES = 0x1408;
enum uint GL_4_BYTES = 0x1409;
enum uint GL_DOUBLE = 0x140A;
enum uint GL_STREAM_DRAW = 0x88E0;
enum uint GL_CCW = 0x0901;
enum uint GL_STENCIL_TEST = 0x0B90;
enum uint GL_SCISSOR_TEST = 0x0C11;
enum uint GL_EQUAL = 0x0202;
enum uint GL_NOTEQUAL = 0x0205;
enum uint GL_ALWAYS = 0x0207;
enum uint GL_KEEP = 0x1E00;
enum uint GL_INCR = 0x1E02;
enum uint GL_INCR_WRAP = 0x8507;
enum uint GL_DECR_WRAP = 0x8508;
enum uint GL_CULL_FACE = 0x0B44;
enum uint GL_BACK = 0x0405;
enum uint GL_FRAGMENT_SHADER = 0x8B30;
enum uint GL_VERTEX_SHADER = 0x8B31;
enum uint GL_COMPILE_STATUS = 0x8B81;
enum uint GL_LINK_STATUS = 0x8B82;
enum uint GL_ELEMENT_ARRAY_BUFFER = 0x8893;
enum uint GL_STATIC_DRAW = 0x88E4;
enum uint GL_UNPACK_ALIGNMENT = 0x0CF5;
enum uint GL_UNPACK_ROW_LENGTH = 0x0CF2;
enum uint GL_UNPACK_SKIP_PIXELS = 0x0CF4;
enum uint GL_UNPACK_SKIP_ROWS = 0x0CF3;
enum uint GL_GENERATE_MIPMAP = 0x8191;
enum uint GL_LINEAR_MIPMAP_LINEAR = 0x2703;
enum uint GL_TEXTURE0 = 0x84C0U;
enum uint GL_TEXTURE1 = 0x84C1U;
enum uint GL_ARRAY_BUFFER = 0x8892;
enum uint GL_SRC_COLOR = 0x0300;
enum uint GL_ONE_MINUS_SRC_COLOR = 0x0301;
enum uint GL_SRC_ALPHA = 0x0302;
enum uint GL_ONE_MINUS_SRC_ALPHA = 0x0303;
enum uint GL_DST_ALPHA = 0x0304;
enum uint GL_ONE_MINUS_DST_ALPHA = 0x0305;
enum uint GL_DST_COLOR = 0x0306;
enum uint GL_ONE_MINUS_DST_COLOR = 0x0307;
enum uint GL_SRC_ALPHA_SATURATE = 0x0308;
enum uint GL_INVERT = 0x150AU;
enum uint GL_DEPTH_STENCIL = 0x84F9U;
enum uint GL_UNSIGNED_INT_24_8 = 0x84FAU;
enum uint GL_FRAMEBUFFER = 0x8D40U;
enum uint GL_COLOR_ATTACHMENT0 = 0x8CE0U;
enum uint GL_DEPTH_STENCIL_ATTACHMENT = 0x821AU;
enum uint GL_FRAMEBUFFER_COMPLETE = 0x8CD5U;
enum uint GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6U;
enum uint GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7U;
enum uint GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8CD9U;
enum uint GL_FRAMEBUFFER_UNSUPPORTED = 0x8CDDU;
enum uint GL_COLOR_LOGIC_OP = 0x0BF2U;
enum uint GL_CLEAR = 0x1500U;
enum uint GL_COPY = 0x1503U;
enum uint GL_XOR = 0x1506U;
enum uint GL_FRAMEBUFFER_BINDING = 0x8CA6U;
enum uint GL_TEXTURE_LOD_BIAS = 0x8501;
}
}
/++
History:
Added September 10, 2021. Previously it would have listed openGlLibrariesSuccessfullyLoaded as false if it couldn't find GLU but really opengl3 works fine without it so I didn't want to keep it required anymore.
+/
__gshared bool gluSuccessfullyLoaded = true;
version(without_opengl) {} else {
static if(!SdpyIsUsingIVGLBinds) {
version(Windows) {
mixin DynamicLoad!(GL, "opengl32", 1, openGlLibrariesSuccessfullyLoaded) gl;
mixin DynamicLoad!(GLU, "glu32", 1, gluSuccessfullyLoaded) glu;
} else {
mixin DynamicLoad!(GL, "GL", 1, openGlLibrariesSuccessfullyLoaded) gl;
mixin DynamicLoad!(GLU, "GLU", 3, gluSuccessfullyLoaded) glu;
}
mixin DynamicLoadSupplementalOpenGL!(GL3) gl3;
shared static this() {
gl.loadDynamicLibrary();
// FIXME: this is NOT actually required and should NOT fail if it is not loaded
// unless those functions are actually used
// go to mark b openGlLibrariesSuccessfullyLoaded = false;
glu.loadDynamicLibrary();
}
}
}
/++
Convenience method for converting D arrays to opengl buffer data
I would LOVE to overload it with the original glBufferData, but D won't
let me since glBufferData is a function pointer :(
Added: August 25, 2020 (version 8.5)
+/
version(without_opengl) {} else
void glBufferDataSlice(GLenum target, const(void[]) data, GLenum usage) {
glBufferData(target, data.length, data.ptr, usage);
}
/+
/++
A matrix for simple uses that easily integrates with [OpenGlShader].
Might not be useful to you since it only as some simple functions and
probably isn't that fast.
Note it uses an inline static array for its storage, so copying it
may be expensive.
+/
struct BasicMatrix(int columns, int rows, T = float) {
import core.stdc.math;
T[columns * rows] data = 0.0;
/++
Basic operations that operate *in place*.
+/
void translate() {
}
/// ditto
void scale() {
}
/// ditto
void rotate() {
}
/++
+/
static if(columns == rows)
static BasicMatrix identity() {
BasicMatrix m;
foreach(i; 0 .. columns)
data[0 + i + i * columns] = 1.0;
return m;
}
static BasicMatrix ortho() {
return BasicMatrix.init;
}
}
+/
/++
Convenience class for using opengl shaders.
Ensure that you've loaded opengl 3+ and set your active
context before trying to use this.
Added: August 25, 2020 (version 8.5)
+/
version(without_opengl) {} else
final class OpenGlShader {
private int shaderProgram_;
private @property void shaderProgram(int a) {
shaderProgram_ = a;
}
/// Get the program ID for use in OpenGL functions.
public @property int shaderProgram() {
return shaderProgram_;
}
/++
+/
static struct Source {
uint type; /// GL_FRAGMENT_SHADER, GL_VERTEX_SHADER, etc.
string code; ///
}
/++
Helper method to just compile some shader code and check for errors
while you do glCreateShader, etc. on the outside yourself.
This just does `glShaderSource` and `glCompileShader` for the given code.
If you the OpenGlShader class constructor, you never need to call this yourself.
+/
static void compile(int sid, Source code) {
const(char)*[1] buffer;
int[1] lengthBuffer;
buffer[0] = code.code.ptr;
lengthBuffer[0] = cast(int) code.code.length;
glShaderSource(sid, cast(int) buffer.length, buffer.ptr, lengthBuffer.ptr);
glCompileShader(sid);
int success;
glGetShaderiv(sid, GL_COMPILE_STATUS, &success);
if(!success) {
char[512] info;
int len;
glGetShaderInfoLog(sid, info.length, &len, info.ptr);
throw new Exception("Shader compile failure: " ~ cast(immutable) info[0 .. len]);
}
}
/++
Calls `glLinkProgram` and throws if error a occurs.
If you the OpenGlShader class constructor, you never need to call this yourself.
+/
static void link(int shaderProgram) {
glLinkProgram(shaderProgram);
int success;
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if(!success) {
char[512] info;
int len;
glGetProgramInfoLog(shaderProgram, info.length, &len, info.ptr);
throw new Exception("Shader link failure: " ~ cast(immutable) info[0 .. len]);
}
}
/++
Constructs the shader object by calling `glCreateProgram`, then
compiling each given [Source], and finally, linking them together.
Throws: on compile or link failure.
+/
this(Source[] codes...) {
shaderProgram = glCreateProgram();
int[16] shadersBufferStack;
int[] shadersBuffer = codes.length <= shadersBufferStack.length ?
shadersBufferStack[0 .. codes.length] :
new int[](codes.length);
foreach(idx, code; codes) {
shadersBuffer[idx] = glCreateShader(code.type);
compile(shadersBuffer[idx], code);
glAttachShader(shaderProgram, shadersBuffer[idx]);
}
link(shaderProgram);
foreach(s; shadersBuffer)
glDeleteShader(s);
}
/// Calls `glUseProgram(this.shaderProgram)`
void use() {
glUseProgram(this.shaderProgram);
}
/// Deletes the program.
void delete_() {
glDeleteProgram(shaderProgram);
shaderProgram = 0;
}
/++
[OpenGlShader.uniforms].name gives you one of these.
You can get the id out of it or just assign
+/
static struct Uniform {
/// the id passed to glUniform*
int id;
/// Assigns the 4 floats. You will probably have to call this via the .opAssign name
void opAssign(float x, float y, float z, float w) {
if(id != -1)
glUniform4f(id, x, y, z, w);
}
void opAssign(float x) {
if(id != -1)
glUniform1f(id, x);
}
void opAssign(float x, float y) {
if(id != -1)
glUniform2f(id, x, y);
}
void opAssign(T)(T t) {
t.glUniform(id);
}
}
static struct UniformsHelper {
OpenGlShader _shader;
@property Uniform opDispatch(string name)() {
auto i = glGetUniformLocation(_shader.shaderProgram, name.ptr);
// FIXME: decide what to do here; the exception is liable to be swallowed by the event syste
//if(i == -1)
//throw new Exception("Could not find uniform " ~ name);
return Uniform(i);
}
@property void opDispatch(string name, T)(T t) {
Uniform f = this.opDispatch!name;
t.glUniform(f);
}
}
/++
Gives access to the uniforms through dot access.
`OpenGlShader.Uniform = shader.uniforms.foo; // calls glGetUniformLocation(this, "foo");
+/
@property UniformsHelper uniforms() { return UniformsHelper(this); }
}
version(without_opengl) {} else {
/++
A static container of experimental types and value constructors for opengl 3+ shaders.
You can declare variables like:
```
OGL.vec3f something;
```
But generally it would be used with [OpenGlShader]'s uniform helpers like
```
shader.uniforms.mouse = OGL.vec(mouseX, mouseY); // or OGL.vec2f if you want to be more specific
```
This is still extremely experimental, not very useful at this point, and thus subject to change at random.
History:
Added December 7, 2021. Not yet stable.
+/
final class OGL {
static:
private template typeFromSpecifier(string specifier) {
static if(specifier == "f")
alias typeFromSpecifier = GLfloat;
else static if(specifier == "i")
alias typeFromSpecifier = GLint;
else static if(specifier == "ui")
alias typeFromSpecifier = GLuint;
else static assert(0, "I don't know this ogl type suffix " ~ specifier);
}
private template CommonType(T...) {
static if(T.length == 1)
alias CommonType = T[0];
else static if(is(typeof(true ? T[0].init : T[1].init) C))
alias CommonType = CommonType!(C, T[2 .. $]);
}
private template typesToSpecifier(T...) {
static if(is(CommonType!T == float))
enum typesToSpecifier = "f";
else static if(is(CommonType!T == int))
enum typesToSpecifier = "i";
else static if(is(CommonType!T == uint))
enum typesToSpecifier = "ui";
else static assert(0, "I can't find a gl type suffix for common type " ~ CommonType!T.stringof);
}
private template genNames(size_t dim, size_t dim2 = 0) {
string helper() {
string s;
if(dim2) {
s ~= "type["~(dim + '0')~"]["~(dim2 + '0')~"] matrix;";
} else {
if(dim > 0) s ~= "type x = 0;";
if(dim > 1) s ~= "type y = 0;";
if(dim > 2) s ~= "type z = 0;";
if(dim > 3) s ~= "type w = 0;";
}
return s;
}
enum genNames = helper();
}
// there's vec, arrays of vec, mat, and arrays of mat
template opDispatch(string name)
if(name.length > 4 && (name[0 .. 3] == "vec" || name[0 .. 3] == "mat"))
{
static if(name[4] == 'x') {
enum dimX = cast(int) (name[3] - '0');
static assert(dimX > 0 && dimX <= 4, "Bad dimension for OGL X type " ~ name[3]);
enum dimY = cast(int) (name[5] - '0');
static assert(dimY > 0 && dimY <= 4, "Bad dimension for OGL Y type " ~ name[5]);
enum isArray = name[$ - 1] == 'v';
enum typeSpecifier = isArray ? name[6 .. $ - 1] : name[6 .. $];
alias type = typeFromSpecifier!typeSpecifier;
} else {
enum dim = cast(int) (name[3] - '0');
static assert(dim > 0 && dim <= 4, "Bad dimension for OGL type " ~ name[3]);
enum isArray = name[$ - 1] == 'v';
enum typeSpecifier = isArray ? name[4 .. $ - 1] : name[4 .. $];
alias type = typeFromSpecifier!typeSpecifier;
}
align(1)
struct opDispatch {
align(1):
static if(name[4] == 'x')
mixin(genNames!(dimX, dimY));
else
mixin(genNames!dim);
private void glUniform(OpenGlShader.Uniform assignTo) {
glUniform(assignTo.id);
}
private void glUniform(int assignTo) {
static if(name[4] == 'x') {
// FIXME
pragma(msg, "This matrix uniform helper has never been tested!!!!");
mixin("glUniformMatrix" ~ name[3 .. $] ~ "v")(assignTo, dimX * dimY, false, this.matrix.ptr);
} else
mixin("glUniform" ~ name[3 .. $])(assignTo, this.tupleof);
}
}
}
auto vec(T...)(T members) {
return typeof(this).opDispatch!("vec" ~ toInternal!string(cast(int) T.length)~ typesToSpecifier!T)(members);
}
}
}
version(linux) {
version(with_eventloop) {} else {
private int epollFd = -1;
void prepareEventLoop() {
if(epollFd != -1)
return; // already initialized, no need to do it again
import ep = core.sys.linux.epoll;
epollFd = ep.epoll_create1(ep.EPOLL_CLOEXEC);
if(epollFd == -1)
throw new Exception("epoll create failure");
}
}
} else version(Posix) {
void prepareEventLoop() {}
}
version(X11) {
import core.stdc.locale : LC_ALL; // rdmd fix
__gshared bool sdx_isUTF8Locale;
// This whole crap is used to initialize X11 locale, so that you can use XIM methods later.
// Yes, there are people with non-utf locale (it's me, Ketmar!), but XIM (composing) will
// not work right if app/X11 locale is not utf. This sux. That's why all that "utf detection"
// anal magic is here. I (Ketmar) hope you like it.
// We will use `sdx_isUTF8Locale` on XIM creation to enforce UTF-8 locale, so XCompose will
// always return correct unicode symbols. The detection is here 'cause user can change locale
// later.
// NOTE: IT IS VERY IMPORTANT THAT THIS BE THE LAST STATIC CTOR OF THE FILE since it tests librariesSuccessfullyLoaded
shared static this () {
if(!librariesSuccessfullyLoaded)
return;
import core.stdc.locale : setlocale, LC_ALL, LC_CTYPE;
// this doesn't hurt; it may add some locking, but the speed is still
// allows doing 60 FPS videogames; also, ignore the result, as most
// users will probably won't do mulththreaded X11 anyway (and I (ketmar)
// never seen this failing).
if (XInitThreads() == 0) { import core.stdc.stdio; fprintf(stderr, "XInitThreads() failed!\n"); }
setlocale(LC_ALL, "");
// check if out locale is UTF-8
auto lct = setlocale(LC_CTYPE, null);
if (lct is null) {
sdx_isUTF8Locale = false;
} else {
for (size_t idx = 0; lct[idx] && lct[idx+1] && lct[idx+2]; ++idx) {
if ((lct[idx+0] == 'u' || lct[idx+0] == 'U') &&
(lct[idx+1] == 't' || lct[idx+1] == 'T') &&
(lct[idx+2] == 'f' || lct[idx+2] == 'F'))
{
sdx_isUTF8Locale = true;
break;
}
}
}
//{ import core.stdc.stdio : stderr, fprintf; fprintf(stderr, "UTF8: %s\n", sdx_isUTF8Locale ? "tan".ptr : "ona".ptr); }
}
}
class ExperimentalTextComponent2 {
/+
Stage 1: get it working monospace
Stage 2: use proportional font
Stage 3: allow changes in inline style
Stage 4: allow new fonts and sizes in the middle
Stage 5: optimize gap buffer
Stage 6: optimize layout
Stage 7: word wrap
Stage 8: justification
Stage 9: editing, selection, etc.
Operations:
insert text
overstrike text
select
cut
modify
+/
/++
It asks for a window so it can translate abstract font sizes to actual on-screen values depending on the window's current dpi, scaling settings, etc.
+/
this(SimpleWindow window) {
this.window = window;
}
private SimpleWindow window;
/++
When you render a [ComponentInFlow], it returns an arbitrary number of these interfaces
representing the internal parts. The first pass is focused on the x parameter, then the
renderer is responsible for going back to the parts in the current line and calling
adjustDownForAscent to change the y params.
+/
static interface ComponentRenderHelper {
/+
When you do an edit, possibly stuff on the same line previously need to move (to adjust
the baseline), stuff subsequent needs to move (adjust x) and possibly stuff below needs
to move (adjust y to make room for new line) until you get back to the same position,
then you can stop - if one thing is unchanged, nothing after it is changed too.
Word wrap might change this as if can rewrap tons of stuff, but the same idea applies,
once you reach something that is unchanged, you can stop.
+/
void adjustDownForAscent(int amount); // at the end of the line it needs to do these
int ascent() const;
int descent() const;
int advance() const;
bool endsWithExplititLineBreak() const;
}
static interface RenderResult {
/++
This is responsible for using what space is left (your object is responsible for keeping its own state after getting it updated from [repositionForNextLine]) and not going over if at all possible. If you can word wrap, you should when space is out. Otherwise, you can keep going if it means overflow hidden or scroll.
+/
void popFront();
@property bool empty() const;
@property ComponentRenderHelper front() const;
void repositionForNextLine(Point baseline, int availableWidth);
}
static interface ComponentInFlow {
void draw(ScreenPainter painter);
//RenderResult render(Point baseline, int availableWidth); // FIXME: it needs to be able to say "my cache is good, nothing different"
bool startsWithExplicitLineBreak() const;
}
static class TextFlowComponent : ComponentInFlow {
bool startsWithExplicitLineBreak() const { return false; } // FIXME: if it is block this can return true
Color foreground;
Color background;
OperatingSystemFont font; // should NEVER be null
ubyte attributes; // underline, strike through, display on new block
version(Windows)
const(wchar)[] content;
else
const(char)[] content; // this should NEVER have a newline, except at the end
RenderedComponent[] rendered; // entirely controlled by [rerender]
// could prolly put some spacing around it too like margin / padding
this(Color f, Color b, OperatingSystemFont font, ubyte attr, const(char)[] c)
in { assert(font !is null);
assert(!font.isNull); }
do
{
this.foreground = f;
this.background = b;
this.font = font;
this.attributes = attr;
version(Windows) {
auto conversionFlags = 0;//WindowsStringConversionFlags.convertNewLines;
auto sz = sizeOfConvertedWstring(c, conversionFlags);
auto buffer = new wchar[](sz);
this.content = makeWindowsString(c, buffer, conversionFlags);
} else {
this.content = c.dup;
}
}
void draw(ScreenPainter painter) {
painter.setFont(this.font);
painter.outlineColor = this.foreground;
painter.fillColor = Color.transparent;
foreach(rendered; this.rendered) {
// the component works in term of baseline,
// but the painter works in term of upper left bounding box
// so need to translate that
if(this.background.a) {
painter.fillColor = this.background;
painter.outlineColor = this.background;
painter.drawRectangle(Point(rendered.startX, rendered.startY - this.font.ascent), Size(rendered.width, this.font.height));
painter.outlineColor = this.foreground;
painter.fillColor = Color.transparent;
}
painter.drawText(Point(rendered.startX, rendered.startY - this.font.ascent), rendered.slice);
// FIXME: strike through, underline, highlight selection, etc.
}
}
}
// I could split the parts into words on render
// for easier word-wrap, each one being an unbreakable "inline-block"
private TextFlowComponent[] parts;
private int needsRerenderFrom;
void addPart(Color f, Color b, OperatingSystemFont font, ubyte attr, const(char)[] c) {
// FIXME: needsRerenderFrom. Basically if the bounding box and baseline is the same as the previous thing, it can prolly just stop.
parts ~= new TextFlowComponent(f, b, font, attr, c);
}
static struct RenderedComponent {
int startX;
int startY;
short width;
// height is always from the containing part's font. This saves some space and means recalculations need not continue past the current line, unless a new part is added with a different font!
// for individual chars in here you've gotta process on demand
version(Windows)
const(wchar)[] slice;
else
const(char)[] slice;
}
void rerender(Rectangle boundingBox) {
Point baseline = boundingBox.upperLeft;
this.boundingBox.left = boundingBox.left;
this.boundingBox.top = boundingBox.top;
auto remainingParts = parts;
int largestX;
foreach(part; parts)
part.font.prepareContext(window);
scope(exit)
foreach(part; parts)
part.font.releaseContext();
calculateNextLine:
int nextLineHeight = 0;
int nextBiggestDescent = 0;
foreach(part; remainingParts) {
auto height = part.font.ascent;
if(height > nextLineHeight)
nextLineHeight = height;
if(part.font.descent > nextBiggestDescent)
nextBiggestDescent = part.font.descent;
if(part.content.length && part.content[$-1] == '\n')
break;
}
baseline.y += nextLineHeight;
auto lineStart = baseline;
while(remainingParts.length) {
remainingParts[0].rendered = null;
bool eol;
if(remainingParts[0].content.length && remainingParts[0].content[$-1] == '\n')
eol = true;
// FIXME: word wrap
auto font = remainingParts[0].font;
auto slice = remainingParts[0].content[0 .. $ - (eol ? 1 : 0)];
auto width = font.stringWidth(slice, window);
remainingParts[0].rendered ~= RenderedComponent(baseline.x, baseline.y, cast(short) width, slice);
remainingParts = remainingParts[1 .. $];
baseline.x += width;
if(eol) {
baseline.y += nextBiggestDescent;
if(baseline.x > largestX)
largestX = baseline.x;
baseline.x = lineStart.x;
goto calculateNextLine;
}
}
if(baseline.x > largestX)
largestX = baseline.x;
this.boundingBox.right = largestX;
this.boundingBox.bottom = baseline.y;
}
// you must call rerender first!
void draw(ScreenPainter painter) {
foreach(part; parts) {
part.draw(painter);
}
}
struct IdentifyResult {
TextFlowComponent part;
int charIndexInPart;
int totalCharIndex = -1; // if this is -1, it just means the end
Rectangle boundingBox;
}
IdentifyResult identify(Point pt, bool exact = false) {
if(parts.length == 0)
return IdentifyResult(null, 0);
if(pt.y < boundingBox.top) {
if(exact)
return IdentifyResult(null, 1);
return IdentifyResult(parts[0], 0);
}
if(pt.y > boundingBox.bottom) {
if(exact)
return IdentifyResult(null, 2);
return IdentifyResult(parts[$-1], cast(int) parts[$-1].content.length);
}
int tci = 0;
// I should probably like binary search this or something...
foreach(ref part; parts) {
foreach(rendered; part.rendered) {
auto rect = Rectangle(rendered.startX, rendered.startY - part.font.ascent, rendered.startX + rendered.width, rendered.startY + part.font.descent);
if(rect.contains(pt)) {
auto x = pt.x - rendered.startX;
auto estimatedIdx = x / part.font.averageWidth;
if(estimatedIdx < 0)
estimatedIdx = 0;
if(estimatedIdx > rendered.slice.length)
estimatedIdx = cast(int) rendered.slice.length;
int idx;
int x1, x2;
if(part.font.isMonospace) {
auto w = part.font.averageWidth;
if(!exact && x > (estimatedIdx + 1) * w)
return IdentifyResult(null, 4);
idx = estimatedIdx;
x1 = idx * w;
x2 = (idx + 1) * w;
} else {
idx = estimatedIdx;
part.font.prepareContext(window);
scope(exit) part.font.releaseContext();
// int iterations;
while(true) {
// iterations++;
x1 = idx ? part.font.stringWidth(rendered.slice[0 .. idx - 1]) : 0;
x2 = part.font.stringWidth(rendered.slice[0 .. idx]); // should be the maximum since `averageWidth` kinda lies.
x1 += rendered.startX;
x2 += rendered.startX;
if(pt.x < x1) {
if(idx == 0) {
if(exact)
return IdentifyResult(null, 6);
else
break;
}
idx--;
} else if(pt.x > x2) {
idx++;
if(idx > rendered.slice.length) {
if(exact)
return IdentifyResult(null, 5);
else
break;
}
} else if(pt.x >= x1 && pt.x <= x2) {
if(idx)
idx--; // point it at the original index
break; // we fit
}
}
// import std.stdio; writeln(iterations)
}
return IdentifyResult(part, idx, tci + idx, Rectangle(x1, rect.top, x2, rect.bottom)); // FIXME: utf-8?
}
}
tci += cast(int) part.content.length; // FIXME: utf-8?
}
return IdentifyResult(null, 3);
}
Rectangle boundingBox; // only set after [rerender]
// text will be positioned around the exclusion zone
static struct ExclusionZone {
}
ExclusionZone[] exclusionZones;
}
// Don't use this yet. When I'm happy with it, I will move it to the
// regular module namespace.
mixin template ExperimentalTextComponent() {
static:
alias Rectangle = arsd.color.Rectangle;
struct ForegroundColor {
Color color;
alias color this;
this(Color c) {
color = c;
}
this(int r, int g, int b, int a = 255) {
color = Color(r, g, b, a);
}
static ForegroundColor opDispatch(string s)() if(__traits(compiles, ForegroundColor(mixin("Color." ~ s)))) {
return ForegroundColor(mixin("Color." ~ s));
}
}
struct BackgroundColor {
Color color;
alias color this;
this(Color c) {
color = c;
}
this(int r, int g, int b, int a = 255) {
color = Color(r, g, b, a);
}
static BackgroundColor opDispatch(string s)() if(__traits(compiles, BackgroundColor(mixin("Color." ~ s)))) {
return BackgroundColor(mixin("Color." ~ s));
}
}
static class InlineElement {
string text;
BlockElement containingBlock;
Color color = Color.black;
Color backgroundColor = Color.transparent;
ushort styles;
string font;
int fontSize;
int lineHeight;
void* identifier;
Rectangle boundingBox;
int[] letterXs; // FIXME: maybe i should do bounding boxes for every character
bool isMergeCompatible(InlineElement other) {
return
containingBlock is other.containingBlock &&
color == other.color &&
backgroundColor == other.backgroundColor &&
styles == other.styles &&
font == other.font &&
fontSize == other.fontSize &&
lineHeight == other.lineHeight &&
true;
}
int xOfIndex(size_t index) {
if(index < letterXs.length)
return letterXs[index];
else
return boundingBox.right;
}
InlineElement clone() {
auto ie = new InlineElement();
ie.tupleof = this.tupleof;
return ie;
}
InlineElement getPreviousInlineElement() {
InlineElement prev = null;
foreach(ie; this.containingBlock.parts) {
if(ie is this)
break;
prev = ie;
}
if(prev is null) {
BlockElement pb;
BlockElement cb = this.containingBlock;
moar:
foreach(ie; this.containingBlock.containingLayout.blocks) {
if(ie is cb)
break;
pb = ie;
}
if(pb is null)
return null;
if(pb.parts.length == 0) {
cb = pb;
goto moar;
}
prev = pb.parts[$-1];
}
return prev;
}
InlineElement getNextInlineElement() {
InlineElement next = null;
foreach(idx, ie; this.containingBlock.parts) {
if(ie is this) {
if(idx + 1 < this.containingBlock.parts.length)
next = this.containingBlock.parts[idx + 1];
break;
}
}
if(next is null) {
BlockElement n;
foreach(idx, ie; this.containingBlock.containingLayout.blocks) {
if(ie is this.containingBlock) {
if(idx + 1 < this.containingBlock.containingLayout.blocks.length)
n = this.containingBlock.containingLayout.blocks[idx + 1];
break;
}
}
if(n is null)
return null;
if(n.parts.length)
next = n.parts[0];
else {} // FIXME
}
return next;
}
}
// Block elements are used entirely for positioning inline elements,
// which are the things that are actually drawn.
class BlockElement {
InlineElement[] parts;
uint alignment;
int whiteSpace; // pre, pre-wrap, wrap
TextLayout containingLayout;
// inputs
Point where;
Size minimumSize;
Size maximumSize;
Rectangle[] excludedBoxes; // like if you want it to write around a floated image or something. Coordinates are relative to the bounding box.
void* identifier;
Rectangle margin;
Rectangle padding;
// outputs
Rectangle[] boundingBoxes;
}
struct TextIdentifyResult {
InlineElement element;
int offset;
private TextIdentifyResult fixupNewline() {
if(element !is null && offset < element.text.length && element.text[offset] == '\n') {
offset--;
} else if(element !is null && offset == element.text.length && element.text.length > 1 && element.text[$-1] == '\n') {
offset--;
}
return this;
}
}
class TextLayout {
BlockElement[] blocks;
Rectangle boundingBox_;
Rectangle boundingBox() { return boundingBox_; }
void boundingBox(Rectangle r) {
if(r != boundingBox_) {
boundingBox_ = r;
layoutInvalidated = true;
}
}
Rectangle contentBoundingBox() {
Rectangle r;
foreach(block; blocks)
foreach(ie; block.parts) {
if(ie.boundingBox.right > r.right)
r.right = ie.boundingBox.right;
if(ie.boundingBox.bottom > r.bottom)
r.bottom = ie.boundingBox.bottom;
}
return r;
}
BlockElement[] getBlocks() {
return blocks;
}
InlineElement[] getTexts() {
InlineElement[] elements;
foreach(block; blocks)
elements ~= block.parts;
return elements;
}
string getPlainText() {
string text;
foreach(block; blocks)
foreach(part; block.parts)
text ~= part.text;
return text;
}
string getHtml() {
return null; // FIXME
}
this(Rectangle boundingBox) {
this.boundingBox = boundingBox;
}
BlockElement addBlock(InlineElement after = null, Rectangle margin = Rectangle(0, 0, 0, 0), Rectangle padding = Rectangle(0, 0, 0, 0)) {
auto be = new BlockElement();
be.containingLayout = this;
if(after is null)
blocks ~= be;
else {
foreach(idx, b; blocks) {
if(b is after.containingBlock) {
blocks = blocks[0 .. idx + 1] ~ be ~ blocks[idx + 1 .. $];
break;
}
}
}
return be;
}
void clear() {
blocks = null;
selectionStart = selectionEnd = caret = Caret.init;
}
void addText(Args...)(Args args) {
if(blocks.length == 0)
addBlock();
InlineElement ie = new InlineElement();
foreach(idx, arg; args) {
static if(is(typeof(arg) == ForegroundColor))
ie.color = arg;
else static if(is(typeof(arg) == TextFormat)) {
if(arg & 0x8000) // ~TextFormat.something turns it off
ie.styles &= arg;
else
ie.styles |= arg;
} else static if(is(typeof(arg) == string)) {
static if(idx == 0 && args.length > 1)
static assert(0, "Put styles before the string.");
size_t lastLineIndex;
foreach(cidx, char a; arg) {
if(a == '\n') {
ie.text = arg[lastLineIndex .. cidx + 1];
lastLineIndex = cidx + 1;
ie.containingBlock = blocks[$-1];
blocks[$-1].parts ~= ie.clone;
ie.text = null;
} else {
}
}
ie.text = arg[lastLineIndex .. $];
ie.containingBlock = blocks[$-1];
blocks[$-1].parts ~= ie.clone;
caret = Caret(this, blocks[$-1].parts[$-1], cast(int) blocks[$-1].parts[$-1].text.length);
}
}
invalidateLayout();
}
void tryMerge(InlineElement into, InlineElement what) {
if(!into.isMergeCompatible(what)) {
return; // cannot merge, different configs
}
// cool, can merge, bring text together...
into.text ~= what.text;
// and remove what
for(size_t a = 0; a < what.containingBlock.parts.length; a++) {
if(what.containingBlock.parts[a] is what) {
for(size_t i = a; i < what.containingBlock.parts.length - 1; i++)
what.containingBlock.parts[i] = what.containingBlock.parts[i + 1];
what.containingBlock.parts = what.containingBlock.parts[0 .. $-1];
}
}
// FIXME: ensure no other carets have a reference to it
}
/// exact = true means return null if no match. otherwise, get the closest one that makes sense for a mouse click.
TextIdentifyResult identify(int x, int y, bool exact = false) {
TextIdentifyResult inexactMatch;
foreach(block; blocks) {
foreach(part; block.parts) {
if(x >= part.boundingBox.left && x < part.boundingBox.right && y >= part.boundingBox.top && y < part.boundingBox.bottom) {
// FIXME binary search
int tidx;
int lastX;
foreach_reverse(idxo, lx; part.letterXs) {
int idx = cast(int) idxo;
if(lx <= x) {
if(lastX && lastX - x < x - lx)
tidx = idx + 1;
else
tidx = idx;
break;
}
lastX = lx;
}
return TextIdentifyResult(part, tidx).fixupNewline;
} else if(!exact) {
// we're not in the box, but are we on the same line?
if(y >= part.boundingBox.top && y < part.boundingBox.bottom)
inexactMatch = TextIdentifyResult(part, x == 0 ? 0 : cast(int) part.text.length);
}
}
}
if(!exact && inexactMatch is TextIdentifyResult.init && blocks.length && blocks[$-1].parts.length)
return TextIdentifyResult(blocks[$-1].parts[$-1], cast(int) blocks[$-1].parts[$-1].text.length).fixupNewline;
return exact ? TextIdentifyResult.init : inexactMatch.fixupNewline;
}
void moveCaretToPixelCoordinates(int x, int y) {
auto result = identify(x, y);
caret.inlineElement = result.element;
caret.offset = result.offset;
}
void selectToPixelCoordinates(int x, int y) {
auto result = identify(x, y);
if(y < caretLastDrawnY1) {
// on a previous line, carat is selectionEnd
selectionEnd = caret;
selectionStart = Caret(this, result.element, result.offset);
} else if(y > caretLastDrawnY2) {
// on a later line
selectionStart = caret;
selectionEnd = Caret(this, result.element, result.offset);
} else {
// on the same line...
if(x <= caretLastDrawnX) {
selectionEnd = caret;
selectionStart = Caret(this, result.element, result.offset);
} else {
selectionStart = caret;
selectionEnd = Caret(this, result.element, result.offset);
}
}
}
/// Call this if the inputs change. It will reflow everything
void redoLayout(ScreenPainter painter) {
//painter.setClipRectangle(boundingBox);
auto pos = Point(boundingBox.left, boundingBox.top);
int lastHeight;
void nl() {
pos.x = boundingBox.left;
pos.y += lastHeight;
}
foreach(block; blocks) {
nl();
foreach(part; block.parts) {
part.letterXs = null;
auto size = painter.textSize(part.text);
version(Windows)
if(part.text.length && part.text[$-1] == '\n')
size.height /= 2; // windows counts the new line at the end, but we don't want that
part.boundingBox = Rectangle(pos.x, pos.y, pos.x + size.width, pos.y + size.height);
foreach(idx, char c; part.text) {
// FIXME: unicode
part.letterXs ~= painter.textSize(part.text[0 .. idx]).width + pos.x;
}
pos.x += size.width;
if(pos.x >= boundingBox.right) {
pos.y += size.height;
pos.x = boundingBox.left;
lastHeight = 0;
} else {
lastHeight = size.height;
}
if(part.text.length && part.text[$-1] == '\n')
nl();
}
}
layoutInvalidated = false;
}
bool layoutInvalidated = true;
void invalidateLayout() {
layoutInvalidated = true;
}
// FIXME: caret can remain sometimes when inserting
// FIXME: inserting at the beginning once you already have something can eff it up.
void drawInto(ScreenPainter painter, bool focused = false) {
if(layoutInvalidated)
redoLayout(painter);
foreach(block; blocks) {
foreach(part; block.parts) {
painter.outlineColor = part.color;
painter.fillColor = part.backgroundColor;
auto pos = part.boundingBox.upperLeft;
auto size = part.boundingBox.size;
painter.drawText(pos, part.text);
if(part.styles & TextFormat.underline)
painter.drawLine(Point(pos.x, pos.y + size.height - 4), Point(pos.x + size.width, pos.y + size.height - 4));
if(part.styles & TextFormat.strikethrough)
painter.drawLine(Point(pos.x, pos.y + size.height/2), Point(pos.x + size.width, pos.y + size.height/2));
}
}
// on every redraw, I will force the caret to be
// redrawn too, in order to eliminate perceived lag
// when moving around with the mouse.
eraseCaret(painter);
if(focused) {
highlightSelection(painter);
drawCaret(painter);
}
}
Color selectionXorColor = Color(255, 255, 127);
void highlightSelection(ScreenPainter painter) {
if(selectionStart is selectionEnd)
return; // no selection
if(selectionStart.inlineElement is null) return;
if(selectionEnd.inlineElement is null) return;
assert(selectionStart.inlineElement !is null);
assert(selectionEnd.inlineElement !is null);
painter.rasterOp = RasterOp.xor;
painter.outlineColor = Color.transparent;
painter.fillColor = selectionXorColor;
auto at = selectionStart.inlineElement;
auto atOffset = selectionStart.offset;
bool done;
while(at) {
auto box = at.boundingBox;
if(atOffset < at.letterXs.length)
box.left = at.letterXs[atOffset];
if(at is selectionEnd.inlineElement) {
if(selectionEnd.offset < at.letterXs.length)
box.right = at.letterXs[selectionEnd.offset];
done = true;
}
painter.drawRectangle(box.upperLeft, box.width, box.height);
if(done)
break;
at = at.getNextInlineElement();
atOffset = 0;
}
}
int caretLastDrawnX, caretLastDrawnY1, caretLastDrawnY2;
bool caretShowingOnScreen = false;
void drawCaret(ScreenPainter painter) {
//painter.setClipRectangle(boundingBox);
int x, y1, y2;
if(caret.inlineElement is null) {
x = boundingBox.left;
y1 = boundingBox.top + 2;
y2 = boundingBox.top + painter.fontHeight;
} else {
x = caret.inlineElement.xOfIndex(caret.offset);
y1 = caret.inlineElement.boundingBox.top + 2;
y2 = caret.inlineElement.boundingBox.bottom - 2;
}
if(caretShowingOnScreen && (x != caretLastDrawnX || y1 != caretLastDrawnY1 || y2 != caretLastDrawnY2))
eraseCaret(painter);
painter.pen = Pen(Color.white, 1);
painter.rasterOp = RasterOp.xor;
painter.drawLine(
Point(x, y1),
Point(x, y2)
);
painter.rasterOp = RasterOp.normal;
caretShowingOnScreen = !caretShowingOnScreen;
if(caretShowingOnScreen) {
caretLastDrawnX = x;
caretLastDrawnY1 = y1;
caretLastDrawnY2 = y2;
}
}
Rectangle caretBoundingBox() {
int x, y1, y2;
if(caret.inlineElement is null) {
x = boundingBox.left;
y1 = boundingBox.top + 2;
y2 = boundingBox.top + 16;
} else {
x = caret.inlineElement.xOfIndex(caret.offset);
y1 = caret.inlineElement.boundingBox.top + 2;
y2 = caret.inlineElement.boundingBox.bottom - 2;
}
return Rectangle(x, y1, x + 1, y2);
}
void eraseCaret(ScreenPainter painter) {
//painter.setClipRectangle(boundingBox);
if(!caretShowingOnScreen) return;
painter.pen = Pen(Color.white, 1);
painter.rasterOp = RasterOp.xor;
painter.drawLine(
Point(caretLastDrawnX, caretLastDrawnY1),
Point(caretLastDrawnX, caretLastDrawnY2)
);
caretShowingOnScreen = false;
painter.rasterOp = RasterOp.normal;
}
/// Caret movement api
/// These should give the user a logical result based on what they see on screen...
/// thus they locate predominately by *pixels* not char index. (These will generally coincide with monospace fonts tho!)
void moveUp() {
if(caret.inlineElement is null) return;
auto x = caret.inlineElement.xOfIndex(caret.offset);
auto y = caret.inlineElement.boundingBox.top + 2;
y -= caret.inlineElement.boundingBox.bottom - caret.inlineElement.boundingBox.top;
if(y < 0)
return;
auto i = identify(x, y);
if(i.element) {
caret.inlineElement = i.element;
caret.offset = i.offset;
}
}
void moveDown() {
if(caret.inlineElement is null) return;
auto x = caret.inlineElement.xOfIndex(caret.offset);
auto y = caret.inlineElement.boundingBox.bottom - 2;
y += caret.inlineElement.boundingBox.bottom - caret.inlineElement.boundingBox.top;
auto i = identify(x, y);
if(i.element) {
caret.inlineElement = i.element;
caret.offset = i.offset;
}
}
void moveLeft() {
if(caret.inlineElement is null) return;
if(caret.offset)
caret.offset--;
else {
auto p = caret.inlineElement.getPreviousInlineElement();
if(p) {
caret.inlineElement = p;
if(p.text.length && p.text[$-1] == '\n')
caret.offset = cast(int) p.text.length - 1;
else
caret.offset = cast(int) p.text.length;
}
}
}
void moveRight() {
if(caret.inlineElement is null) return;
if(caret.offset < caret.inlineElement.text.length && caret.inlineElement.text[caret.offset] != '\n') {
caret.offset++;
} else {
auto p = caret.inlineElement.getNextInlineElement();
if(p) {
caret.inlineElement = p;
caret.offset = 0;
}
}
}
void moveHome() {
if(caret.inlineElement is null) return;
auto x = 0;
auto y = caret.inlineElement.boundingBox.top + 2;
auto i = identify(x, y);
if(i.element) {
caret.inlineElement = i.element;
caret.offset = i.offset;
}
}
void moveEnd() {
if(caret.inlineElement is null) return;
auto x = int.max;
auto y = caret.inlineElement.boundingBox.top + 2;
auto i = identify(x, y);
if(i.element) {
caret.inlineElement = i.element;
caret.offset = i.offset;
}
}
void movePageUp(ref Caret caret) {}
void movePageDown(ref Caret caret) {}
void moveDocumentStart(ref Caret caret) {
if(blocks.length && blocks[0].parts.length)
caret = Caret(this, blocks[0].parts[0], 0);
else
caret = Caret.init;
}
void moveDocumentEnd(ref Caret caret) {
if(blocks.length) {
auto parts = blocks[$-1].parts;
if(parts.length) {
caret = Caret(this, parts[$-1], cast(int) parts[$-1].text.length);
} else {
caret = Caret.init;
}
} else
caret = Caret.init;
}
void deleteSelection() {
if(selectionStart is selectionEnd)
return;
if(selectionStart.inlineElement is null) return;
if(selectionEnd.inlineElement is null) return;
assert(selectionStart.inlineElement !is null);
assert(selectionEnd.inlineElement !is null);
auto at = selectionStart.inlineElement;
if(selectionEnd.inlineElement is at) {
// same element, need to chop out
at.text = at.text[0 .. selectionStart.offset] ~ at.text[selectionEnd.offset .. $];
at.letterXs = at.letterXs[0 .. selectionStart.offset] ~ at.letterXs[selectionEnd.offset .. $];
selectionEnd.offset -= selectionEnd.offset - selectionStart.offset;
} else {
// different elements, we can do it with slicing
at.text = at.text[0 .. selectionStart.offset];
if(selectionStart.offset < at.letterXs.length)
at.letterXs = at.letterXs[0 .. selectionStart.offset];
at = at.getNextInlineElement();
while(at) {
if(at is selectionEnd.inlineElement) {
at.text = at.text[selectionEnd.offset .. $];
if(selectionEnd.offset < at.letterXs.length)
at.letterXs = at.letterXs[selectionEnd.offset .. $];
selectionEnd.offset = 0;
break;
} else {
auto cfd = at;
cfd.text = null; // delete the whole thing
at = at.getNextInlineElement();
if(cfd.text.length == 0) {
// and remove cfd
for(size_t a = 0; a < cfd.containingBlock.parts.length; a++) {
if(cfd.containingBlock.parts[a] is cfd) {
for(size_t i = a; i < cfd.containingBlock.parts.length - 1; i++)
cfd.containingBlock.parts[i] = cfd.containingBlock.parts[i + 1];
cfd.containingBlock.parts = cfd.containingBlock.parts[0 .. $-1];
}
}
}
}
}
}
caret = selectionEnd;
selectNone();
invalidateLayout();
}
/// Plain text editing api. These work at the current caret inside the selected inline element.
void insert(in char[] text) {
foreach(dchar ch; text)
insert(ch);
}
/// ditto
void insert(dchar ch) {
bool selectionDeleted = false;
if(selectionStart !is selectionEnd) {
deleteSelection();
selectionDeleted = true;
}
if(ch == 127) {
delete_();
return;
}
if(ch == 8) {
if(!selectionDeleted)
backspace();
return;
}
invalidateLayout();
if(ch == 13) ch = 10;
auto e = caret.inlineElement;
if(e is null) {
addText("" ~ cast(char) ch) ; // FIXME
return;
}
if(caret.offset == e.text.length) {
e.text ~= cast(char) ch; // FIXME
caret.offset++;
if(ch == 10) {
auto c = caret.inlineElement.clone;
c.text = null;
c.letterXs = null;
insertPartAfter(c,e);
caret = Caret(this, c, 0);
}
} else {
// FIXME cast char sucks
if(ch == 10) {
auto c = caret.inlineElement.clone;
c.text = e.text[caret.offset .. $];
if(caret.offset < c.letterXs.length)
c.letterXs = e.letterXs[caret.offset .. $]; // FIXME boundingBox
e.text = e.text[0 .. caret.offset] ~ cast(char) ch;
if(caret.offset <= e.letterXs.length) {
e.letterXs = e.letterXs[0 .. caret.offset] ~ 0; // FIXME bounding box
}
insertPartAfter(c,e);
caret = Caret(this, c, 0);
} else {
e.text = e.text[0 .. caret.offset] ~ cast(char) ch ~ e.text[caret.offset .. $];
caret.offset++;
}
}
}
void insertPartAfter(InlineElement what, InlineElement where) {
foreach(idx, p; where.containingBlock.parts) {
if(p is where) {
if(idx + 1 == where.containingBlock.parts.length)
where.containingBlock.parts ~= what;
else
where.containingBlock.parts = where.containingBlock.parts[0 .. idx + 1] ~ what ~ where.containingBlock.parts[idx + 1 .. $];
return;
}
}
}
void cleanupStructures() {
for(size_t i = 0; i < blocks.length; i++) {
auto block = blocks[i];
for(size_t a = 0; a < block.parts.length; a++) {
auto part = block.parts[a];
if(part.text.length == 0) {
for(size_t b = a; b < block.parts.length - 1; b++)
block.parts[b] = block.parts[b+1];
block.parts = block.parts[0 .. $-1];
}
}
if(block.parts.length == 0) {
for(size_t a = i; a < blocks.length - 1; a++)
blocks[a] = blocks[a+1];
blocks = blocks[0 .. $-1];
}
}
}
void backspace() {
try_again:
auto e = caret.inlineElement;
if(e is null)
return;
if(caret.offset == 0) {
auto prev = e.getPreviousInlineElement();
if(prev is null)
return;
auto newOffset = cast(int) prev.text.length;
tryMerge(prev, e);
caret.inlineElement = prev;
caret.offset = prev is null ? 0 : newOffset;
goto try_again;
} else if(caret.offset == e.text.length) {
e.text = e.text[0 .. $-1];
caret.offset--;
} else {
e.text = e.text[0 .. caret.offset - 1] ~ e.text[caret.offset .. $];
caret.offset--;
}
//cleanupStructures();
invalidateLayout();
}
void delete_() {
if(selectionStart !is selectionEnd)
deleteSelection();
else {
auto before = caret;
moveRight();
if(caret != before) {
backspace();
}
}
invalidateLayout();
}
void overstrike() {}
/// Selection API. See also: caret movement.
void selectAll() {
moveDocumentStart(selectionStart);
moveDocumentEnd(selectionEnd);
}
bool selectNone() {
if(selectionStart != selectionEnd) {
selectionStart = selectionEnd = Caret.init;
return true;
}
return false;
}
/// Rich text editing api. These allow you to manipulate the meta data of the current element and add new elements.
/// They will modify the current selection if there is one and will splice one in if needed.
void changeAttributes() {}
/// Text search api. They manipulate the selection and/or caret.
void findText(string text) {}
void findIndex(size_t textIndex) {}
// sample event handlers
void handleEvent(KeyEvent event) {
//if(event.type == KeyEvent.Type.KeyPressed) {
//}
}
void handleEvent(dchar ch) {
}
void handleEvent(MouseEvent event) {
}
bool contentEditable; // can it be edited?
bool contentCaretable; // is there a caret/cursor that moves around in there?
bool contentSelectable; // selectable?
Caret caret;
Caret selectionStart;
Caret selectionEnd;
bool insertMode;
}
struct Caret {
TextLayout layout;
InlineElement inlineElement;
int offset;
}
enum TextFormat : ushort {
// decorations
underline = 1,
strikethrough = 2,
// font selectors
bold = 0x4000 | 1, // weight 700
light = 0x4000 | 2, // weight 300
veryBoldOrLight = 0x4000 | 4, // weight 100 with light, weight 900 with bold
// bold | light is really invalid but should give weight 500
// veryBoldOrLight without one of the others should just give the default for the font; it should be ignored.
italic = 0x4000 | 8,
smallcaps = 0x4000 | 16,
}
void* findFont(string family, int weight, TextFormat formats) {
return null;
}
}
/++
$(PITFALL This is not yet stable and may break in future versions without notice.)
History:
Added February 19, 2021
+/
/// Group: drag_and_drop
interface DropHandler {
/++
Called when the drag enters the handler's area.
+/
DragAndDropAction dragEnter(DropPackage*);
/++
Called when the drag leaves the handler's area or is
cancelled. You should free your resources when this is called.
+/
void dragLeave();
/++
Called continually as the drag moves over the handler's area.
Returns: feedback to the dragger
+/
DropParameters dragOver(Point pt);
/++
The user dropped the data and you should process it now. You can
access the data through the given [DropPackage].
+/
void drop(scope DropPackage*);
/++
Called when the drop is complete. You should free whatever temporary
resources you were using. It is often reasonable to simply forward
this call to [dragLeave].
+/
void finish();
/++
Parameters returned by [DropHandler.drop].
+/
static struct DropParameters {
/++
Acceptable action over this area.
+/
DragAndDropAction action;
/++
Rectangle, in client coordinates, where the dragger can expect the same result during this drag session and thus need not ask again.
If you leave this as Rectangle.init, the dragger will continue to ask and this can waste resources.
+/
Rectangle consistentWithin;
}
}
/++
History:
Added February 19, 2021
+/
/// Group: drag_and_drop
enum DragAndDropAction {
none = 0,
copy,
move,
link,
ask,
custom
}
/++
An opaque structure representing dropped data. It contains
private, platform-specific data that your `drop` function
should simply forward.
$(PITFALL This is not yet stable and may break in future versions without notice.)
History:
Added February 19, 2021
+/
/// Group: drag_and_drop
struct DropPackage {
/++
Lists the available formats as magic numbers. You should compare these
against looked-up formats (see [DraggableData.getFormatId]) you know you support and can
understand the passed data.
+/
DraggableData.FormatId[] availableFormats() {
version(X11) {
return xFormats;
} else version(Windows) {
if(pDataObj is null)
return null;
typeof(return) ret;
IEnumFORMATETC ef;
if(pDataObj.EnumFormatEtc(DATADIR.DATADIR_GET, &ef) == S_OK) {
FORMATETC fmt;
ULONG fetched;
while(ef.Next(1, &fmt, &fetched) == S_OK) {
if(fetched == 0)
break;
if(fmt.lindex != -1)
continue;
if(fmt.dwAspect != DVASPECT.DVASPECT_CONTENT)
continue;
if(!(fmt.tymed & TYMED.TYMED_HGLOBAL))
continue;
ret ~= fmt.cfFormat;
}
}
return ret;
}
}
/++
Gets data from the drop and optionally accepts it.
Returns:
void because the data is fed asynchronously through the `dg` parameter.
Params:
acceptedAction = the action to report back to the ender. If it is [DragAndDropAction.none], you are just inspecting the data, but not accepting the drop.
This is useful to tell the sender that you accepted a move, for example, so they can update their data source as well. For other cases, accepting a drop also indicates that any memory associated with the transfer can be freed.
Calling `getData` again after accepting a drop is not permitted.
format = the format you want, from [availableFormats]. Use [DraggableData.getFormatId] to convert from a MIME string or well-known standard format.
dg = delegate to receive the data asynchronously. Please note this delegate may be called immediately, never be called, or be called somewhere in between during event loop processing depending on the platform, requested format, and other conditions beyond your control.
Throws:
if `format` was not compatible with the [availableFormats] or if the drop has already been accepted.
History:
Included in first release of [DropPackage].
+/
void getData(DragAndDropAction acceptedAction, DraggableData.FormatId format, void delegate(scope ubyte[] data) dg) {
version(X11) {
auto display = XDisplayConnection.get();
auto selectionAtom = GetAtom!"XdndSelection"(display);
auto best = format;
static class X11GetSelectionHandler_Drop : X11GetSelectionHandler {
XDisplay* display;
Atom selectionAtom;
DraggableData.FormatId best;
DraggableData.FormatId format;
void delegate(scope ubyte[] data) dg;
DragAndDropAction acceptedAction;
Window sourceWindow;
SimpleWindow win;
this(XDisplay* display, SimpleWindow win, Window sourceWindow, DraggableData.FormatId format, Atom selectionAtom, DraggableData.FormatId best, void delegate(scope ubyte[] data) dg, DragAndDropAction acceptedAction) {
this.display = display;
this.win = win;
this.sourceWindow = sourceWindow;
this.format = format;
this.selectionAtom = selectionAtom;
this.best = best;
this.dg = dg;
this.acceptedAction = acceptedAction;
}
mixin X11GetSelectionHandler_Basics;
void handleData(Atom target, in ubyte[] data) {
//if(target == GetAtom!"UTF8_STRING"(XDisplayConnection.get) || target == XA_STRING || target == GetAtom!"text/plain"(XDisplayConnection.get))
dg(cast(ubyte[]) data);
if(acceptedAction != DragAndDropAction.none) {
auto display = XDisplayConnection.get;
XClientMessageEvent xclient;
xclient.type = EventType.ClientMessage;
xclient.window = sourceWindow;
xclient.message_type = GetAtom!"XdndFinished"(display);
xclient.format = 32;
xclient.data.l[0] = win.impl.window;
xclient.data.l[1] = 1; // drop successful
xclient.data.l[2] = dndActionAtom(display, acceptedAction);
XSendEvent(
display,
sourceWindow,
false,
EventMask.NoEventMask,
cast(XEvent*) &xclient
);
XFlush(display);
}
}
Atom findBestFormat(Atom[] answer) {
Atom best = None;
foreach(option; answer) {
if(option == format) {
best = option;
break;
}
/*
if(option == GetAtom!"UTF8_STRING"(XDisplayConnection.get)) {
best = option;
break;
} else if(option == XA_STRING) {
best = option;
} else if(option == GetAtom!"text/plain"(XDisplayConnection.get)) {
best = option;
}
*/
}
return best;
}
}
win.impl.getSelectionHandlers[selectionAtom] = new X11GetSelectionHandler_Drop(display, win, sourceWindow, format, selectionAtom, best, dg, acceptedAction);
XConvertSelection(display, selectionAtom, best, GetAtom!("SDD_DATA", true)(display), win.impl.window, dataTimestamp);
} else version(Windows) {
// clean up like DragLeave
// pass effect back up
FORMATETC t;
assert(format >= 0 && format <= ushort.max);
t.cfFormat = cast(ushort) format;
t.lindex = -1;
t.dwAspect = DVASPECT.DVASPECT_CONTENT;
t.tymed = TYMED.TYMED_HGLOBAL;
STGMEDIUM m;
if(pDataObj.GetData(&t, &m) != S_OK) {
// fail
} else {
// succeed, take the data and clean up
// FIXME: ensure it is legit HGLOBAL
auto handle = m.hGlobal;
if(handle) {
auto sz = GlobalSize(handle);
if(auto ptr = cast(ubyte*) GlobalLock(handle)) {
scope(exit) GlobalUnlock(handle);
scope(exit) GlobalFree(handle);
auto data = ptr[0 .. sz];
dg(data);
}
}
}
}
}
private:
version(X11) {
SimpleWindow win;
Window sourceWindow;
Time dataTimestamp;
Atom[] xFormats;
}
version(Windows) {
IDataObject pDataObj;
}
}
/++
A generic helper base class for making a drop handler with a preference list of custom types.
This is the base for [TextDropHandler] and [FilesDropHandler] and you can use it for your own
droppers too.
It assumes the whole window it used, but you can subclass to change that.
$(PITFALL This is not yet stable and may break in future versions without notice.)
History:
Added February 19, 2021
+/
/// Group: drag_and_drop
class GenericDropHandlerBase : DropHandler {
// no fancy state here so no need to do anything here
void finish() { }
void dragLeave() { }
private DragAndDropAction acceptedAction;
private DraggableData.FormatId acceptedFormat;
private void delegate(scope ubyte[]) acceptedHandler;
struct FormatHandler {
DraggableData.FormatId format;
void delegate(scope ubyte[]) handler;
}
protected abstract FormatHandler[] formatHandlers();
DragAndDropAction dragEnter(DropPackage* pkg) {
debug(sdpy_dnd) { import std.stdio; foreach(fmt; pkg.availableFormats()) writeln(fmt, " ", DraggableData.getFormatName(fmt)); }
foreach(fmt; formatHandlers())
foreach(f; pkg.availableFormats())
if(f == fmt.format) {
acceptedFormat = f;
acceptedHandler = fmt.handler;
return acceptedAction = DragAndDropAction.copy;
}
return acceptedAction = DragAndDropAction.none;
}
DropParameters dragOver(Point pt) {
return DropParameters(acceptedAction);
}
void drop(scope DropPackage* dropPackage) {
if(!acceptedFormat || acceptedHandler is null) {
debug(sdpy_dnd) { import std.stdio; writeln("drop called w/ handler ", acceptedHandler, " and format ", acceptedFormat); }
return; // prolly shouldn't happen anyway...
}
dropPackage.getData(acceptedAction, acceptedFormat, acceptedHandler);
}
}
/++
A simple handler for making your window accept drops of plain text.
$(PITFALL This is not yet stable and may break in future versions without notice.)
History:
Added February 22, 2021
+/
/// Group: drag_and_drop
class TextDropHandler : GenericDropHandlerBase {
private void delegate(in char[] text) dg;
/++
+/
this(void delegate(in char[] text) dg) {
this.dg = dg;
}
protected override FormatHandler[] formatHandlers() {
version(X11)
return [
FormatHandler(GetAtom!"UTF8_STRING"(XDisplayConnection.get), &translator),
FormatHandler(GetAtom!"text/plain;charset=utf-8"(XDisplayConnection.get), &translator),
];
else version(Windows)
return [
FormatHandler(CF_UNICODETEXT, &translator),
];
}
private void translator(scope ubyte[] data) {
version(X11)
dg(cast(char[]) data);
else version(Windows)
dg(makeUtf8StringFromWindowsString(cast(wchar[]) data));
}
}
/++
A simple handler for making your window accept drops of files, issued to you as file names.
$(PITFALL This is not yet stable and may break in future versions without notice.)
History:
Added February 22, 2021
+/
/// Group: drag_and_drop
class FilesDropHandler : GenericDropHandlerBase {
private void delegate(in char[][]) dg;
/++
+/
this(void delegate(in char[][] fileNames) dg) {
this.dg = dg;
}
protected override FormatHandler[] formatHandlers() {
version(X11)
return [
FormatHandler(GetAtom!"text/uri-list"(XDisplayConnection.get), &translator),
];
else version(Windows)
return [
FormatHandler(CF_HDROP, &translator),
];
}
private void translator(scope ubyte[] data) {
version(X11) {
char[] listString = cast(char[]) data;
char[][16] buffer;
int count;
char[][] result = buffer[];
void commit(char[] s) {
if(count == result.length)
result.length += 16;
if(s.length > 7 && s[0 ..7] == "file://")
s = s[7 .. $]; // FIXME: also may need to trim out the host and do some entity decoding
result[count++] = s;
}
size_t last;
foreach(idx, char c; listString) {
if(c == '\n') {
commit(listString[last .. idx - 1]); // a \r
last = idx + 1; // a \n
}
}
if(last < listString.length) {
commit(listString[last .. $]);
}
// FIXME: they are uris now, should I translate it to local file names?
// of course the host name is supposed to be there cuz of X rokking...
dg(result[0 .. count]);
} else version(Windows) {
static struct DROPFILES {
DWORD pFiles;
POINT pt;
BOOL fNC;
BOOL fWide;
}
const(char)[][16] buffer;
int count;
const(char)[][] result = buffer[];
size_t last;
void commitA(in char[] stuff) {
if(count == result.length)
result.length += 16;
result[count++] = stuff;
}
void commitW(in wchar[] stuff) {
commitA(makeUtf8StringFromWindowsString(stuff));
}
void magic(T)(T chars) {
size_t idx;
while(chars[idx]) {
last = idx;
while(chars[idx]) {
idx++;
}
static if(is(T == char*))
commitA(chars[last .. idx]);
else
commitW(chars[last .. idx]);
idx++;
}
}
auto df = cast(DROPFILES*) data.ptr;
if(df.fWide) {
wchar* chars = cast(wchar*) (data.ptr + df.pFiles);
magic(chars);
} else {
char* chars = cast(char*) (data.ptr + df.pFiles);
magic(chars);
}
dg(result[0 .. count]);
}
}
}
/++
Interface to describe data being dragged. See also [draggable] helper function.
$(PITFALL This is not yet stable and may break in future versions without notice.)
History:
Added February 19, 2021
+/
interface DraggableData {
version(X11)
alias FormatId = Atom;
else
alias FormatId = uint;
/++
Gets the platform-specific FormatId associated with the given named format.
This may be a MIME type, but may also be other various strings defined by the
programs you want to interoperate with.
FIXME: sdpy needs to offer data adapter things that look for compatible formats
and convert it to some particular type for you.
+/
static FormatId getFormatId(string name)() {
version(X11)
return GetAtom!name(XDisplayConnection.get);
else version(Windows) {
static UINT cache;
if(!cache)
cache = RegisterClipboardFormatA(name);
return cache;
} else
throw new NotYetImplementedException();
}
/++
Looks up a string to represent the name for the given format, if there is one.
You should avoid using this function because it is slow. It is provided more for
debugging than for primary use.
+/
static string getFormatName(FormatId format) {
version(X11) {
if(format == 0)
return "None";
else
return getAtomName(format, XDisplayConnection.get);
} else version(Windows) {
switch(format) {
case CF_UNICODETEXT: return "CF_UNICODETEXT";
case CF_DIBV5: return "CF_DIBV5";
case CF_RIFF: return "CF_RIFF";
case CF_WAVE: return "CF_WAVE";
case CF_HDROP: return "CF_HDROP";
default:
char[1024] name;
auto count = GetClipboardFormatNameA(format, name.ptr, name.length);
return name[0 .. count].idup;
}
}
}
FormatId[] availableFormats();
// Return the slice of data you filled, empty slice if done.
// this is to support the incremental thing
ubyte[] getData(FormatId format, return scope ubyte[] data);
size_t dataLength(FormatId format);
}
/++
$(PITFALL This is not yet stable and may break in future versions without notice.)
History:
Added February 19, 2021
+/
DraggableData draggable(string s) {
version(X11)
return new class X11SetSelectionHandler_Text, DraggableData {
this() {
super(s);
}
override FormatId[] availableFormats() {
return X11SetSelectionHandler_Text.availableFormats();
}
override ubyte[] getData(FormatId format, return scope ubyte[] data) {
return X11SetSelectionHandler_Text.getData(format, data);
}
size_t dataLength(FormatId format) {
return s.length;
}
};
version(Windows)
return new class DraggableData {
FormatId[] availableFormats() {
return [CF_UNICODETEXT];
}
ubyte[] getData(FormatId format, return scope ubyte[] data) {
return cast(ubyte[]) makeWindowsString(s, cast(wchar[]) data, WindowsStringConversionFlags.convertNewLines | WindowsStringConversionFlags.zeroTerminate);
}
size_t dataLength(FormatId format) {
return sizeOfConvertedWstring(s, WindowsStringConversionFlags.convertNewLines | WindowsStringConversionFlags.zeroTerminate) * wchar.sizeof;
}
};
}
/++
$(PITFALL This is not yet stable and may break in future versions without notice.)
History:
Added February 19, 2021
+/
/// Group: drag_and_drop
int doDragDrop(SimpleWindow window, DraggableData handler, DragAndDropAction action = DragAndDropAction.copy)
in {
assert(window !is null);
assert(handler !is null);
}
do
{
version(X11) {
auto sh = cast(X11SetSelectionHandler) handler;
if(sh is null) {
// gotta make my own adapter.
sh = new class X11SetSelectionHandler {
mixin X11SetSelectionHandler_Basics;
Atom[] availableFormats() { return handler.availableFormats(); }
ubyte[] getData(Atom format, return scope ubyte[] data) {
return handler.getData(format, data);
}
// since the drop selection is only ever used once it isn't important
// to reset it.
void done() {}
};
}
return doDragDropX11(window, sh, action);
} else version(Windows) {
return doDragDropWindows(window, handler, action);
} else throw new NotYetImplementedException();
}
version(Windows)
private int doDragDropWindows(SimpleWindow window, DraggableData handler, DragAndDropAction action = DragAndDropAction.copy) {
IDataObject obj = new class IDataObject {
ULONG refCount;
ULONG AddRef() {
return ++refCount;
}
ULONG Release() {
return --refCount;
}
HRESULT QueryInterface(const (IID)*riid, LPVOID *ppv) {
if (IID_IUnknown == *riid) {
*ppv = cast(void*) cast(IUnknown) this;
}
else if (IID_IDataObject == *riid) {
*ppv = cast(void*) cast(IDataObject) this;
}
else {
*ppv = null;
return E_NOINTERFACE;
}
AddRef();
return NOERROR;
}
HRESULT DAdvise(FORMATETC* pformatetc, DWORD advf, IAdviseSink pAdvSink, DWORD* pdwConnection) {
// import std.stdio; writeln("Advise");
return E_NOTIMPL;
}
HRESULT DUnadvise(DWORD dwConnection) {
return E_NOTIMPL;
}
HRESULT EnumDAdvise(IEnumSTATDATA* ppenumAdvise) {
// import std.stdio; writeln("EnumDAdvise");
return OLE_E_ADVISENOTSUPPORTED;
}
// tell what formats it supports
FORMATETC[] types;
this() {
FORMATETC t;
foreach(ty; handler.availableFormats()) {
assert(ty <= ushort.max && ty >= 0);
t.cfFormat = cast(ushort) ty;
t.lindex = -1;
t.dwAspect = DVASPECT.DVASPECT_CONTENT;
t.tymed = TYMED.TYMED_HGLOBAL;
}
types ~= t;
}
HRESULT EnumFormatEtc(DWORD dwDirection, IEnumFORMATETC* ppenumFormatEtc) {
if(dwDirection == DATADIR.DATADIR_GET) {
*ppenumFormatEtc = new class IEnumFORMATETC {
ULONG refCount;
ULONG AddRef() {
return ++refCount;
}
ULONG Release() {
return --refCount;
}
HRESULT QueryInterface(const (IID)*riid, LPVOID *ppv) {
if (IID_IUnknown == *riid) {
*ppv = cast(void*) cast(IUnknown) this;
}
else if (IID_IEnumFORMATETC == *riid) {
*ppv = cast(void*) cast(IEnumFORMATETC) this;
}
else {
*ppv = null;
return E_NOINTERFACE;
}
AddRef();
return NOERROR;
}
int pos;
this() {
pos = 0;
}
HRESULT Clone(IEnumFORMATETC* ppenum) {
// import std.stdio; writeln("clone");
return E_NOTIMPL; // FIXME
}
// Caller is responsible for freeing memory
HRESULT Next(ULONG celt, FORMATETC* rgelt, ULONG* pceltFetched) {
// fetched may be null if celt is one
if(celt != 1)
return E_NOTIMPL; // FIXME
if(celt + pos > types.length)
return S_FALSE;
*rgelt = types[pos++];
if(pceltFetched !is null)
*pceltFetched = 1;
// import std.stdio; writeln("ok celt ", celt);
return S_OK;
}
HRESULT Reset() {
pos = 0;
return S_OK;
}
HRESULT Skip(ULONG celt) {
if(celt + pos <= types.length) {
pos += celt;
return S_OK;
}
return S_FALSE;
}
};
return S_OK;
} else
return E_NOTIMPL;
}
// given a format, return the format you'd prefer to use cuz it is identical
HRESULT GetCanonicalFormatEtc(FORMATETC* pformatectIn, FORMATETC* pformatetcOut) {
// FIXME: prolly could be better but meh
// import std.stdio; writeln("gcf: ", *pformatectIn);
*pformatetcOut = *pformatectIn;
return S_OK;
}
HRESULT GetData(FORMATETC* pformatetcIn, STGMEDIUM* pmedium) {
foreach(ty; types) {
if(ty == *pformatetcIn) {
auto format = ty.cfFormat;
// import std.stdio; writeln("A: ", *pformatetcIn, "\nB: ", ty);
STGMEDIUM medium;
medium.tymed = TYMED.TYMED_HGLOBAL;
auto sz = handler.dataLength(format);
auto handle = GlobalAlloc(GMEM_MOVEABLE, sz);
if(handle is null) throw new Exception("GlobalAlloc");
if(auto data = cast(wchar*) GlobalLock(handle)) {
auto slice = data[0 .. sz];
scope(exit)
GlobalUnlock(handle);
handler.getData(format, cast(ubyte[]) slice[]);
}
medium.hGlobal = handle; // FIXME
*pmedium = medium;
return S_OK;
}
}
return DV_E_FORMATETC;
}
HRESULT GetDataHere(FORMATETC* pformatetcIn, STGMEDIUM* pmedium) {
// import std.stdio; writeln("GDH: ", *pformatetcIn);
return E_NOTIMPL; // FIXME
}
HRESULT QueryGetData(FORMATETC* pformatetc) {
auto search = *pformatetc;
search.tymed &= TYMED.TYMED_HGLOBAL;
foreach(ty; types)
if(ty == search) {
// import std.stdio; writeln("QueryGetData ", search, " ", types[0]);
return S_OK;
}
if(pformatetc.cfFormat==CF_UNICODETEXT) {
//import std.stdio; writeln("QueryGetData FALSE ", search, " ", types[0]);
}
return S_FALSE;
}
HRESULT SetData(FORMATETC* pformatetc, STGMEDIUM* pmedium, BOOL fRelease) {
// import std.stdio; writeln("SetData: ");
return E_NOTIMPL;
}
};
IDropSource src = new class IDropSource {
ULONG refCount;
ULONG AddRef() {
return ++refCount;
}
ULONG Release() {
return --refCount;
}
HRESULT QueryInterface(const (IID)*riid, LPVOID *ppv) {
if (IID_IUnknown == *riid) {
*ppv = cast(void*) cast(IUnknown) this;
}
else if (IID_IDropSource == *riid) {
*ppv = cast(void*) cast(IDropSource) this;
}
else {
*ppv = null;
return E_NOINTERFACE;
}
AddRef();
return NOERROR;
}
int QueryContinueDrag(int fEscapePressed, uint grfKeyState) {
if(fEscapePressed)
return DRAGDROP_S_CANCEL;
if(!(grfKeyState & MK_LBUTTON))
return DRAGDROP_S_DROP;
return S_OK;
}
int GiveFeedback(uint dwEffect) {
return DRAGDROP_S_USEDEFAULTCURSORS;
}
};
DWORD effect;
if(action == DragAndDropAction.none) assert(0, "Don't drag something with a none effect.");
DROPEFFECT de = win32DragAndDropAction(action);
// I'm not as concerned about the GC here since DoDragDrop blocks so the stack frame still sane the whole time
// but still prolly a FIXME
auto ret = DoDragDrop(obj, src, de, &effect);
/+
import std.stdio;
if(ret == DRAGDROP_S_DROP)
writeln("drop ", effect);
else if(ret == DRAGDROP_S_CANCEL)
writeln("cancel");
else if(ret == S_OK)
writeln("ok");
else writeln(ret);
+/
return ret;
}
version(Windows)
DROPEFFECT win32DragAndDropAction(DragAndDropAction action) {
DROPEFFECT de;
with(DragAndDropAction)
with(DROPEFFECT)
final switch(action) {
case none: de = DROPEFFECT_NONE; break;
case copy: de = DROPEFFECT_COPY; break;
case move: de = DROPEFFECT_MOVE; break;
case link: de = DROPEFFECT_LINK; break;
case ask: throw new Exception("ask not implemented yet");
case custom: throw new Exception("custom not implemented yet");
}
return de;
}
/++
History:
Added February 19, 2021
+/
/// Group: drag_and_drop
void enableDragAndDrop(SimpleWindow window, DropHandler handler) {
version(X11) {
auto display = XDisplayConnection.get;
Atom atom = 5; // right???
XChangeProperty(
display,
window.impl.window,
GetAtom!"XdndAware"(display),
XA_ATOM,
32 /* bits */,
PropModeReplace,
&atom,
1);
window.dropHandler = handler;
} else version(Windows) {
initDnd();
auto dropTarget = new class (handler) IDropTarget {
DropHandler handler;
this(DropHandler handler) {
this.handler = handler;
}
ULONG refCount;
ULONG AddRef() {
return ++refCount;
}
ULONG Release() {
return --refCount;
}
HRESULT QueryInterface(const (IID)*riid, LPVOID *ppv) {
if (IID_IUnknown == *riid) {
*ppv = cast(void*) cast(IUnknown) this;
}
else if (IID_IDropTarget == *riid) {
*ppv = cast(void*) cast(IDropTarget) this;
}
else {
*ppv = null;
return E_NOINTERFACE;
}
AddRef();
return NOERROR;
}
// ///////////////////
HRESULT DragEnter(IDataObject pDataObj, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect) {
DropPackage dropPackage = DropPackage(pDataObj);
*pdwEffect = win32DragAndDropAction(handler.dragEnter(&dropPackage));
return S_OK; // https://docs.microsoft.com/en-us/windows/win32/api/oleidl/nf-oleidl-idroptarget-dragenter
}
HRESULT DragLeave() {
handler.dragLeave();
// release the IDataObject if needed
return S_OK;
}
HRESULT DragOver(DWORD grfKeyState, POINTL pt, DWORD* pdwEffect) {
auto res = handler.dragOver(Point(pt.x, pt.y)); // FIXME: translate screen coordinates back to window coordinates
*pdwEffect = win32DragAndDropAction(res.action);
// same as DragEnter basically
return S_OK;
}
HRESULT Drop(IDataObject pDataObj, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect) {
DropPackage pkg = DropPackage(pDataObj);
handler.drop(&pkg);
return S_OK;
}
};
// Windows can hold on to the handler and try to call it
// during which time the GC can't see it. so important to
// manually manage this. At some point i'll FIXME and make
// all my com instances manually managed since they supposed
// to respect the refcount.
import core.memory;
GC.addRoot(cast(void*) dropTarget);
if(RegisterDragDrop(window.impl.hwnd, dropTarget) != S_OK)
throw new Exception("register");
window.dropHandler = handler;
} else throw new NotYetImplementedException();
}
static if(UsingSimpledisplayX11) {
enum _NET_WM_STATE_ADD = 1;
enum _NET_WM_STATE_REMOVE = 0;
enum _NET_WM_STATE_TOGGLE = 2;
/// X-specific. Use [SimpleWindow.requestAttention] instead for most cases.
void demandAttention(SimpleWindow window, bool needs = true) {
demandAttention(window.impl.window, needs);
}
/// ditto
void demandAttention(Window window, bool needs = true) {
setNetWmStateAtom(window, GetAtom!("_NET_WM_STATE_DEMANDS_ATTENTION", false)(XDisplayConnection.get), needs);
}
void setNetWmStateAtom(Window window, Atom atom, bool set = true, Atom atom2 = None) {
auto display = XDisplayConnection.get();
if(atom == None)
return; // non-failure error
//auto atom2 = GetAtom!"_NET_WM_STATE_SHADED"(display);
XClientMessageEvent xclient;
xclient.type = EventType.ClientMessage;
xclient.window = window;
xclient.message_type = GetAtom!"_NET_WM_STATE"(display);
xclient.format = 32;
xclient.data.l[0] = set ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
xclient.data.l[1] = atom;
xclient.data.l[2] = atom2;
xclient.data.l[3] = 1;
// [3] == source. 0 == unknown, 1 == app, 2 == else
XSendEvent(
display,
RootWindow(display, DefaultScreen(display)),
false,
EventMask.SubstructureRedirectMask | EventMask.SubstructureNotifyMask,
cast(XEvent*) &xclient
);
/+
XChangeProperty(
display,
window.impl.window,
GetAtom!"_NET_WM_STATE"(display),
XA_ATOM,
32 /* bits */,
PropModeAppend,
&atom,
1);
+/
}
private Atom dndActionAtom(Display* display, DragAndDropAction action) {
Atom actionAtom;
with(DragAndDropAction)
final switch(action) {
case none: actionAtom = None; break;
case copy: actionAtom = GetAtom!"XdndActionCopy"(display); break;
case move: actionAtom = GetAtom!"XdndActionMove"(display); break;
case link: actionAtom = GetAtom!"XdndActionLink"(display); break;
case ask: actionAtom = GetAtom!"XdndActionAsk"(display); break;
case custom: actionAtom = GetAtom!"XdndActionCustom"(display); break;
}
return actionAtom;
}
private int doDragDropX11(SimpleWindow window, X11SetSelectionHandler handler, DragAndDropAction action) {
// FIXME: I need to show user feedback somehow.
auto display = XDisplayConnection.get;
auto actionAtom = dndActionAtom(display, action);
assert(actionAtom, "Don't use action none to accept a drop");
setX11Selection!"XdndSelection"(window, handler, null);
auto oldKeyHandler = window.handleKeyEvent;
scope(exit) window.handleKeyEvent = oldKeyHandler;
auto oldCharHandler = window.handleCharEvent;
scope(exit) window.handleCharEvent = oldCharHandler;
auto oldMouseHandler = window.handleMouseEvent;
scope(exit) window.handleMouseEvent = oldMouseHandler;
Window[Window] eligibility; // 0 == not eligible, otherwise it is the window id of an eligible child
import core.sys.posix.sys.time;
timeval tv;
gettimeofday(&tv, null);
Time dataTimestamp = tv.tv_sec * 1000 + tv.tv_usec / 1000;
Time lastMouseTimestamp;
bool dnding = true;
Window lastIn = None;
void leave() {
if(lastIn == None)
return;
XEvent ev;
ev.xclient.type = EventType.ClientMessage;
ev.xclient.window = lastIn;
ev.xclient.message_type = GetAtom!("XdndLeave", true)(display);
ev.xclient.format = 32;
ev.xclient.data.l[0] = window.impl.window;
XSendEvent(XDisplayConnection.get, lastIn, false, EventMask.NoEventMask, &ev);
XFlush(display);
lastIn = None;
}
void enter(Window w) {
assert(lastIn == None);
lastIn = w;
XEvent ev;
ev.xclient.type = EventType.ClientMessage;
ev.xclient.window = lastIn;
ev.xclient.message_type = GetAtom!("XdndEnter", true)(display);
ev.xclient.format = 32;
ev.xclient.data.l[0] = window.impl.window;
ev.xclient.data.l[1] = (5 << 24) | 0; // version 5, no more sources. FIXME source types
auto types = handler.availableFormats();
assert(types.length > 0);
ev.xclient.data.l[2] = types[0];
if(types.length > 1)
ev.xclient.data.l[3] = types[1];
if(types.length > 2)
ev.xclient.data.l[4] = types[2];
// FIXME: other types?!?!? and make sure we skip TARGETS
XSendEvent(XDisplayConnection.get, lastIn, false, EventMask.NoEventMask, &ev);
XFlush(display);
}
void position(int rootX, int rootY) {
assert(lastIn != None);
XEvent ev;
ev.xclient.type = EventType.ClientMessage;
ev.xclient.window = lastIn;
ev.xclient.message_type = GetAtom!("XdndPosition", true)(display);
ev.xclient.format = 32;
ev.xclient.data.l[0] = window.impl.window;
ev.xclient.data.l[1] = 0; // reserved
ev.xclient.data.l[2] = (rootX << 16) | rootY;
ev.xclient.data.l[3] = dataTimestamp;
ev.xclient.data.l[4] = actionAtom;
XSendEvent(XDisplayConnection.get, lastIn, false, EventMask.NoEventMask, &ev);
XFlush(display);
}
void drop() {
XEvent ev;
ev.xclient.type = EventType.ClientMessage;
ev.xclient.window = lastIn;
ev.xclient.message_type = GetAtom!("XdndDrop", true)(display);
ev.xclient.format = 32;
ev.xclient.data.l[0] = window.impl.window;
ev.xclient.data.l[1] = 0; // reserved
ev.xclient.data.l[2] = dataTimestamp;
XSendEvent(XDisplayConnection.get, lastIn, false, EventMask.NoEventMask, &ev);
XFlush(display);
lastIn = None;
dnding = false;
}
// fyi nativeEventHandler can return 0 if it handles it, or otherwise it goes back to the normal handler
// but idk if i should...
window.setEventHandlers(
delegate(KeyEvent ev) {
if(ev.pressed == true && ev.key == Key.Escape) {
// cancel
dnding = false;
}
},
delegate(MouseEvent ev) {
if(ev.timestamp < lastMouseTimestamp)
return;
lastMouseTimestamp = ev.timestamp;
if(ev.type == MouseEventType.motion) {
auto display = XDisplayConnection.get;
auto root = RootWindow(display, DefaultScreen(display));
Window topWindow;
int rootX, rootY;
XTranslateCoordinates(display, window.impl.window, root, ev.x, ev.y, &rootX, &rootY, &topWindow);
if(topWindow == None)
return;
top:
if(auto result = topWindow in eligibility) {
auto dropWindow = *result;
if(dropWindow == None) {
leave();
return;
}
if(dropWindow != lastIn) {
leave();
enter(dropWindow);
position(rootX, rootY);
} else {
position(rootX, rootY);
}
} else {
// determine eligibility
auto data = cast(Atom[]) getX11PropertyData(topWindow, GetAtom!"XdndAware"(display), XA_ATOM);
if(data.length == 1) {
// in case there is no WM or it isn't reparenting
eligibility[topWindow] = (data[0] == 5) ? topWindow : None; // FIXME I'm supposed to handle older versions too but meh
} else {
Window tryScanChildren(Window search, int maxRecurse) {
// could be reparenting window manager, so gotta check the next few children too
Window child;
int x;
int y;
XTranslateCoordinates(display, window.impl.window, search, ev.x, ev.y, &x, &y, &child);
if(child == None)
return None;
auto data = cast(Atom[]) getX11PropertyData(child, GetAtom!"XdndAware"(display), XA_ATOM);
if(data.length == 1) {
return (data[0] == 5) ? child : None; // FIXME I'm supposed to handle older versions too but meh
} else {
if(maxRecurse)
return tryScanChildren(child, maxRecurse - 1);
else
return None;
}
}
// if a WM puts more than 3 layers on it, like wtf is it doing, screw that.
auto topResult = tryScanChildren(topWindow, 3);
// it is easy to have a false negative due to the mouse going over a WM
// child window like the close button if separate from the frame... so I
// can't really cache negatives, :(
if(topResult != None) {
eligibility[topWindow] = topResult;
goto top; // reload to do the positioning iff eligibility changed lest we endless loop
}
}
}
} else if(ev.type == MouseEventType.buttonReleased) {
drop();
dnding = false;
}
}
);
window.grabInput();
scope(exit)
window.releaseInputGrab();
EventLoop.get.run(() => dnding);
return 0;
}
/// X-specific
TrueColorImage getWindowNetWmIcon(Window window) {
try {
auto display = XDisplayConnection.get;
auto data = getX11PropertyData (window, GetAtom!"_NET_WM_ICON"(display), XA_CARDINAL);
if (data.length > arch_ulong.sizeof * 2) {
auto meta = cast(arch_ulong[]) (data[0 .. arch_ulong.sizeof * 2]);
// these are an array of rgba images that we have to convert into pixmaps ourself
int width = cast(int) meta[0];
int height = cast(int) meta[1];
auto bytes = cast(ubyte[]) (data[arch_ulong.sizeof * 2 .. $]);
static if(arch_ulong.sizeof == 4) {
bytes = bytes[0 .. width * height * 4];
alias imageData = bytes;
} else static if(arch_ulong.sizeof == 8) {
bytes = bytes[0 .. width * height * 8];
auto imageData = new ubyte[](4 * width * height);
} else static assert(0);
// this returns ARGB. Remember it is little-endian so
// we have BGRA
// our thing uses RGBA, which in little endian, is ABGR
for(int idx = 0, idx2 = 0; idx < bytes.length; idx += arch_ulong.sizeof, idx2 += 4) {
auto r = bytes[idx + 2];
auto g = bytes[idx + 1];
auto b = bytes[idx + 0];
auto a = bytes[idx + 3];
imageData[idx2 + 0] = r;
imageData[idx2 + 1] = g;
imageData[idx2 + 2] = b;
imageData[idx2 + 3] = a;
}
return new TrueColorImage(width, height, imageData);
}
return null;
} catch(Exception e) {
return null;
}
}
} /* UsingSimpledisplayX11 */
void loadBinNameToWindowClassName () {
import core.stdc.stdlib : realloc;
version(linux) {
// args[0] MAY be empty, so we'll just use this
import core.sys.posix.unistd : readlink;
char[1024] ebuf = void; // 1KB should be enough for everyone!
auto len = readlink("/proc/self/exe", ebuf.ptr, ebuf.length);
if (len < 1) return;
} else /*version(Windows)*/ {
import core.runtime : Runtime;
if (Runtime.args.length == 0 || Runtime.args[0].length == 0) return;
auto ebuf = Runtime.args[0];
auto len = ebuf.length;
}
auto pos = len;
while (pos > 0 && ebuf[pos-1] != '/') --pos;
sdpyWindowClassStr = cast(char*)realloc(sdpyWindowClassStr, len-pos+1);
if (sdpyWindowClassStr is null) return; // oops
sdpyWindowClassStr[0..len-pos+1] = 0; // just in case
sdpyWindowClassStr[0..len-pos] = ebuf[pos..len];
}
/++
An interface representing a font that is drawn with custom facilities.
You might want [OperatingSystemFont] instead, which represents
a font loaded and drawn by functions native to the operating system.
WARNING: I might still change this.
+/
interface DrawableFont : MeasurableFont {
/++
Please note the point is upperLeft, NOT baseline! This is the point of a bounding box of the string.
Implementations must use the painter's fillColor to draw a rectangle behind the string,
then use the outlineColor to draw the string. It might alpha composite if there's a transparent
fill color, but that's up to the implementation.
+/
void drawString(ScreenPainter painter, Point upperLeft, in char[] text);
/++
Requests that the given string is added to the image cache. You should only do this rarely, but
if you have a string that you know will be used over and over again, adding it to a cache can
improve things (assuming the implementation actually has a cache; it is also valid for an implementation
to implement this as a do-nothing method).
+/
void cacheString(SimpleWindow window, Color foreground, Color background, string text);
}
/++
Loads a true type font using [arsd.ttf] that can be drawn as images on windows
through a [ScreenPainter]. That module must be compiled in if you choose to use this function.
You should also consider [OperatingSystemFont], which loads and draws a font with
facilities native to the user's operating system. You might also consider
[arsd.ttf.OpenGlLimitedFont] or using [arsd.nanovega] if you are making some kind
of game, as they have their own ways to draw text too.
Be warned: this can be slow, especially on remote connections to the X server, since
it needs to create and transfer bitmaps instead of just text. The [DrawableFont] interface
offers [DrawableFont.cacheString] which can help with this, sometimes. You might want to
experiment in your specific case.
Please note that the return type of [DrawableFont] also includes an implementation of
[MeasurableFont].
+/
DrawableFont arsdTtfFont()(in ubyte[] data, int size) {
import arsd.ttf;
static class ArsdTtfFont : DrawableFont {
TtfFont font;
int size;
this(in ubyte[] data, int size) {
font = TtfFont(data);
this.size = size;
auto scale = stbtt_ScaleForPixelHeight(&font.font, size);
int ascent_, descent_, line_gap;
stbtt_GetFontVMetrics(&font.font, &ascent_, &descent_, &line_gap);
int advance, lsb;
stbtt_GetCodepointHMetrics(&font.font, 'x', &advance, &lsb);
xWidth = cast(int) (advance * scale);
stbtt_GetCodepointHMetrics(&font.font, 'M', &advance, &lsb);
MWidth = cast(int) (advance * scale);
}
private int ascent_;
private int descent_;
private int xWidth;
private int MWidth;
bool isMonospace() {
return xWidth == MWidth;
}
int averageWidth() {
return xWidth;
}
int height() {
return size;
}
int ascent() {
return ascent_;
}
int descent() {
return descent_;
}
int stringWidth(scope const(char)[] s, SimpleWindow window = null) {
int width, height;
font.getStringSize(s, size, width, height);
return width;
}
Sprite[string] cache;
void cacheString(SimpleWindow window, Color foreground, Color background, string text) {
auto sprite = new Sprite(window, stringToImage(foreground, background, text));
cache[text] = sprite;
}
Image stringToImage(Color fg, Color bg, in char[] text) {
int width, height;
auto data = font.renderString(text, size, width, height);
auto image = new TrueColorImage(width, height);
int pos = 0;
foreach(y; 0 .. height)
foreach(x; 0 .. width) {
fg.a = data[0];
bg.a = 255;
auto color = alphaBlend(fg, bg);
image.imageData.bytes[pos++] = color.r;
image.imageData.bytes[pos++] = color.g;
image.imageData.bytes[pos++] = color.b;
image.imageData.bytes[pos++] = data[0];
data = data[1 .. $];
}
assert(data.length == 0);
return Image.fromMemoryImage(image);
}
void drawString(ScreenPainter painter, Point upperLeft, in char[] text) {
Sprite sprite = (text in cache) ? *(text in cache) : null;
auto fg = painter.impl._outlineColor;
auto bg = painter.impl._fillColor;
if(sprite !is null) {
auto w = cast(SimpleWindow) painter.window;
assert(w !is null);
sprite.drawAt(painter, upperLeft);
} else {
painter.drawImage(upperLeft, stringToImage(fg, bg, text));
}
}
}
return new ArsdTtfFont(data, size);
}
class NotYetImplementedException : Exception {
this(string file = __FILE__, size_t line = __LINE__) {
super("Not yet implemented", file, line);
}
}
///
__gshared bool librariesSuccessfullyLoaded = true;
///
__gshared bool openGlLibrariesSuccessfullyLoaded = true;
private mixin template DynamicLoadSupplementalOpenGL(Iface) {
mixin(staticForeachReplacement!Iface);
void loadDynamicLibrary() @nogc {
(cast(void function() @nogc) &loadDynamicLibraryForReal)();
}
void loadDynamicLibraryForReal() {
foreach(name; __traits(derivedMembers, Iface)) {
mixin("alias tmp = " ~ name ~ ";");
tmp = cast(typeof(tmp)) glbindGetProcAddress(name);
if(tmp is null) throw new Exception("load failure of function " ~ name ~ " from supplemental OpenGL");
}
}
}
private const(char)[] staticForeachReplacement(Iface)() pure {
/*
// just this for gdc 9....
// when i drop support for it and switch to gdc10, we can put this original back for a slight compile time ram decrease
static foreach(name; __traits(derivedMembers, Iface))
mixin("__gshared typeof(&__traits(getMember, Iface, name)) " ~ name ~ ";");
*/
char[] code = new char[](__traits(derivedMembers, Iface).length * 64);
size_t pos;
void append(in char[] what) {
if(pos + what.length > code.length)
code.length = (code.length * 3) / 2;
code[pos .. pos + what.length] = what[];
pos += what.length;
}
foreach(name; __traits(derivedMembers, Iface)) {
append(`__gshared typeof(&__traits(getMember, Iface, "`);
append(name);
append(`")) `);
append(name);
append(";");
}
return code[0 .. pos];
}
private mixin template DynamicLoad(Iface, string library, int majorVersion, alias success) {
mixin(staticForeachReplacement!Iface);
private __gshared void* libHandle;
private __gshared bool attempted;
void loadDynamicLibrary() @nogc {
(cast(void function() @nogc) &loadDynamicLibraryForReal)();
}
bool loadAttempted() {
return attempted;
}
bool loadSuccessful() {
return libHandle !is null;
}
void loadDynamicLibraryForReal() {
attempted = true;
version(Posix) {
import core.sys.posix.dlfcn;
version(OSX) {
version(X11)
libHandle = dlopen("/usr/X11/lib/lib" ~ library ~ ".dylib", RTLD_NOW);
else
libHandle = dlopen(library ~ ".dylib", RTLD_NOW);
} else {
libHandle = dlopen("lib" ~ library ~ ".so", RTLD_NOW);
if(libHandle is null)
libHandle = dlopen(("lib" ~ library ~ ".so." ~ toInternal!string(majorVersion) ~ "\0").ptr, RTLD_NOW);
}
static void* loadsym(void* l, const char* name) {
import core.stdc.stdlib;
if(l is null)
return &abort;
return dlsym(l, name);
}
} else version(Windows) {
import core.sys.windows.winbase;
libHandle = LoadLibrary(library ~ ".dll");
static void* loadsym(void* l, const char* name) {
import core.stdc.stdlib;
if(l is null)
return &abort;
return GetProcAddress(l, name);
}
}
if(libHandle is null) {
success = false;
//throw new Exception("load failure of library " ~ library);
}
foreach(name; __traits(derivedMembers, Iface)) {
mixin("alias tmp = " ~ name ~ ";");
tmp = cast(typeof(tmp)) loadsym(libHandle, name);
if(tmp is null) throw new Exception("load failure of function " ~ name ~ " from " ~ library);
}
}
void unloadDynamicLibrary() {
version(Posix) {
import core.sys.posix.dlfcn;
dlclose(libHandle);
} else version(Windows) {
import core.sys.windows.winbase;
FreeLibrary(libHandle);
}
foreach(name; __traits(derivedMembers, Iface))
mixin(name ~ " = null;");
}
}
/+
The GC can be called from any thread, and a lot of cleanup must be done
on the gui thread. Since the GC can interrupt any locks - including being
triggered inside a critical section - it is vital to avoid deadlocks to get
these functions called from the right place.
If the buffer overflows, things are going to get leaked. I'm kinda ok with that
right now.
The cleanup function is run when the event loop gets around to it, which is just
whenever there's something there after it has been woken up for other work. It does
NOT wake up the loop itself - can't risk doing that from inside the GC in another thread.
(Well actually it might be ok but i don't wanna mess with it right now.)
+/
private struct CleanupQueue {
import core.stdc.stdlib;
void queue(alias func, T...)(T args) {
static struct Args {
T args;
}
static struct RealJob {
Job j;
Args a;
}
static void call(Job* data) {
auto rj = cast(RealJob*) data;
func(rj.a.args);
}
RealJob* thing = cast(RealJob*) malloc(RealJob.sizeof);
thing.j.call = &call;
thing.a.args = args;
buffer[tail++] = cast(Job*) thing;
// FIXME: set overflowed
}
void process() {
const tail = this.tail;
while(tail != head) {
Job* job = cast(Job*) buffer[head++];
job.call(job);
free(job);
}
if(overflowed)
throw new Exception("cleanup overflowed");
}
private:
ubyte tail; // must ONLY be written by queue
ubyte head; // must ONLY be written by process
bool overflowed;
static struct Job {
void function(Job*) call;
}
void*[256] buffer;
}
private __gshared CleanupQueue cleanupQueue;
version(X11)
/++
Returns the custom scaling factor read out of environment["ARSD_SCALING_FACTOR"].
$(WARNING
This function is exempted from stability guarantees.
)
+/
float customScalingFactorForMonitor(int monitorNumber) {
import core.stdc.stdlib;
auto val = getenv("ARSD_SCALING_FACTOR");
if(val is null)
return 1.0;
char[16] buffer = 0;
int pos;
const(char)* at = val;
foreach(item; 0 .. monitorNumber + 1) {
if(*at == 0)
break; // reuse the last number when we at the end of the string
pos = 0;
while(pos + 1 < buffer.length && *at && *at != ';') {
buffer[pos++] = *at;
at++;
}
if(*at)
at++; // skip the semicolon
buffer[pos] = 0;
}
//sdpyPrintDebugString(buffer[0 .. pos]);
import core.stdc.math;
auto f = atof(buffer.ptr);
if(f <= 0.0 || isnan(f) || isinf(f))
return 1.0;
return f;
}
void guiAbortProcess(string msg) {
import core.stdc.stdlib;
version(Windows) {
WCharzBuffer t = WCharzBuffer(msg);
MessageBoxW(null, t.ptr, "Program Termination"w.ptr, 0);
} else {
import core.stdc.stdio;
fwrite(msg.ptr, 1, msg.length, stderr);
msg = "\n";
fwrite(msg.ptr, 1, msg.length, stderr);
fflush(stderr);
}
abort();
}
private int minInternal(int a, int b) {
return (a < b) ? a : b;
}
private alias scriptable = arsd_jsvar_compatible;
|
D
|
module org.serviio.ui.resources.ApplicationResource;
import org.restlet.resource.Get;
import org.serviio.ui.representation.ApplicationRepresentation;
public abstract interface ApplicationResource
{
//@Get("xml|json")
public abstract ApplicationRepresentation load();
}
/* Location: D:\Program Files\Serviio\lib\serviio.jar
* Qualified Name: org.serviio.ui.resources.ApplicationResource
* JD-Core Version: 0.6.2
*/
|
D
|
module hunt.http.codec.http.hpack.HpackContext;
// import hunt.http.codec.http.model;
import hunt.http.HttpField;
import hunt.http.HttpHeader;
import hunt.http.HttpMethod;
import hunt.http.codec.http.model.StaticTableHttpField;
import hunt.http.codec.http.hpack.Huffman;
import hunt.http.codec.http.hpack.NBitInteger;
import hunt.Exceptions;
import hunt.text.Common;
import hunt.collection;
import hunt.logging;
import std.array;
import std.conv;
import std.uni;
import std.format;
/**
* HPACK - Header Compression for HTTP/2
* <p>
* This class maintains the compression context for a single HTTP/2 connection.
* Specifically it holds the static and dynamic Header Field Tables and the
* associated sizes and limits.
* </p>
* <p>
* It is compliant with draft 11 of the specification
* </p>
*/
class HpackContext {
private enum string EMPTY = "";
enum string[][] STATIC_TABLE =
[
[null, null],
/* 1 */ [":authority", EMPTY],
/* 2 */ [":method", "GET"],
/* 3 */ [":method", "POST"],
/* 4 */ [":path", "/"],
/* 5 */ [":path", "/index.html"],
/* 6 */ [":scheme", "http"],
/* 7 */ [":scheme", "https"],
/* 8 */ [":status", "200"],
/* 9 */ [":status", "204"],
/* 10 */ [":status", "206"],
/* 11 */ [":status", "304"],
/* 12 */ [":status", "400"],
/* 13 */ [":status", "404"],
/* 14 */ [":status", "500"],
/* 15 */ ["accept-charset", EMPTY],
/* 16 */ ["accept-encoding", "gzip, deflate"],
/* 17 */ ["accept-language", EMPTY],
/* 18 */ ["accept-ranges", EMPTY],
/* 19 */ ["accept", EMPTY],
/* 20 */ ["access-control-allow-origin", EMPTY],
/* 21 */ ["age", EMPTY],
/* 22 */ ["allow", EMPTY],
/* 23 */ ["authorization", EMPTY],
/* 24 */ ["cache-control", EMPTY],
/* 25 */ ["content-disposition", EMPTY],
/* 26 */ ["content-encoding", EMPTY],
/* 27 */ ["content-language", EMPTY],
/* 28 */ ["content-length", EMPTY],
/* 29 */ ["content-location", EMPTY],
/* 30 */ ["content-range", EMPTY],
/* 31 */ ["content-type", EMPTY],
/* 32 */ ["cookie", EMPTY],
/* 33 */ ["date", EMPTY],
/* 34 */ ["etag", EMPTY],
/* 35 */ ["expect", EMPTY],
/* 36 */ ["expires", EMPTY],
/* 37 */ ["from", EMPTY],
/* 38 */ ["host", EMPTY],
/* 39 */ ["if-match", EMPTY],
/* 40 */ ["if-modified-since", EMPTY],
/* 41 */ ["if-none-match", EMPTY],
/* 42 */ ["if-range", EMPTY],
/* 43 */ ["if-unmodified-since", EMPTY],
/* 44 */ ["last-modified", EMPTY],
/* 45 */ ["link", EMPTY],
/* 46 */ ["location", EMPTY],
/* 47 */ ["max-forwards", EMPTY],
/* 48 */ ["proxy-authenticate", EMPTY],
/* 49 */ ["proxy-authorization", EMPTY],
/* 50 */ ["range", EMPTY],
/* 51 */ ["referer", EMPTY],
/* 52 */ ["refresh", EMPTY],
/* 53 */ ["retry-after", EMPTY],
/* 54 */ ["server", EMPTY],
/* 55 */ ["set-cookie", EMPTY],
/* 56 */ ["strict-transport-security", EMPTY],
/* 57 */ ["transfer-encoding", EMPTY],
/* 58 */ ["user-agent", EMPTY],
/* 59 */ ["vary", EMPTY],
/* 60 */ ["via", EMPTY],
/* 61 */ ["www-authenticate", EMPTY]
];
private __gshared static Entry[HttpField] __staticFieldMap; // = new HashMap<>();
private __gshared static StaticEntry[string] __staticNameMap; // = new ArrayTernaryTrie<>(true, 512);
private __gshared static StaticEntry[int] __staticTableByHeader; // = new StaticEntry[HttpHeader.getCount];
private __gshared static StaticEntry[] __staticTable; // = new StaticEntry[STATIC_TABLE.length];
enum int STATIC_SIZE = cast(int)STATIC_TABLE.length - 1;
shared static this() {
// __staticTableByHeader = new StaticEntry[HttpHeader.getCount];
__staticTable = new StaticEntry[STATIC_TABLE.length];
Set!string added = new HashSet!(string)();
for (int i = 1; i < STATIC_TABLE.length; i++) {
StaticEntry entry = null;
string name = STATIC_TABLE[i][0];
string value = STATIC_TABLE[i][1];
// HttpHeader header = HttpHeader.CACHE[name];
HttpHeader header = HttpHeader.get(name);
if (header != HttpHeader.Null && !value.empty) {
if(header == HttpHeader.C_METHOD) {
HttpMethod method = HttpMethod.CACHE[value];
if (method != HttpMethod.Null)
entry = new StaticEntry(i, new StaticTableHttpField!(HttpMethod)(header, name, value, method));
}
else if(header == HttpHeader.C_SCHEME) {
// HttpScheme scheme = HttpScheme.CACHE.get(value);
string scheme = value;
if (!scheme.empty)
entry = new StaticEntry(i, new StaticTableHttpField!(string)(header, name, value, scheme));
}
else if(header == HttpHeader.C_STATUS) {
entry = new StaticEntry(i, new StaticTableHttpField!(string)(header, name, value, (value)));
}
}
else
{
// warning("name=>", name, ", length=", HttpHeader.CACHE.length);
}
if (entry is null)
entry = new StaticEntry(i, header == HttpHeader.Null ? new HttpField(STATIC_TABLE[i][0], value) : new HttpField(header, name, value));
__staticTable[i] = entry;
HttpField currentField = entry._field;
string fieldName = currentField.getName().toLower();
string fieldValue = currentField.getValue();
if (fieldValue !is null)
{
// tracef("%s, hash: %d", currentField.toString(), currentField.toHash());
__staticFieldMap[currentField] = entry;
}
else
{
warning("Empty field: ", currentField.toString());
}
if (!added.contains(fieldName)) {
added.add(fieldName);
__staticNameMap[fieldName] = entry;
// if (__staticNameMap[fieldName] is null)
// throw new IllegalStateException("name trie too small");
}
}
// trace(__staticNameMap);
foreach (HttpHeader h ; HttpHeader.values()) {
if(h == HttpHeader.Null)
continue;
string headerName = h.asString().toLower();
// tracef("headerName:%s, ordinal=%d", headerName, h.ordinal());
StaticEntry *entry = (headerName in __staticNameMap);
if (entry !is null)
__staticTableByHeader[h.ordinal()] = *entry;
}
// trace(__staticTableByHeader);
}
private int _maxDynamicTableSizeInBytes;
private int _dynamicTableSizeInBytes;
private DynamicTable _dynamicTable;
private Map!(HttpField, Entry) _fieldMap; // = new HashMap!(HttpField, Entry)();
private Map!(string, Entry) _nameMap; // = new HashMap!(string, Entry)();
this(int maxDynamicTableSize) {
_fieldMap = new HashMap!(HttpField, Entry)();
_nameMap = new HashMap!(string, Entry)();
_maxDynamicTableSizeInBytes = maxDynamicTableSize;
int guesstimateEntries = 10 + maxDynamicTableSize / (32 + 10 + 10);
_dynamicTable = new DynamicTable(guesstimateEntries);
version(HUNT_HTTP_DEBUG_MORE)
tracef(format("HdrTbl[%x] created max=%d", toHash(), maxDynamicTableSize));
}
void resize(int newMaxDynamicTableSize) {
version(HUNT_HTTP_DEBUG_MORE)
tracef(format("HdrTbl[%x] resized max=%d->%d", toHash(), _maxDynamicTableSizeInBytes, newMaxDynamicTableSize));
_maxDynamicTableSizeInBytes = newMaxDynamicTableSize;
_dynamicTable.evict();
}
Entry get(HttpField field) {
Entry entry = _fieldMap.get(field);
if (entry is null)
{
auto entryPtr = field in __staticFieldMap;
if(entryPtr is null) {
// warningf("The field does not exist: %s, %s", field.toString(), field.toHash());
version(HUNT_HTTP_DEBUG) {
warning("The field does not exist: ", field.toString());
}
} else {
entry = *entryPtr;
}
}
return entry;
}
Entry get(string name) {
string lowerName = std.uni.toLower(name);
StaticEntry *entry = lowerName in __staticNameMap;
if (entry !is null)
return *entry;
// trace("name=", name);
// if(!_nameMap.containsKey(n))
// return null;
return _nameMap.get(lowerName);
}
Entry get(int index) {
if (index <= STATIC_SIZE)
return __staticTable[index];
return _dynamicTable.get(index);
}
Entry get(HttpHeader header) {
version(HUNT_DEBUG) {
tracef("header:%s, ordinal=%d",header, header.ordinal());
}
int o = header.ordinal();
Entry e = __staticTableByHeader.get(o, null);
if (e is null)
return get(header.asString());
return e;
}
static Entry getStatic(HttpHeader header) {
return __staticTableByHeader[header.ordinal()];
}
Entry add(HttpField field) {
Entry entry = new Entry(field);
int size = entry.getSize();
if (size > _maxDynamicTableSizeInBytes) {
version(HUNT_DEBUG)
tracef(format("HdrTbl[%x] !added size %d>%d", toHash(), size, _maxDynamicTableSizeInBytes));
return null;
}
_dynamicTableSizeInBytes += size;
_dynamicTable.add(entry);
_fieldMap.put(field, entry);
_nameMap.put(std.uni.toLower(field.getName()), entry);
version(HUNT_DEBUG)
tracef(format("HdrTbl[%x] added %s", toHash(), entry));
_dynamicTable.evict();
return entry;
}
/**
* @return Current dynamic table size in entries
*/
int size() {
return _dynamicTable.size();
}
/**
* @return Current Dynamic table size in Octets
*/
int getDynamicTableSize() {
return _dynamicTableSizeInBytes;
}
/**
* @return Max Dynamic table size in Octets
*/
int getMaxDynamicTableSize() {
return _maxDynamicTableSizeInBytes;
}
int index(Entry entry) {
if (entry._slot < 0)
return 0;
if (entry.isStatic())
return entry._slot;
return _dynamicTable.index(entry);
}
static int staticIndex(HttpHeader header) {
if (header == HttpHeader.Null)
return 0;
// Entry entry = __staticNameMap[header.asString()];
StaticEntry *entry = header.asString() in __staticNameMap;
if (entry is null)
return 0;
return entry._slot;
}
override
string toString() {
return format("HpackContext@%x{entries=%d,size=%d,max=%d}", toHash(), _dynamicTable.size(), _dynamicTableSizeInBytes, _maxDynamicTableSizeInBytes);
}
private class DynamicTable {
Entry[] _entries;
int _size;
int _offset;
int _growby;
private this(int initCapacity) {
_entries = new Entry[initCapacity];
_growby = initCapacity;
}
void add(Entry entry) {
if (_size == _entries.length) {
Entry[] entries = new Entry[_entries.length + _growby];
for (int i = 0; i < _size; i++) {
int slot = (_offset + i) % cast(int)_entries.length;
entries[i] = _entries[slot];
entries[i]._slot = i;
}
_entries = entries;
_offset = 0;
}
int slot = (_size++ + _offset) % cast(int)_entries.length;
_entries[slot] = entry;
entry._slot = slot;
}
int index(Entry entry) {
return STATIC_SIZE + _size - (entry._slot - _offset + cast(int)_entries.length) % cast(int)_entries.length;
}
Entry get(int index) {
int d = index - STATIC_SIZE - 1;
if (d < 0 || d >= _size)
return null;
int slot = (_offset + _size - d - 1) % cast(int)_entries.length;
return _entries[slot];
}
int size() {
return _size;
}
private void evict() {
while (_dynamicTableSizeInBytes > _maxDynamicTableSizeInBytes) {
Entry entry = _entries[_offset];
_entries[_offset] = null;
_offset = (_offset + 1) % cast(int)_entries.length;
_size--;
version(HUNT_DEBUG)
tracef(format("HdrTbl[%x] evict %s", toHash(), entry));
_dynamicTableSizeInBytes -= entry.getSize();
entry._slot = -1;
_fieldMap.remove(entry.getHttpField());
string lc = std.uni.toLower(entry.getHttpField().getName());
if (entry == _nameMap.get(lc))
_nameMap.remove(lc);
}
version(HUNT_DEBUG) {
tracef(format("HdrTbl[%x] entries=%d, size=%d, max=%d", toHash(), _dynamicTable.size(),
_dynamicTableSizeInBytes, _maxDynamicTableSizeInBytes));
}
}
}
static class Entry {
HttpField _field;
int _slot; // The index within it's array
this() {
_slot = -1;
_field = null;
}
this(HttpField field) {
_field = field;
}
int getSize() {
string value = _field.getValue();
return 32 + cast(int)(_field.getName().length + value.length);
}
HttpField getHttpField() {
return _field;
}
bool isStatic() {
return false;
}
byte[] getStaticHuffmanValue() {
return null;
}
override string toString() {
return format("{%s,%d,%s,%x}", isStatic() ? "S" : "D", _slot, _field, toHash());
}
}
static class StaticEntry :Entry {
private byte[] _huffmanValue;
private byte _encodedField;
this(int index, HttpField field) {
super(field);
_slot = index;
string value = field.getValue();
if (value != null && value.length > 0) {
int huffmanLen = Huffman.octetsNeeded(value);
int lenLen = NBitInteger.octectsNeeded(7, huffmanLen);
_huffmanValue = new byte[1 + lenLen + huffmanLen];
ByteBuffer buffer = BufferUtils.toBuffer(_huffmanValue);
// Indicate Huffman
buffer.put(cast(byte) 0x80);
// Add huffman length
NBitInteger.encode(buffer, 7, huffmanLen);
// Encode value
Huffman.encode(buffer, value);
} else
_huffmanValue = null;
_encodedField = cast(byte) (0x80 | index);
}
override
bool isStatic() {
return true;
}
override
byte[] getStaticHuffmanValue() {
return _huffmanValue;
}
byte getEncodedField() {
return _encodedField;
}
}
}
|
D
|
constituting or relating to a tail
resembling a tail
situated in or directed toward the part of the body from which the tail arises
toward the posterior end of the body
|
D
|
# FIXED
OSAL/osal_memory_icall.obj: C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/osal/src/common/osal_memory_icall.c
OSAL/osal_memory_icall.obj: C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/osal/src/inc/comdef.h
OSAL/osal_memory_icall.obj: C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/hal/src/target/_common/hal_types.h
OSAL/osal_memory_icall.obj: C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/hal/src/target/_common/cc26xx/_hal_types.h
OSAL/osal_memory_icall.obj: C:/ti/ti-cgt-arm_18.12.5.LTS/include/stdint.h
OSAL/osal_memory_icall.obj: C:/ti/ti-cgt-arm_18.12.5.LTS/include/_stdint40.h
OSAL/osal_memory_icall.obj: C:/ti/ti-cgt-arm_18.12.5.LTS/include/sys/stdint.h
OSAL/osal_memory_icall.obj: C:/ti/ti-cgt-arm_18.12.5.LTS/include/sys/cdefs.h
OSAL/osal_memory_icall.obj: C:/ti/ti-cgt-arm_18.12.5.LTS/include/sys/_types.h
OSAL/osal_memory_icall.obj: C:/ti/ti-cgt-arm_18.12.5.LTS/include/machine/_types.h
OSAL/osal_memory_icall.obj: C:/ti/ti-cgt-arm_18.12.5.LTS/include/machine/_stdint.h
OSAL/osal_memory_icall.obj: C:/ti/ti-cgt-arm_18.12.5.LTS/include/sys/_stdint.h
OSAL/osal_memory_icall.obj: C:/ti/ti-cgt-arm_18.12.5.LTS/include/stdbool.h
OSAL/osal_memory_icall.obj: C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/hal/src/inc/hal_defs.h
OSAL/osal_memory_icall.obj: C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/osal/src/inc/osal.h
OSAL/osal_memory_icall.obj: C:/ti/ti-cgt-arm_18.12.5.LTS/include/limits.h
OSAL/osal_memory_icall.obj: C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/osal/src/inc/osal_memory.h
OSAL/osal_memory_icall.obj: C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/osal/src/inc/osal_timers.h
OSAL/osal_memory_icall.obj: C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/icall/src/inc/icall.h
OSAL/osal_memory_icall.obj: C:/ti/ti-cgt-arm_18.12.5.LTS/include/stdlib.h
OSAL/osal_memory_icall.obj: C:/ti/ti-cgt-arm_18.12.5.LTS/include/_ti_config.h
OSAL/osal_memory_icall.obj: C:/ti/ti-cgt-arm_18.12.5.LTS/include/linkage.h
OSAL/osal_memory_icall.obj: C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/hal/src/inc/hal_assert.h
OSAL/osal_memory_icall.obj: C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/hal/src/target/_common/hal_types.h
OSAL/osal_memory_icall.obj: C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/icall/src/inc/icall_jt.h
C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/osal/src/common/osal_memory_icall.c:
C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/osal/src/inc/comdef.h:
C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/hal/src/target/_common/hal_types.h:
C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/hal/src/target/_common/cc26xx/_hal_types.h:
C:/ti/ti-cgt-arm_18.12.5.LTS/include/stdint.h:
C:/ti/ti-cgt-arm_18.12.5.LTS/include/_stdint40.h:
C:/ti/ti-cgt-arm_18.12.5.LTS/include/sys/stdint.h:
C:/ti/ti-cgt-arm_18.12.5.LTS/include/sys/cdefs.h:
C:/ti/ti-cgt-arm_18.12.5.LTS/include/sys/_types.h:
C:/ti/ti-cgt-arm_18.12.5.LTS/include/machine/_types.h:
C:/ti/ti-cgt-arm_18.12.5.LTS/include/machine/_stdint.h:
C:/ti/ti-cgt-arm_18.12.5.LTS/include/sys/_stdint.h:
C:/ti/ti-cgt-arm_18.12.5.LTS/include/stdbool.h:
C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/hal/src/inc/hal_defs.h:
C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/osal/src/inc/osal.h:
C:/ti/ti-cgt-arm_18.12.5.LTS/include/limits.h:
C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/osal/src/inc/osal_memory.h:
C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/osal/src/inc/osal_timers.h:
C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/icall/src/inc/icall.h:
C:/ti/ti-cgt-arm_18.12.5.LTS/include/stdlib.h:
C:/ti/ti-cgt-arm_18.12.5.LTS/include/_ti_config.h:
C:/ti/ti-cgt-arm_18.12.5.LTS/include/linkage.h:
C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/hal/src/inc/hal_assert.h:
C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/hal/src/target/_common/hal_types.h:
C:/ti/simplelink_cc2640r2_sdk_4_40_00_10/source/ti/ble5stack/icall/src/inc/icall_jt.h:
|
D
|
// Copyright Ferdinand Majerech 2010 - 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
///In game HUD.
module pong.hud;
@safe
import std.algorithm;
import std.conv;
import pong.player;
import gui.guielement;
import gui.guistatictext;
import time.time;
import math.math;
import color;
///In game HUD.
class HUD
{
private:
alias std.conv.to to;
///Parent of all HUD elements.
GUIElement parent_;
///Displays player 1 score.
GUIStaticText score_text_1_;
///Displays player 2 score.
GUIStaticText score_text_2_;
///Displays time left in game.
GUIStaticText time_text_;
///Maximum time the game can take in game time.
real time_limit_;
public:
/**
* Constructs HUD with specified parameters.
*
* Params: parent = Parent GUI element for all HUD elements.
* time_limit = Maximum time the game will take.
*/
this(GUIElement parent, in real time_limit)
{
parent_ = parent;
time_limit_ = time_limit;
with(new GUIStaticTextFactory)
{
x = "p_left + 8";
y = "p_top + 8";
width = "96";
height = "16";
font_size = 16;
font = "orbitron-light.ttf";
align_x = AlignX.Right;
score_text_1_ = produce();
y = "p_bottom - 24";
score_text_2_ = produce();
x = "p_right - 112";
font = "orbitron-bold.ttf";
time_text_ = produce();
}
parent_.add_child(score_text_1_);
parent_.add_child(score_text_2_);
parent_.add_child(time_text_);
}
///Destroy the HUD.
~this()
{
score_text_1_.die();
score_text_2_.die();
time_text_.die();
}
/**
* Update the HUD.
*
* Params: time_left = Time left until time limit runs out.
* player_1 = First player of the game.
* player_2 = Second player of the game.
*/
void update(real time_left, in Player player_1, in Player player_2)
{
//update time display
time_left = max(time_left, 0.0L);
const time_str = time_string(time_left);
immutable color_start = rgba!"A0A0FFA0";
immutable color_end = Color.red;
//only update if the text has changed
if(time_str != time_text_.text)
{
time_text_.text = time_str != "0:0" ? time_str : time_str ~ " !";
const real t = max(time_left / time_limit_, 1.0L);
time_text_.text_color = color_start.interpolated(color_end, t);
}
//update score displays
score_text_1_.text = player_1.name ~ ": " ~ to!string(player_1.score);
score_text_2_.text = player_2.name ~ ": " ~ to!string(player_2.score);
}
///Hide the HUD.
void hide()
{
score_text_1_.hide();
score_text_2_.hide();
time_text_.hide();
}
///Show the HUD.
void show()
{
score_text_1_.show();
score_text_2_.show();
time_text_.show();
}
}
|
D
|
/Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIO.build/LinuxCPUSet.swift.o : /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/IO.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/NonBlockingFileIO.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/IOData.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Codec.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Thread.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Embedded.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Selectable.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/FileHandle.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ChannelPipeline.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/AddressedEnvelope.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-core.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/EventLoopFuture.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/PriorityQueue.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Channel.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/DeadChannel.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/SocketChannel.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/BaseSocketChannel.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/MulticastChannel.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/BlockingIOThreadPool.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/System.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/FileRegion.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ContiguousCollection.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ChannelOption.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Heap.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Bootstrap.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/EventLoop.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/SocketOptionProvider.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/CircularBuffer.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/MarkedCircularBuffer.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/PendingWritesManager.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/PendingDatagramWritesManager.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ChannelInvoker.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ChannelHandler.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/TypeAssistedChannelHandler.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Resolver.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/GetaddrinfoResolver.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/CompositeError.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/RecvByteBufferAllocator.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Selector.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/FileDescriptor.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Interfaces.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Utilities.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/IntegerTypes.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/SocketAddresses.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/HappyEyeballs.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ChannelHandlers.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-views.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/LinuxCPUSet.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Socket.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/BaseSocket.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ServerSocket.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-int.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-aux.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Linux.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/NIOAny.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio-zlib-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes
/Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIO.build/LinuxCPUSet~partial.swiftmodule : /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/IO.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/NonBlockingFileIO.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/IOData.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Codec.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Thread.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Embedded.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Selectable.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/FileHandle.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ChannelPipeline.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/AddressedEnvelope.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-core.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/EventLoopFuture.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/PriorityQueue.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Channel.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/DeadChannel.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/SocketChannel.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/BaseSocketChannel.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/MulticastChannel.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/BlockingIOThreadPool.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/System.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/FileRegion.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ContiguousCollection.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ChannelOption.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Heap.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Bootstrap.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/EventLoop.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/SocketOptionProvider.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/CircularBuffer.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/MarkedCircularBuffer.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/PendingWritesManager.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/PendingDatagramWritesManager.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ChannelInvoker.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ChannelHandler.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/TypeAssistedChannelHandler.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Resolver.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/GetaddrinfoResolver.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/CompositeError.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/RecvByteBufferAllocator.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Selector.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/FileDescriptor.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Interfaces.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Utilities.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/IntegerTypes.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/SocketAddresses.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/HappyEyeballs.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ChannelHandlers.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-views.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/LinuxCPUSet.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Socket.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/BaseSocket.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ServerSocket.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-int.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-aux.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Linux.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/NIOAny.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio-zlib-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes
/Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIO.build/LinuxCPUSet~partial.swiftdoc : /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/IO.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/NonBlockingFileIO.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/IOData.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Codec.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Thread.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Embedded.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Selectable.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/FileHandle.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ChannelPipeline.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/AddressedEnvelope.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-core.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/EventLoopFuture.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/PriorityQueue.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Channel.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/DeadChannel.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/SocketChannel.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/BaseSocketChannel.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/MulticastChannel.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/BlockingIOThreadPool.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/System.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/FileRegion.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ContiguousCollection.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ChannelOption.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Heap.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Bootstrap.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/EventLoop.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/SocketOptionProvider.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/CircularBuffer.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/MarkedCircularBuffer.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/PendingWritesManager.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/PendingDatagramWritesManager.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ChannelInvoker.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ChannelHandler.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/TypeAssistedChannelHandler.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Resolver.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/GetaddrinfoResolver.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/CompositeError.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/RecvByteBufferAllocator.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Selector.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/FileDescriptor.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Interfaces.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Utilities.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/IntegerTypes.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/SocketAddresses.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/HappyEyeballs.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ChannelHandlers.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-views.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/LinuxCPUSet.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Socket.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/BaseSocket.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ServerSocket.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-int.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-aux.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/Linux.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/NIO/NIOAny.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio-zlib-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes
|
D
|
/Users/doki/Desktop/code12/FabriclogPoint/Build/Intermediates/FabricPoint.build/Debug-iphoneos/FabricPoint.build/Objects-normal/arm64/CameraViewController.o : /Users/doki/Desktop/code12/FabriclogPoint/FabricPoint/AppDelegate.swift /Users/doki/Desktop/code12/FabriclogPoint/FabricPoint/ViewController.swift /Users/doki/Desktop/code12/FabriclogPoint/FabricPoint/CameraViewController.swift /Users/doki/Desktop/code12/FabriclogPoint/FabricPoint/PointUseViewController.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/ObjectiveC.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Metal.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Foundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/AVFoundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreGraphics.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/UIKit.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreText.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/AudioToolbox.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreMedia.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/AVFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreAudio.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/SwiftOnoneSupport.swiftmodule
/Users/doki/Desktop/code12/FabriclogPoint/Build/Intermediates/FabricPoint.build/Debug-iphoneos/FabricPoint.build/Objects-normal/arm64/CameraViewController~partial.swiftmodule : /Users/doki/Desktop/code12/FabriclogPoint/FabricPoint/AppDelegate.swift /Users/doki/Desktop/code12/FabriclogPoint/FabricPoint/ViewController.swift /Users/doki/Desktop/code12/FabriclogPoint/FabricPoint/CameraViewController.swift /Users/doki/Desktop/code12/FabriclogPoint/FabricPoint/PointUseViewController.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/ObjectiveC.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Metal.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Foundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/AVFoundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreGraphics.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/UIKit.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreText.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/AudioToolbox.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreMedia.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/AVFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreAudio.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/SwiftOnoneSupport.swiftmodule
/Users/doki/Desktop/code12/FabriclogPoint/Build/Intermediates/FabricPoint.build/Debug-iphoneos/FabricPoint.build/Objects-normal/arm64/CameraViewController~partial.swiftdoc : /Users/doki/Desktop/code12/FabriclogPoint/FabricPoint/AppDelegate.swift /Users/doki/Desktop/code12/FabriclogPoint/FabricPoint/ViewController.swift /Users/doki/Desktop/code12/FabriclogPoint/FabricPoint/CameraViewController.swift /Users/doki/Desktop/code12/FabriclogPoint/FabricPoint/PointUseViewController.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/ObjectiveC.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Metal.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Foundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/AVFoundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreGraphics.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/UIKit.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreText.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/AudioToolbox.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreMedia.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/AVFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreAudio.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/SwiftOnoneSupport.swiftmodule
|
D
|
module imports.test48a;
struct S
{
int a = 1;
int b = 2;
private:
int c = 3;
}
|
D
|
import std.stdio;
import std.conv;
import std.algorithm;
import std.range;
import std.format;
import std.string;
void main(string[] args)
{
string[][string] inc;
foreach (line; stdin.byLine)
{
string o1, o2;
line.formattedRead!"%s)%s"(o1, o2);
auto p = o1 in inc;
if (p)
*p ~= o2;
else
inc[o1] = [o2];
}
string[] queue;
queue ~= "COM";
int[string] orbits;
orbits[queue.front] = 0;
while (queue.length > 0)
{
string curr = queue.front;
queue.popFront;
int dist = orbits[curr];
foreach (o; inc.get(curr, []))
{
orbits[o] = dist + 1;
queue ~= o;
}
}
orbits.byValue.sum.writeln;
}
|
D
|
instance Mod_1767_PAL_Paladin_PAT (Npc_Default)
{
// ------ NSC ------
name = NAME_Paladin;
guild = GIL_pal;
id = 1767;
voice = 0;
flags = 0; //NPC_FLAG_IMMORTAL oder 0
npctype = NPCTYPE_pat_Paladin_mauer;
// ------ Attribute ------
B_SetAttributesToChapter (self, 5); //setzt Attribute und LEVEL entsprechend dem angegebenen Kapitel (1-6)
// ------ NSC-relevante Talente vergeben ------
B_GiveNpcTalents (self);
// ------ Kampf-Talente ------ //Der enthaltene B_AddFightSkill setzt Talent-Ani abhängig von TrefferChance% - alle Kampftalente werden gleichhoch gesetzt
B_SetFightSkills (self, 65); //Grenzen für Talent-Level liegen bei 30 und 60
// ------ Kampf-Taktik ------
fight_tactic = FAI_HUMAN_STRONG; // MASTER / STRONG / COWARD
// ------ Equippte Waffen ------ //Munition wird automatisch generiert, darf aber angegeben werden
EquipItem (self, ItMw_Paladinschwert);
// ------ Inventory ------
B_CreateAmbientInv (self);
// ------ visuals ------ //Muss NACH Attributen kommen, weil in B_SetNpcVisual die Breite abh. v. STR skaliert wird
B_SetNpcVisual (self, MALE, "Hum_Head_FatBald", Face_N_NormalBart_Dexter, BodyTex_N, ITAR_pal_h);
Mdl_SetModelFatness (self, 1);
Mdl_ApplyOverlayMds (self, "Humans_Militia.mds"); // Tired / Militia / Mage / Arrogance / Relaxed
// ------ TA anmelden ------
daily_routine = Rtn_Start_1767;
};
FUNC VOID Rtn_Start_1767 ()
{
TA_Stand_Guarding_WP (08,05,22,05,"WP_PAT_WEG_135");
TA_Stand_Guarding_WP (22,05,08,05,"WP_PAT_WEG_135");
};
|
D
|
/**
* Log4D - industrial strength logging for D.
*
* Version: $Id$
*
* Author: Kevin Lamonte, <a href="mailto:kevin.lamonte@gmail.com">kevin.lamonte@gmail.com</a>
*
* License: Boost1.0
*
* Copyright (C) 2014 Kevin Lamonte
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or
* organization obtaining a copy of the software and accompanying
* documentation covered by this license (the "Software") to use, reproduce,
* display, distribute, execute, and transmit the Software, and to prepare
* derivative works of the Software, and to permit third-parties to whom the
* Software is furnished to do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated
* by a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
module log4d.layout;
// Description ---------------------------------------------------------------
// Imports -------------------------------------------------------------------
import core.thread;
import std.array;
import std.datetime;
import std.format;
import std.logger;
import std.string;
import std.socket;
import log4d.config;
import log4d.logger;
// Defines -------------------------------------------------------------------
// Globals -------------------------------------------------------------------
// Classes -------------------------------------------------------------------
/**
* A Layout is responsible for rendering the data of a log message to a
* string.
*/
public abstract class Layout {
/**
* Subclasses must implement rendering function.
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be emitted by the Appender
*/
public string render(Log4DLogger logger, Logger.LogEntry message);
/**
* Protected constructor for subclasses.
*/
protected this() {
}
/**
* Subclasses must implement property setter.
*
* Params:
* name = name of property to set
* value = value of property to set
*/
public void setProperty(string name, string value) {
}
/**
* Public constructor finds subclass by name.
*
* Params:
* className = name of subclass to return
*/
static public Layout getLayout(string className) {
if (className == "log4d.layout.SimpleLayout") {
return new SimpleLayout();
}
if (className == "log4d.layout.PatternLayout") {
return new PatternLayout();
}
assert(0, className ~ " not found");
}
}
/**
* SimpleLayout renders a message as "<LogLevel> - <message>"
*/
public class SimpleLayout : Layout {
/**
* Set a property from the config file.
*
* Params:
* name = name of property to set
* value = value of property to set
*/
override public void setProperty(string name, string value) {
super.setProperty(name, value);
}
/**
* Render the message
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be emitted by the Appender
*/
override public string render(Log4DLogger logger, Logger.LogEntry message) {
auto writer = appender!string();
formattedWrite(writer, "%s", message.logLevel);
return toUpper(writer.data) ~ " - " ~ message.msg ~ "\n";
}
}
/**
* PatternLayout renders a message using printf-style formatting for fields.
* The property ConversionPattern is used to specify a format string. The
* following formats are available:
*
* %c Category of the logging event (logger name)
* %C The module name (NOT class name) at the logging call site
* %d Current date in yyyy/MM/dd hh:mm:ss format
* %d{...} Current date in customized format (see below)
* %F The filename at the logging call site
* %H The system hostname (as determined by std.socket.Socket.hostName)
* %l The "pretty function name" at the logging call site
* %L Line number at the logging call site
* %m The message to be logged
* %M Function name at the logging call site
* %n Newline (OS-independent)
* %p Priority (LogLevel) of the logging event (%p{1} shows the first letter)
* %P Process ID (PID) of the caller's process
* %r Number of milliseconds elapsed from program start to logging event
(as determined by std.datetime.Clock.currAppTick)
* %R Number of milliseconds elapsed from last logging event to current
* logging event
* %t Thread ID of the caller's thread
* %T A stack trace of functions called
* %% A literal percent sign '%'
*
*/
public class PatternLayout : Layout {
/// The format string defaults to SimpleLayout
private string conversionPattern = "%p - %m";
/// Shared time since last call to render()
private static __gshared TickDuration lastLogTime;
/// The pieces of the formatted message
private Token [] tokens;
/**
* PatternLayout.render() basically pieces together a string out of a
* list of these token types.
*/
private abstract class Token {
/**
* Produce the string representation.
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be appended in PatternLayout.render()
*/
public string render(Log4DLogger logger, Logger.LogEntry message);
}
/**
* A string literal (stuff between the format tokens)
*/
private class StringToken : Token {
/// The string to show in render()
private string literal;
/**
* Public constructor
*
* Params:
* literal = the string to render()
*/
public this(string literal) {
this.literal = literal;
}
/**
* Produce the string representation.
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be appended in PatternLayout.render()
*/
override public string render(Log4DLogger logger, Logger.LogEntry message) {
return literal;
}
}
/**
* A format token has both a qualified placeholder field and an optional
* braces field.
*/
private abstract class FormatToken : Token {
/// The printf part of the format. Example: "%0.4c{2}", this
/// would be "0.4".
protected string printf;
/// The braces part of the format Example: "%0.4c{2}", this
/// would be "2".
protected string braces;
/**
* Some subclasses change printf/braces in a different way. Let them
* use an empty constructor.
*/
protected this() {
}
/**
* Public constructor
*
* Params:
* printf = the printf part of the format
* braces = the optional braces part
*/
public this(string printf, string braces) {
this.printf = printf;
this.braces = braces;
}
}
/**
* Format for the logger level: %p
*/
private class LogLevelToken : FormatToken {
/**
* Public constructor
*
* Params:
* printf = the printf part of the format
* braces = the optional braces part
*/
public this(string printf, string braces) {
this.braces = braces;
if (printf.length > 0) {
this.printf = "%" ~ printf ~ "s";
}
}
/**
* Produce "INFO" or "I" depending on braces.
*
* Params:
* message = the message parameters
*
* Returns:
* string that is ready to be appended in PatternLayout.render()
*/
private string logLevelString(Logger.LogEntry message) {
if (braces == "1") {
final switch (message.logLevel) {
case LogLevel.all:
return "A";
case LogLevel.trace:
return "T";
case LogLevel.info:
return "I";
case LogLevel.warning:
return "W";
case LogLevel.error:
return "E";
case LogLevel.critical:
return "C";
case LogLevel.fatal:
return "F";
case LogLevel.off:
return "O";
}
}
final switch (message.logLevel) {
case LogLevel.all:
return "ALL";
case LogLevel.trace:
return "TRACE";
case LogLevel.info:
return "INFO";
case LogLevel.warning:
return "WARNING";
case LogLevel.error:
return "ERROR";
case LogLevel.critical:
return "CRITICAL";
case LogLevel.fatal:
return "FATAL";
case LogLevel.off:
return "OFF";
}
}
/**
* Produce the string representation.
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be appended in PatternLayout.render()
*/
override public string render(Log4DLogger logger, Logger.LogEntry message) {
auto str = logLevelString(message);
if (printf.length > 0) {
auto writer = appender!string();
formattedWrite(writer, printf, str);
return writer.data;
}
return str;
}
}
/**
* Format for the date: %D
*
* TODO: %d{<SimpleDateFormat spec>}
*/
private class DateToken : FormatToken {
/**
* Public constructor
*
* Params:
* printf = the printf part of the format
* braces = the optional braces part
*/
public this(string printf, string braces) {
super(printf, braces);
}
/**
* Produce the string representation.
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be appended in PatternLayout.render()
*/
override public string render(Log4DLogger logger, Logger.LogEntry message) {
auto writer = appender!string();
if (braces == "ABSOLUTE") {
// HH:mm:ss,SSS
formattedWrite(writer, "%02d:%02d:%02d,%03d",
message.timestamp.hour,
message.timestamp.minute,
message.timestamp.second,
message.timestamp.fracSec.msecs);
} else if (braces == "ISO8601") {
// yyyy/MM/DD HH:mm:ss,SSS
formattedWrite(writer, "%04d/%02d/%02d %02d:%02d:%02d,%03d",
message.timestamp.year,
message.timestamp.month,
message.timestamp.day,
message.timestamp.hour,
message.timestamp.minute,
message.timestamp.second,
message.timestamp.fracSec.msecs);
} else if (braces == "DATE") {
// This is ripped out of std.datetime. monthToString() is
// not public, boo.
immutable string[12] shortMonthNames = [ "Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov",
"Dec" ];
// dd MMM yyyy HH:mm:ss,SSS
formattedWrite(writer, "%02d %s %04d %02d:%02d:%02d,%03d",
message.timestamp.day,
// monthToString(message.timestamp.month),
shortMonthNames[message.timestamp.month - Month.jan],
message.timestamp.year,
message.timestamp.hour,
message.timestamp.minute,
message.timestamp.second,
message.timestamp.fracSec.msecs);
} else {
// Default: yyyy/MM/DD HH:mm:ss
formattedWrite(writer, "%04d/%02d/%02d %02d:%02d:%02d",
message.timestamp.year,
message.timestamp.month,
message.timestamp.day,
message.timestamp.hour,
message.timestamp.minute,
message.timestamp.second);
}
return writer.data;
}
}
/**
* Format for the log message: %m
*/
private class MessageToken : FormatToken {
/**
* Public constructor
*
* Params:
* printf = the printf part of the format
* braces = the optional braces part
*/
public this(string printf, string braces) {
this.braces = braces;
if (printf.length > 0) {
this.printf = "%" ~ printf ~ "s";
}
}
/**
* Produce the string representation.
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be appended in PatternLayout.render()
*/
override public string render(Log4DLogger logger, Logger.LogEntry message) {
if (printf.length > 0) {
auto writer = appender!string();
formattedWrite(writer, printf, message.msg);
return writer.data;
}
return message.msg;
}
}
/**
* Format for the logger name: %c
*
* TODO: %c{1}, %c{2}, ...
*/
private class LoggerNameToken : FormatToken {
/**
* Public constructor
*
* Params:
* printf = the printf part of the format
* braces = the optional braces part
*/
public this(string printf, string braces) {
this.braces = braces;
if (printf.length > 0) {
this.printf = "%" ~ printf ~ "s";
}
}
/**
* Produce the string representation.
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be appended in PatternLayout.render()
*/
override public string render(Log4DLogger logger, Logger.LogEntry message) {
if (printf.length > 0) {
auto writer = appender!string();
formattedWrite(writer, printf, logger.name);
return writer.data;
}
return logger.name;
}
}
/**
* Format for the module name: %C
*/
private class ModuleNameToken : FormatToken {
/**
* Public constructor
*
* Params:
* printf = the printf part of the format
* braces = the optional braces part
*/
public this(string printf, string braces) {
this.braces = braces;
if (printf.length > 0) {
this.printf = "%" ~ printf ~ "s";
}
}
/**
* Produce the string representation.
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be appended in PatternLayout.render()
*/
override public string render(Log4DLogger logger, Logger.LogEntry message) {
if (printf.length > 0) {
auto writer = appender!string();
formattedWrite(writer, printf, message.moduleName);
return writer.data;
}
return message.moduleName;
}
}
/**
* Format for the function name: %F
*
* TODO: %F{1}, %F{2}, ...
*/
private class FileNameToken : FormatToken {
/**
* Public constructor
*
* Params:
* printf = the printf part of the format
* braces = the optional braces part
*/
public this(string printf, string braces) {
this.braces = braces;
if (printf.length > 0) {
this.printf = "%" ~ printf ~ "s";
}
}
/**
* Produce the string representation.
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be appended in PatternLayout.render()
*/
override public string render(Log4DLogger logger, Logger.LogEntry message) {
if (printf.length > 0) {
auto writer = appender!string();
formattedWrite(writer, printf, message.file);
return writer.data;
}
return message.file;
}
}
/**
* Format for the pretty function name: %l
*/
private class PrettyFunctionNameToken : FormatToken {
/**
* Public constructor
*
* Params:
* printf = the printf part of the format
* braces = the optional braces part
*/
public this(string printf, string braces) {
this.braces = braces;
if (printf.length > 0) {
this.printf = "%" ~ printf ~ "s";
}
}
/**
* Produce the string representation.
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be appended in PatternLayout.render()
*/
override public string render(Log4DLogger logger, Logger.LogEntry message) {
if (printf.length > 0) {
auto writer = appender!string();
formattedWrite(writer, printf, message.prettyFuncName);
return writer.data;
}
return message.prettyFuncName;
}
}
/**
* Format for the function name: %M
*
* TODO: %M{1}, %M{2}, ...
*/
private class FunctionNameToken : FormatToken {
/**
* Public constructor
*
* Params:
* printf = the printf part of the format
* braces = the optional braces part
*/
public this(string printf, string braces) {
this.braces = braces;
if (printf.length > 0) {
this.printf = "%" ~ printf ~ "s";
}
}
/**
* Produce the string representation.
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be appended in PatternLayout.render()
*/
override public string render(Log4DLogger logger, Logger.LogEntry message) {
if (printf.length > 0) {
auto writer = appender!string();
formattedWrite(writer, printf, message.funcName);
return writer.data;
}
return message.funcName;
}
}
/**
* Format for the hostname: %H
*/
private class HostnameToken : FormatToken {
/// Determine hostname only once
private __gshared string hostname = "";
/**
* Public constructor
*
* Params:
* printf = the printf part of the format
* braces = the optional braces part
*/
public this(string printf, string braces) {
this.braces = braces;
if (printf.length > 0) {
this.printf = "%" ~ printf ~ "s";
}
synchronized (LogManager.getInstance().mutex) {
if (hostname.length == 0) {
hostname = Socket.hostName;
}
}
}
/**
* Produce the string representation.
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be appended in PatternLayout.render()
*/
override public string render(Log4DLogger logger, Logger.LogEntry message) {
if (printf.length > 0) {
auto writer = appender!string();
formattedWrite(writer, printf, hostname);
return writer.data;
}
return hostname;
}
}
/**
* Format for the line number: %L
*/
private class LineNumberToken : FormatToken {
/**
* Public constructor
*
* Params:
* printf = the printf part of the format
* braces = the optional braces part
*/
public this(string printf, string braces) {
this.braces = braces;
this.printf = "%" ~ printf ~ "d";
}
/**
* Produce the string representation.
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be appended in PatternLayout.render()
*/
override public string render(Log4DLogger logger, Logger.LogEntry message) {
auto writer = appender!string();
if (printf.length > 0) {
formattedWrite(writer, printf, message.line);
} else {
formattedWrite(writer, "%d", message.line);
}
return writer.data;
}
}
/**
* Format for the PID: %P
*/
private class ProcessIDToken : FormatToken {
/**
* Public constructor
*
* Params:
* printf = the printf part of the format
* braces = the optional braces part
*/
public this(string printf, string braces) {
this.braces = braces;
if (printf.length > 0) {
this.printf = "%" ~ printf ~ "s";
}
}
/**
* Produce the string representation.
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be appended in PatternLayout.render()
*/
override public string render(Log4DLogger logger, Logger.LogEntry message) {
auto writer = appender!string();
if (printf.length > 0) {
formattedWrite(writer, printf, getpid());
} else {
formattedWrite(writer, "%s", getpid());
}
return writer.data;
}
}
/**
* Format for the thread ID: %t
*/
private class ThreadIDToken : FormatToken {
/**
* Public constructor
*
* Params:
* printf = the printf part of the format
* braces = the optional braces part
*/
public this(string printf, string braces) {
this.braces = braces;
if (printf.length > 0) {
this.printf = "%" ~ printf ~ "x";
}
}
/**
* Produce the string representation.
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be appended in PatternLayout.render()
*/
override public string render(Log4DLogger logger, Logger.LogEntry message) {
auto writer = appender!string();
auto myThread = Thread.getThis();
if (printf.length > 0) {
formattedWrite(writer, printf, myThread.toHash());
} else {
formattedWrite(writer, "%x", myThread.toHash());
}
return writer.data;
}
}
/**
* Format for the time elapsed since the application was started: %r
*/
private class AppMillisToken : FormatToken {
/**
* Public constructor
*
* Params:
* printf = the printf part of the format
* braces = the optional braces part
*/
public this(string printf, string braces) {
this.braces = braces;
this.printf = "%" ~ printf ~ "d";
}
/**
* Produce the string representation.
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be appended in PatternLayout.render()
*/
override public string render(Log4DLogger logger, Logger.LogEntry message) {
auto writer = appender!string();
if (printf.length > 0) {
formattedWrite(writer, printf, Clock.currAppTick().to!("msecs", long)());
} else {
formattedWrite(writer, "%d", Clock.currAppTick().to!("msecs", long)());
}
return writer.data;
}
}
/**
* Format for the time elapsed since the last logging call: %R
*/
private class DiffMillisToken : FormatToken {
/**
* Public constructor
*
* Params:
* printf = the printf part of the format
* braces = the optional braces part
*/
public this(string printf, string braces) {
this.braces = braces;
this.printf = "%" ~ printf ~ "d";
}
/**
* Produce the string representation.
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be appended in PatternLayout.render()
*/
override public string render(Log4DLogger logger, Logger.LogEntry message) {
auto now = Clock.currSystemTick;
auto diffTime = now - lastLogTime;
auto writer = appender!string();
if (printf.length > 0) {
formattedWrite(writer, printf, diffTime.to!("msecs", long));
} else {
formattedWrite(writer, "%d", diffTime.to!("msecs", long));
}
return writer.data;
}
}
/**
* Set a property from the config file.
*
* Params:
* name = name of property to set
* value = value of property to set
*/
override public void setProperty(string name, string value) {
super.setProperty(name, value);
if (name == "ConversionPattern") {
conversionPattern = value;
setupPattern();
}
}
/**
* Turn conversionPattern into a series of fixed strings and replaceable tokens.
*/
private void setupPattern() {
tokens.length = 0;
enum State {
LITERAL,
PERCENT,
PRINTF,
BRACE,
}
State state = State.LITERAL;
string printf = "";
string braces = "";
string literal = "";
FormatToken printfToken;
// Perform a line scan, locating printf-style tokens and string
// literals.
foreach (ch; conversionPattern) {
/+
std.stdio.stdout.writefln("state: %s ch '%s' literal '%s' printf '%s' braces '%s'",
state, ch, literal, printf, braces);
+/
final switch (state) {
case State.LITERAL:
if (ch == '%') {
state = State.PERCENT;
continue;
}
literal ~= ch;
break;
case State.PERCENT:
if (ch == '%') {
literal ~= '%';
state = State.LITERAL;
continue;
}
if (literal.length > 0) {
tokens ~= new StringToken(literal);
literal = "";
}
assert(printf.length == 0);
state = State.PRINTF;
goto case State.PRINTF;
case State.PRINTF:
if ((ch >= '0') && (ch <= '9')) {
printf ~= ch;
continue;
}
if ((ch == '.') ||
(ch == '-') ||
(ch == '+')
) {
printf ~= ch;
continue;
}
if (ch == '{') {
assert(braces.length == 0);
state = State.BRACE;
continue;
}
if (ch == '%') {
// Another printf token back-to-back
printf = "";
printfToken = null;
state = State.PERCENT;
continue;
}
if (printfToken !is null) {
assert(literal.length == 0);
state = State.LITERAL;
literal ~= ch;
printfToken = null;
continue;
}
if (ch == 'p') {
printfToken = new LogLevelToken(printf, braces);
printf = "";
tokens ~= printfToken;
continue;
} else if (ch == 'c') {
printfToken = new LoggerNameToken(printf, braces);
printf = "";
tokens ~= printfToken;
continue;
} else if (ch == 'C') {
printfToken = new ModuleNameToken(printf, braces);
printf = "";
tokens ~= printfToken;
continue;
} else if (ch == 'd') {
printfToken = new DateToken(printf, braces);
printf = "";
tokens ~= printfToken;
continue;
} else if (ch == 'F') {
printfToken = new FileNameToken(printf, braces);
printf = "";
tokens ~= printfToken;
continue;
} else if (ch == 'H') {
printfToken = new HostnameToken(printf, braces);
printf = "";
tokens ~= printfToken;
continue;
} else if (ch == 'l') {
printfToken = new PrettyFunctionNameToken(printf, braces);
printf = "";
tokens ~= printfToken;
continue;
} else if (ch == 'L') {
printfToken = new LineNumberToken(printf, braces);
printf = "";
tokens ~= printfToken;
continue;
} else if (ch == 'M') {
printfToken = new FunctionNameToken(printf, braces);
printf = "";
tokens ~= printfToken;
continue;
} else if (ch == 'm') {
printfToken = new MessageToken(printf, braces);
printf = "";
tokens ~= printfToken;
continue;
} else if (ch == 'n') {
tokens ~= new StringToken("\n");
printf = "";
state = State.LITERAL;
continue;
} else if (ch == 'P') {
printfToken = new ProcessIDToken(printf, braces);
printf = "";
tokens ~= printfToken;
continue;
} else if (ch == 'r') {
printfToken = new AppMillisToken(printf, braces);
printf = "";
tokens ~= printfToken;
continue;
} else if (ch == 'R') {
printfToken = new DiffMillisToken(printf, braces);
printf = "";
tokens ~= printfToken;
continue;
} else if (ch == 't') {
printfToken = new ThreadIDToken(printf, braces);
printf = "";
tokens ~= printfToken;
continue;
}
// Unknown printf specifier, abandon ship
printf = "";
state = State.LITERAL;
break;
case State.BRACE:
if (ch == '}') {
assert(printfToken !is null);
printfToken.braces = braces;
braces = "";
printf = "";
printfToken = null;
assert(literal.length == 0);
state = State.LITERAL;
continue;
}
braces ~= ch;
break;
}
}
// At EOF, see what is left
final switch (state) {
case State.LITERAL:
if (literal.length > 0) {
tokens ~= new StringToken(literal);
}
break;
case State.PERCENT:
if (literal.length > 0) {
tokens ~= new StringToken(literal);
}
break;
case State.PRINTF:
// Nothing else to do here - tokens already has the printfToken
// if it was recognized.
break;
case State.BRACE:
// Nothing to do here, printfToken.braces is incomplete so ignore it.
break;
}
}
/**
* Render the message
*
* Params:
* logger = logger that generated the message
* message = the message parameters
*
* Returns:
* string that is ready to be emitted by the Appender
*/
override public string render(Log4DLogger logger, Logger.LogEntry message) {
auto now = Clock.currSystemTick;
auto writer = appender!string();
foreach (t; tokens) {
writer.put(t.render(logger, message));
}
synchronized (LogManager.getInstance().mutex) {
lastLogTime = now;
}
return writer.data;
}
}
// Functions -----------------------------------------------------------------
|
D
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Port to the D programming language:
* Frank Benoit <benoit@tionex.de>
*******************************************************************************/
module dwt.events.DisposeListener;
public import dwt.internal.DWTEventListener;
public import dwt.events.DisposeEvent;
/**
* Classes which implement this interface provide a method
* that deals with the event that is generated when a widget
* is disposed.
* <p>
* After creating an instance of a class that :
* this interface it can be added to a widget using the
* <code>addDisposeListener</code> method and removed using
* the <code>removeDisposeListener</code> method. When a
* widget is disposed, the widgetDisposed method will
* be invoked.
* </p>
*
* @see DisposeEvent
*/
public interface DisposeListener : DWTEventListener {
/**
* Sent when the widget is disposed.
*
* @param e an event containing information about the dispose
*/
public void widgetDisposed(DisposeEvent e);
}
|
D
|
c: Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
SPDX-License-Identifier: curl
Long: http0.9
Tags: Versions
Protocols: HTTP
Help: Allow HTTP 0.9 responses
Category: http
Example: --http0.9 $URL
Added: 7.64.0
See-also: http1.1 http2 http3
Multi: boolean
---
Tells curl to be fine with HTTP version 0.9 response.
HTTP/0.9 is a response without headers and therefore you can also connect with
this to non-HTTP servers and still get a response since curl will simply
transparently downgrade - if allowed.
Since curl 7.66.0, HTTP/0.9 is disabled by default.
|
D
|
module mach.sdl.graphics;
public:
import mach.sdl.graphics.color;
import mach.sdl.graphics.displaymode;
import mach.sdl.graphics.mask;
import mach.sdl.graphics.pixelformat;
import mach.sdl.graphics.primitives;
import mach.sdl.graphics.surface;
import mach.sdl.graphics.texture;
import mach.sdl.graphics.ttf;
import mach.sdl.graphics.vertex;
|
D
|
// Written in the D programming language.
/**
* Elementary mathematical functions
*
* Contains the elementary mathematical functions (powers, roots,
* and trigonometric functions), and low-level floating-point operations.
* Mathematical special functions are available in std.mathspecial.
*
* The functionality closely follows the IEEE754-2008 standard for
* floating-point arithmetic, including the use of camelCase names rather
* than C99-style lower case names. All of these functions behave correctly
* when presented with an infinity or NaN.
*
* Unlike C, there is no global 'errno' variable. Consequently, almost all of
* these functions are pure nothrow.
*
* Status:
* The semantics and names of feqrel and approxEqual will be revised.
*
* Macros:
* WIKI = Phobos/StdMath
*
* TABLE_SV = <table border=1 cellpadding=4 cellspacing=0>
* <caption>Special Values</caption>
* $0</table>
* SVH = $(TR $(TH $1) $(TH $2))
* SV = $(TR $(TD $1) $(TD $2))
*
* NAN = $(RED NAN)
* SUP = <span style="vertical-align:super;font-size:smaller">$0</span>
* GAMMA = Γ
* THETA = θ
* INTEGRAL = ∫
* INTEGRATE = $(BIG ∫<sub>$(SMALL $1)</sub><sup>$2</sup>)
* POWER = $1<sup>$2</sup>
* SUB = $1<sub>$2</sub>
* BIGSUM = $(BIG Σ <sup>$2</sup><sub>$(SMALL $1)</sub>)
* CHOOSE = $(BIG () <sup>$(SMALL $1)</sup><sub>$(SMALL $2)</sub> $(BIG ))
* PLUSMN = ±
* INFIN = ∞
* PLUSMNINF = ±∞
* PI = π
* LT = <
* GT = >
* SQRT = √
* HALF = ½
*
* Copyright: Copyright Digital Mars 2000 - 2011.
* D implementations of tan, atan, atan2, exp, expm1, exp2, log, log10, log1p,
* log2, floor, ceil and lrint functions are based on the CEPHES math library,
* which is Copyright (C) 2001 Stephen L. Moshier <steve@moshier.net>
* and are incorporated herein by permission of the author. The author
* reserves the right to distribute this material elsewhere under different
* copying permissions. These modifications are distributed here under
* the following terms:
* License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
* Authors: $(WEB digitalmars.com, Walter Bright),
* Don Clugston, Conversion of CEPHES math library to D by Iain Buclaw
* Source: $(PHOBOSSRC std/_math.d)
*/
module std.math;
import core.stdc.math;
import std.traits;
version(unittest)
{
import std.typetuple;
}
version(LDC)
{
import ldc.intrinsics;
}
version(DigitalMars)
{
version = INLINE_YL2X; // x87 has opcodes for these
}
version (X86)
{
version = X86_Any;
}
version (X86_64)
{
version = X86_Any;
}
version(D_InlineAsm_X86)
{
version = InlineAsm_X86_Any;
}
else version(D_InlineAsm_X86_64)
{
version = InlineAsm_X86_Any;
}
version(unittest)
{
import core.stdc.stdio;
static if(real.sizeof > double.sizeof)
enum uint useDigits = 16;
else
enum uint useDigits = 15;
/******************************************
* Compare floating point numbers to n decimal digits of precision.
* Returns:
* 1 match
* 0 nomatch
*/
private bool equalsDigit(real x, real y, uint ndigits)
{
if (signbit(x) != signbit(y))
return 0;
if (isinf(x) && isinf(y))
return 1;
if (isinf(x) || isinf(y))
return 0;
if (isnan(x) && isnan(y))
return 1;
if (isnan(x) || isnan(y))
return 0;
char[30] bufx;
char[30] bufy;
assert(ndigits < bufx.length);
int ix;
int iy;
version(Win64)
alias double real_t;
else
alias real real_t;
ix = sprintf(bufx.ptr, "%.*Lg", ndigits, cast(real_t) x);
iy = sprintf(bufy.ptr, "%.*Lg", ndigits, cast(real_t) y);
assert(ix < bufx.length && ix > 0);
assert(ix < bufy.length && ix > 0);
return bufx[0 .. ix] == bufy[0 .. iy];
}
}
private:
/*
* The following IEEE 'real' formats are currently supported:
* 64 bit Big-endian 'double' (eg PowerPC)
* 128 bit Big-endian 'quadruple' (eg SPARC)
* 64 bit Little-endian 'double' (eg x86-SSE2)
* 80 bit Little-endian, with implied bit 'real80' (eg x87, Itanium).
* 128 bit Little-endian 'quadruple' (not implemented on any known processor!)
*
* Non-IEEE 128 bit Big-endian 'doubledouble' (eg PowerPC) has partial support
*/
version(LittleEndian)
{
static assert(real.mant_dig == 53 || real.mant_dig==64
|| real.mant_dig == 113,
"Only 64-bit, 80-bit, and 128-bit reals"~
" are supported for LittleEndian CPUs");
}
else
{
static assert(real.mant_dig == 53 || real.mant_dig==106
|| real.mant_dig == 113,
"Only 64-bit and 128-bit reals are supported for BigEndian CPUs."~
" double-double reals have partial support");
}
// Constants used for extracting the components of the representation.
// They supplement the built-in floating point properties.
template floatTraits(T)
{
// EXPMASK is a ushort mask to select the exponent portion (without sign)
// EXPPOS_SHORT is the index of the exponent when represented as a ushort array.
// SIGNPOS_BYTE is the index of the sign when represented as a ubyte array.
// RECIP_EPSILON is the value such that (smallest_subnormal) * RECIP_EPSILON == T.min_normal
enum T RECIP_EPSILON = (1/T.epsilon);
static if (T.mant_dig == 24)
{ // float
enum ushort EXPMASK = 0x7F80;
enum ushort EXPBIAS = 0x3F00;
enum uint EXPMASK_INT = 0x7F80_0000;
enum uint MANTISSAMASK_INT = 0x007F_FFFF;
version(LittleEndian)
{
enum EXPPOS_SHORT = 1;
}
else
{
enum EXPPOS_SHORT = 0;
}
}
else static if (T.mant_dig == 53) // double, or real==double
{
enum ushort EXPMASK = 0x7FF0;
enum ushort EXPBIAS = 0x3FE0;
enum uint EXPMASK_INT = 0x7FF0_0000;
enum uint MANTISSAMASK_INT = 0x000F_FFFF; // for the MSB only
version(LittleEndian)
{
enum EXPPOS_SHORT = 3;
enum SIGNPOS_BYTE = 7;
}
else
{
enum EXPPOS_SHORT = 0;
enum SIGNPOS_BYTE = 0;
}
}
else static if (T.mant_dig == 64) // real80
{
enum ushort EXPMASK = 0x7FFF;
enum ushort EXPBIAS = 0x3FFE;
version(LittleEndian)
{
enum EXPPOS_SHORT = 4;
enum SIGNPOS_BYTE = 9;
}
else
{
enum EXPPOS_SHORT = 0;
enum SIGNPOS_BYTE = 0;
}
}
else static if (T.mant_dig == 113) // quadruple
{
enum ushort EXPMASK = 0x7FFF;
version(LittleEndian)
{
enum EXPPOS_SHORT = 7;
enum SIGNPOS_BYTE = 15;
}
else
{
enum EXPPOS_SHORT = 0;
enum SIGNPOS_BYTE = 0;
}
}
else static if (T.mant_dig == 106) // doubledouble
{
enum ushort EXPMASK = 0x7FF0;
// the exponent byte is not unique
version(LittleEndian)
{
enum EXPPOS_SHORT = 7; // [3] is also an exp short
enum SIGNPOS_BYTE = 15;
}
else
{
enum EXPPOS_SHORT = 0; // [4] is also an exp short
enum SIGNPOS_BYTE = 0;
}
}
}
// These apply to all floating-point types
version(LittleEndian)
{
enum MANTISSA_LSB = 0;
enum MANTISSA_MSB = 1;
}
else
{
enum MANTISSA_LSB = 1;
enum MANTISSA_MSB = 0;
}
public:
// Values obtained from Wolfram Alpha. 116 bits ought to be enough for anybody.
// Wolfram Alpha LLC. 2011. Wolfram|Alpha. http://www.wolframalpha.com/input/?i=e+in+base+16 (access July 6, 2011).
enum real E = 0x1.5bf0a8b1457695355fb8ac404e7a8p+1L; /** e = 2.718281... */
enum real LOG2T = 0x1.a934f0979a3715fc9257edfe9b5fbp+1L; /** $(SUB log, 2)10 = 3.321928... */
enum real LOG2E = 0x1.71547652b82fe1777d0ffda0d23a8p+0L; /** $(SUB log, 2)e = 1.442695... */
enum real LOG2 = 0x1.34413509f79fef311f12b35816f92p-2L; /** $(SUB log, 10)2 = 0.301029... */
enum real LOG10E = 0x1.bcb7b1526e50e32a6ab7555f5a67cp-2L; /** $(SUB log, 10)e = 0.434294... */
enum real LN2 = 0x1.62e42fefa39ef35793c7673007e5fp-1L; /** ln 2 = 0.693147... */
enum real LN10 = 0x1.26bb1bbb5551582dd4adac5705a61p+1L; /** ln 10 = 2.302585... */
enum real PI = 0x1.921fb54442d18469898cc51701b84p+1L; /** $(_PI) = 3.141592... */
enum real PI_2 = PI/2; /** $(PI) / 2 = 1.570796... */
enum real PI_4 = PI/4; /** $(PI) / 4 = 0.785398... */
enum real M_1_PI = 0x1.45f306dc9c882a53f84eafa3ea69cp-2L; /** 1 / $(PI) = 0.318309... */
enum real M_2_PI = 2*M_1_PI; /** 2 / $(PI) = 0.636619... */
enum real M_2_SQRTPI = 0x1.20dd750429b6d11ae3a914fed7fd8p+0L; /** 2 / $(SQRT)$(PI) = 1.128379... */
enum real SQRT2 = 0x1.6a09e667f3bcc908b2fb1366ea958p+0L; /** $(SQRT)2 = 1.414213... */
enum real SQRT1_2 = SQRT2/2; /** $(SQRT)$(HALF) = 0.707106... */
// Note: Make sure the magic numbers in compiler backend for x87 match these.
/***********************************
* Calculates the absolute value
*
* For complex numbers, abs(z) = sqrt( $(POWER z.re, 2) + $(POWER z.im, 2) )
* = hypot(z.re, z.im).
*/
Num abs(Num)(Num x) @safe pure nothrow
if (is(typeof(Num.init >= 0)) && is(typeof(-Num.init)) &&
!(is(Num* : const(ifloat*)) || is(Num* : const(idouble*))
|| is(Num* : const(ireal*))))
{
static if (isFloatingPoint!(Num))
return fabs(x);
else
return x>=0 ? x : -x;
}
auto abs(Num)(Num z) @safe pure nothrow
if (is(Num* : const(cfloat*)) || is(Num* : const(cdouble*))
|| is(Num* : const(creal*)))
{
return hypot(z.re, z.im);
}
/** ditto */
real abs(Num)(Num y) @safe pure nothrow
if (is(Num* : const(ifloat*)) || is(Num* : const(idouble*))
|| is(Num* : const(ireal*)))
{
return fabs(y.im);
}
unittest
{
assert(isIdentical(abs(-0.0L), 0.0L));
assert(isNaN(abs(real.nan)));
assert(abs(-real.infinity) == real.infinity);
assert(abs(-3.2Li) == 3.2L);
assert(abs(71.6Li) == 71.6L);
assert(abs(-56) == 56);
assert(abs(2321312L) == 2321312L);
assert(abs(-1+1i) == sqrt(2.0L));
}
/***********************************
* Complex conjugate
*
* conj(x + iy) = x - iy
*
* Note that z * conj(z) = $(POWER z.re, 2) - $(POWER z.im, 2)
* is always a real number
*/
creal conj(creal z) @safe pure nothrow
{
return z.re - z.im*1i;
}
/** ditto */
ireal conj(ireal y) @safe pure nothrow
{
return -y;
}
unittest
{
assert(conj(7 + 3i) == 7-3i);
ireal z = -3.2Li;
assert(conj(z) == -z);
}
/***********************************
* Returns cosine of x. x is in radians.
*
* $(TABLE_SV
* $(TR $(TH x) $(TH cos(x)) $(TH invalid?))
* $(TR $(TD $(NAN)) $(TD $(NAN)) $(TD yes) )
* $(TR $(TD $(PLUSMN)$(INFIN)) $(TD $(NAN)) $(TD yes) )
* )
* Bugs:
* Results are undefined if |x| >= $(POWER 2,64).
*/
real cos(real x) @safe pure nothrow; /* intrinsic */
/***********************************
* Returns sine of x. x is in radians.
*
* $(TABLE_SV
* $(TR $(TH x) $(TH sin(x)) $(TH invalid?))
* $(TR $(TD $(NAN)) $(TD $(NAN)) $(TD yes))
* $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) $(TD no))
* $(TR $(TD $(PLUSMNINF)) $(TD $(NAN)) $(TD yes))
* )
* Bugs:
* Results are undefined if |x| >= $(POWER 2,64).
*/
real sin(real x) @safe pure nothrow; /* intrinsic */
/***********************************
* sine, complex and imaginary
*
* sin(z) = sin(z.re)*cosh(z.im) + cos(z.re)*sinh(z.im)i
*
* If both sin($(THETA)) and cos($(THETA)) are required,
* it is most efficient to use expi($(THETA)).
*/
creal sin(creal z) @safe pure nothrow
{
creal cs = expi(z.re);
creal csh = coshisinh(z.im);
return cs.im * csh.re + cs.re * csh.im * 1i;
}
/** ditto */
ireal sin(ireal y) @safe pure nothrow
{
return cosh(y.im)*1i;
}
unittest
{
assert(sin(0.0+0.0i) == 0.0);
assert(sin(2.0+0.0i) == sin(2.0L) );
}
/***********************************
* cosine, complex and imaginary
*
* cos(z) = cos(z.re)*cosh(z.im) - sin(z.re)*sinh(z.im)i
*/
creal cos(creal z) @safe pure nothrow
{
creal cs = expi(z.re);
creal csh = coshisinh(z.im);
return cs.re * csh.re - cs.im * csh.im * 1i;
}
/** ditto */
real cos(ireal y) @safe pure nothrow
{
return cosh(y.im);
}
unittest
{
assert(cos(0.0+0.0i)==1.0);
assert(cos(1.3L+0.0i)==cos(1.3L));
assert(cos(5.2Li)== cosh(5.2L));
}
/****************************************************************************
* Returns tangent of x. x is in radians.
*
* $(TABLE_SV
* $(TR $(TH x) $(TH tan(x)) $(TH invalid?))
* $(TR $(TD $(NAN)) $(TD $(NAN)) $(TD yes))
* $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) $(TD no))
* $(TR $(TD $(PLUSMNINF)) $(TD $(NAN)) $(TD yes))
* )
*/
real tan(real x) @trusted pure nothrow
{
version(D_InlineAsm_X86)
{
asm
{
fld x[EBP] ; // load theta
fxam ; // test for oddball values
fstsw AX ;
sahf ;
jc trigerr ; // x is NAN, infinity, or empty
// 387's can handle subnormals
SC18: fptan ;
fstp ST(0) ; // dump X, which is always 1
fstsw AX ;
sahf ;
jnp Lret ; // C2 = 1 (x is out of range)
// Do argument reduction to bring x into range
fldpi ;
fxch ;
SC17: fprem1 ;
fstsw AX ;
sahf ;
jp SC17 ;
fstp ST(1) ; // remove pi from stack
jmp SC18 ;
trigerr:
jnp Lret ; // if theta is NAN, return theta
fstp ST(0) ; // dump theta
}
return real.nan;
Lret: {}
}
else version(D_InlineAsm_X86_64)
{
version (Win64)
{
asm
{
fld real ptr [RCX] ; // load theta
}
}
else
{
asm
{
fld x[RBP] ; // load theta
}
}
asm
{
fxam ; // test for oddball values
fstsw AX ;
test AH,1 ;
jnz trigerr ; // x is NAN, infinity, or empty
// 387's can handle subnormals
SC18: fptan ;
fstp ST(0) ; // dump X, which is always 1
fstsw AX ;
test AH,4 ;
jz Lret ; // C2 = 1 (x is out of range)
// Do argument reduction to bring x into range
fldpi ;
fxch ;
SC17: fprem1 ;
fstsw AX ;
test AH,4 ;
jnz SC17 ;
fstp ST(1) ; // remove pi from stack
jmp SC18 ;
trigerr:
test AH,4 ;
jz Lret ; // if theta is NAN, return theta
fstp ST(0) ; // dump theta
}
return real.nan;
Lret: {}
}
else
{
// Coefficients for tan(x)
static immutable real[3] P = [
-1.7956525197648487798769E7L,
1.1535166483858741613983E6L,
-1.3093693918138377764608E4L,
];
static immutable real[5] Q = [
-5.3869575592945462988123E7L,
2.5008380182335791583922E7L,
-1.3208923444021096744731E6L,
1.3681296347069295467845E4L,
1.0000000000000000000000E0L,
];
// PI/4 split into three parts.
enum real P1 = 7.853981554508209228515625E-1L;
enum real P2 = 7.946627356147928367136046290398E-9L;
enum real P3 = 3.061616997868382943065164830688E-17L;
// Special cases.
if (x == 0.0 || isNaN(x))
return x;
if (isInfinity(x))
return real.nan;
// Make argument positive but save the sign.
bool sign = false;
if (signbit(x))
{
sign = true;
x = -x;
}
// Compute x mod PI/4.
real y = floor(x / PI_4);
// Strip high bits of integer part.
real z = ldexp(y, -4);
// Compute y - 16 * (y / 16).
z = y - ldexp(floor(z), 4);
// Integer and fraction part modulo one octant.
int j = cast(int)(z);
// Map zeros and singularities to origin.
if (j & 1)
{
j += 1;
y += 1.0;
}
z = ((x - y * P1) - y * P2) - y * P3;
real zz = z * z;
if (zz > 1.0e-20L)
y = z + z * (zz * poly(zz, P) / poly(zz, Q));
else
y = z;
if (j & 2)
y = -1.0 / y;
return (sign) ? -y : y;
}
}
unittest
{
static real[2][] vals = // angle,tan
[
[ 0, 0],
[ .5, .5463024898],
[ 1, 1.557407725],
[ 1.5, 14.10141995],
[ 2, -2.185039863],
[ 2.5,-.7470222972],
[ 3, -.1425465431],
[ 3.5, .3745856402],
[ 4, 1.157821282],
[ 4.5, 4.637332055],
[ 5, -3.380515006],
[ 5.5,-.9955840522],
[ 6, -.2910061914],
[ 6.5, .2202772003],
[ 10, .6483608275],
// special angles
[ PI_4, 1],
//[ PI_2, real.infinity], // PI_2 is not _exactly_ pi/2.
[ 3*PI_4, -1],
[ PI, 0],
[ 5*PI_4, 1],
//[ 3*PI_2, -real.infinity],
[ 7*PI_4, -1],
[ 2*PI, 0],
];
int i;
for (i = 0; i < vals.length; i++)
{
real x = vals[i][0];
real r = vals[i][1];
real t = tan(x);
//printf("tan(%Lg) = %Lg, should be %Lg\n", x, t, r);
if (!isIdentical(r, t)) assert(fabs(r-t) <= .0000001);
x = -x;
r = -r;
t = tan(x);
//printf("tan(%Lg) = %Lg, should be %Lg\n", x, t, r);
if (!isIdentical(r, t) && !(r!=r && t!=t)) assert(fabs(r-t) <= .0000001);
}
// overflow
assert(isNaN(tan(real.infinity)));
assert(isNaN(tan(-real.infinity)));
// NaN propagation
assert(isIdentical( tan(NaN(0x0123L)), NaN(0x0123L) ));
}
unittest
{
assert(equalsDigit(tan(PI / 3), std.math.sqrt(3.0), useDigits));
}
/***************
* Calculates the arc cosine of x,
* returning a value ranging from 0 to $(PI).
*
* $(TABLE_SV
* $(TR $(TH x) $(TH acos(x)) $(TH invalid?))
* $(TR $(TD $(GT)1.0) $(TD $(NAN)) $(TD yes))
* $(TR $(TD $(LT)-1.0) $(TD $(NAN)) $(TD yes))
* $(TR $(TD $(NAN)) $(TD $(NAN)) $(TD yes))
* )
*/
real acos(real x) @safe pure nothrow
{
return atan2(sqrt(1-x*x), x);
}
/// ditto
double acos(double x) @safe pure nothrow { return acos(cast(real)x); }
/// ditto
float acos(float x) @safe pure nothrow { return acos(cast(real)x); }
unittest
{
assert(equalsDigit(acos(0.5), std.math.PI / 3, useDigits));
}
/***************
* Calculates the arc sine of x,
* returning a value ranging from -$(PI)/2 to $(PI)/2.
*
* $(TABLE_SV
* $(TR $(TH x) $(TH asin(x)) $(TH invalid?))
* $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) $(TD no))
* $(TR $(TD $(GT)1.0) $(TD $(NAN)) $(TD yes))
* $(TR $(TD $(LT)-1.0) $(TD $(NAN)) $(TD yes))
* )
*/
real asin(real x) @safe pure nothrow
{
return atan2(x, sqrt(1-x*x));
}
/// ditto
double asin(double x) @safe pure nothrow { return asin(cast(real)x); }
/// ditto
float asin(float x) @safe pure nothrow { return asin(cast(real)x); }
unittest
{
assert(equalsDigit(asin(0.5), PI / 6, useDigits));
}
/***************
* Calculates the arc tangent of x,
* returning a value ranging from -$(PI)/2 to $(PI)/2.
*
* $(TABLE_SV
* $(TR $(TH x) $(TH atan(x)) $(TH invalid?))
* $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) $(TD no))
* $(TR $(TD $(PLUSMN)$(INFIN)) $(TD $(NAN)) $(TD yes))
* )
*/
real atan(real x) @safe pure nothrow
{
version(InlineAsm_X86_Any)
{
return atan2(x, 1.0L);
}
else
{
// Coefficients for atan(x)
static immutable real[5] P = [
-5.0894116899623603312185E1L,
-9.9988763777265819915721E1L,
-6.3976888655834347413154E1L,
-1.4683508633175792446076E1L,
-8.6863818178092187535440E-1L,
];
static immutable real[6] Q = [
1.5268235069887081006606E2L,
3.9157570175111990631099E2L,
3.6144079386152023162701E2L,
1.4399096122250781605352E2L,
2.2981886733594175366172E1L,
1.0000000000000000000000E0L,
];
// tan(PI/8)
enum real TAN_PI_8 = 4.1421356237309504880169e-1L;
// tan(3 * PI/8)
enum real TAN3_PI_8 = 2.41421356237309504880169L;
// Special cases.
if (x == 0.0)
return x;
if (isInfinity(x))
return copysign(PI_2, x);
// Make argument positive but save the sign.
bool sign = false;
if (signbit(x))
{
sign = true;
x = -x;
}
// Range reduction.
real y;
if (x > TAN3_PI_8)
{
y = PI_2;
x = -(1.0 / x);
}
else if (x > TAN_PI_8)
{
y = PI_4;
x = (x - 1.0)/(x + 1.0);
}
else
y = 0.0;
// Rational form in x^^2.
real z = x * x;
y = y + (poly(z, P) / poly(z, Q)) * z * x + x;
return (sign) ? -y : y;
}
}
/// ditto
double atan(double x) @safe pure nothrow { return atan(cast(real)x); }
/// ditto
float atan(float x) @safe pure nothrow { return atan(cast(real)x); }
unittest
{
assert(equalsDigit(atan(std.math.sqrt(3.0)), PI / 3, useDigits));
}
/***************
* Calculates the arc tangent of y / x,
* returning a value ranging from -$(PI) to $(PI).
*
* $(TABLE_SV
* $(TR $(TH y) $(TH x) $(TH atan(y, x)))
* $(TR $(TD $(NAN)) $(TD anything) $(TD $(NAN)) )
* $(TR $(TD anything) $(TD $(NAN)) $(TD $(NAN)) )
* $(TR $(TD $(PLUSMN)0.0) $(TD $(GT)0.0) $(TD $(PLUSMN)0.0) )
* $(TR $(TD $(PLUSMN)0.0) $(TD +0.0) $(TD $(PLUSMN)0.0) )
* $(TR $(TD $(PLUSMN)0.0) $(TD $(LT)0.0) $(TD $(PLUSMN)$(PI)))
* $(TR $(TD $(PLUSMN)0.0) $(TD -0.0) $(TD $(PLUSMN)$(PI)))
* $(TR $(TD $(GT)0.0) $(TD $(PLUSMN)0.0) $(TD $(PI)/2) )
* $(TR $(TD $(LT)0.0) $(TD $(PLUSMN)0.0) $(TD -$(PI)/2) )
* $(TR $(TD $(GT)0.0) $(TD $(INFIN)) $(TD $(PLUSMN)0.0) )
* $(TR $(TD $(PLUSMN)$(INFIN)) $(TD anything) $(TD $(PLUSMN)$(PI)/2))
* $(TR $(TD $(GT)0.0) $(TD -$(INFIN)) $(TD $(PLUSMN)$(PI)) )
* $(TR $(TD $(PLUSMN)$(INFIN)) $(TD $(INFIN)) $(TD $(PLUSMN)$(PI)/4))
* $(TR $(TD $(PLUSMN)$(INFIN)) $(TD -$(INFIN)) $(TD $(PLUSMN)3$(PI)/4))
* )
*/
real atan2(real y, real x) @trusted pure nothrow
{
version(InlineAsm_X86_Any)
{
version (Win64)
{
asm {
naked;
fld real ptr [RDX]; // y
fld real ptr [RCX]; // x
fpatan;
ret;
}
}
else
{
asm {
fld y;
fld x;
fpatan;
}
}
}
else
{
// Special cases.
if (isNaN(x) || isNaN(y))
return real.nan;
if (y == 0.0)
{
if (x >= 0 && !signbit(x))
return copysign(0, y);
else
return copysign(PI, y);
}
if (x == 0.0)
return copysign(PI_2, y);
if (isInfinity(x))
{
if (signbit(x))
{
if (isInfinity(y))
return copysign(3*PI_4, y);
else
return copysign(PI, y);
}
else
{
if (isInfinity(y))
return copysign(PI_4, y);
else
return copysign(0.0, y);
}
}
if (isInfinity(y))
return copysign(PI_2, y);
// Call atan and determine the quadrant.
real z = atan(y / x);
if (signbit(x))
{
if (signbit(y))
z = z - PI;
else
z = z + PI;
}
if (z == 0.0)
return copysign(z, y);
return z;
}
}
/// ditto
double atan2(double y, double x) @safe pure nothrow
{
return atan2(cast(real)y, cast(real)x);
}
/// ditto
float atan2(float y, float x) @safe pure nothrow
{
return atan2(cast(real)y, cast(real)x);
}
unittest
{
assert(equalsDigit(atan2(1.0L, std.math.sqrt(3.0L)), PI / 6, useDigits));
}
/***********************************
* Calculates the hyperbolic cosine of x.
*
* $(TABLE_SV
* $(TR $(TH x) $(TH cosh(x)) $(TH invalid?))
* $(TR $(TD $(PLUSMN)$(INFIN)) $(TD $(PLUSMN)0.0) $(TD no) )
* )
*/
real cosh(real x) @safe pure nothrow
{
// cosh = (exp(x)+exp(-x))/2.
// The naive implementation works correctly.
real y = exp(x);
return (y + 1.0/y) * 0.5;
}
/// ditto
double cosh(double x) @safe pure nothrow { return cosh(cast(real)x); }
/// ditto
float cosh(float x) @safe pure nothrow { return cosh(cast(real)x); }
unittest
{
assert(equalsDigit(cosh(1.0), (E + 1.0 / E) / 2, useDigits));
}
/***********************************
* Calculates the hyperbolic sine of x.
*
* $(TABLE_SV
* $(TR $(TH x) $(TH sinh(x)) $(TH invalid?))
* $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) $(TD no))
* $(TR $(TD $(PLUSMN)$(INFIN)) $(TD $(PLUSMN)$(INFIN)) $(TD no))
* )
*/
real sinh(real x) @safe pure nothrow
{
// sinh(x) = (exp(x)-exp(-x))/2;
// Very large arguments could cause an overflow, but
// the maximum value of x for which exp(x) + exp(-x)) != exp(x)
// is x = 0.5 * (real.mant_dig) * LN2. // = 22.1807 for real80.
if (fabs(x) > real.mant_dig * LN2)
{
return copysign(0.5 * exp(fabs(x)), x);
}
real y = expm1(x);
return 0.5 * y / (y+1) * (y+2);
}
/// ditto
double sinh(double x) @safe pure nothrow { return sinh(cast(real)x); }
/// ditto
float sinh(float x) @safe pure nothrow { return sinh(cast(real)x); }
unittest
{
assert(equalsDigit(sinh(1.0), (E - 1.0 / E) / 2, useDigits));
}
/***********************************
* Calculates the hyperbolic tangent of x.
*
* $(TABLE_SV
* $(TR $(TH x) $(TH tanh(x)) $(TH invalid?))
* $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) $(TD no) )
* $(TR $(TD $(PLUSMN)$(INFIN)) $(TD $(PLUSMN)1.0) $(TD no))
* )
*/
real tanh(real x) @safe pure nothrow
{
// tanh(x) = (exp(x) - exp(-x))/(exp(x)+exp(-x))
if (fabs(x) > real.mant_dig * LN2)
{
return copysign(1, x);
}
real y = expm1(2*x);
return y / (y + 2);
}
/// ditto
double tanh(double x) @safe pure nothrow { return tanh(cast(real)x); }
/// ditto
float tanh(float x) @safe pure nothrow { return tanh(cast(real)x); }
unittest
{
assert(equalsDigit(tanh(1.0), sinh(1.0) / cosh(1.0), 15));
}
package:
/* Returns cosh(x) + I * sinh(x)
* Only one call to exp() is performed.
*/
creal coshisinh(real x) @safe pure nothrow
{
// See comments for cosh, sinh.
if (fabs(x) > real.mant_dig * LN2)
{
real y = exp(fabs(x));
return y * 0.5 + 0.5i * copysign(y, x);
}
else
{
real y = expm1(x);
return (y + 1.0 + 1.0/(y + 1.0)) * 0.5 + 0.5i * y / (y+1) * (y+2);
}
}
unittest
{
creal c = coshisinh(3.0L);
assert(c.re == cosh(3.0L));
assert(c.im == sinh(3.0L));
}
public:
/***********************************
* Calculates the inverse hyperbolic cosine of x.
*
* Mathematically, acosh(x) = log(x + sqrt( x*x - 1))
*
* $(TABLE_DOMRG
* $(DOMAIN 1..$(INFIN))
* $(RANGE 1..log(real.max), $(INFIN)) )
* $(TABLE_SV
* $(SVH x, acosh(x) )
* $(SV $(NAN), $(NAN) )
* $(SV $(LT)1, $(NAN) )
* $(SV 1, 0 )
* $(SV +$(INFIN),+$(INFIN))
* )
*/
real acosh(real x) @safe pure nothrow
{
if (x > 1/real.epsilon)
return LN2 + log(x);
else
return log(x + sqrt(x*x - 1));
}
/// ditto
double acosh(double x) @safe pure nothrow { return acosh(cast(real)x); }
/// ditto
float acosh(float x) @safe pure nothrow { return acosh(cast(real)x); }
unittest
{
assert(isNaN(acosh(0.9)));
assert(isNaN(acosh(real.nan)));
assert(acosh(1.0)==0.0);
assert(acosh(real.infinity) == real.infinity);
assert(isNaN(acosh(0.5)));
assert(equalsDigit(acosh(cosh(3.0)), 3, useDigits));
}
/***********************************
* Calculates the inverse hyperbolic sine of x.
*
* Mathematically,
* ---------------
* asinh(x) = log( x + sqrt( x*x + 1 )) // if x >= +0
* asinh(x) = -log(-x + sqrt( x*x + 1 )) // if x <= -0
* -------------
*
* $(TABLE_SV
* $(SVH x, asinh(x) )
* $(SV $(NAN), $(NAN) )
* $(SV $(PLUSMN)0, $(PLUSMN)0 )
* $(SV $(PLUSMN)$(INFIN),$(PLUSMN)$(INFIN))
* )
*/
real asinh(real x) @safe pure nothrow
{
return (fabs(x) > 1 / real.epsilon)
// beyond this point, x*x + 1 == x*x
? copysign(LN2 + log(fabs(x)), x)
// sqrt(x*x + 1) == 1 + x * x / ( 1 + sqrt(x*x + 1) )
: copysign(log1p(fabs(x) + x*x / (1 + sqrt(x*x + 1)) ), x);
}
/// ditto
double asinh(double x) @safe pure nothrow { return asinh(cast(real)x); }
/// ditto
float asinh(float x) @safe pure nothrow { return asinh(cast(real)x); }
unittest
{
assert(isIdentical(asinh(0.0), 0.0));
assert(isIdentical(asinh(-0.0), -0.0));
assert(asinh(real.infinity) == real.infinity);
assert(asinh(-real.infinity) == -real.infinity);
assert(isNaN(asinh(real.nan)));
assert(equalsDigit(asinh(sinh(3.0)), 3, useDigits));
}
/***********************************
* Calculates the inverse hyperbolic tangent of x,
* returning a value from ranging from -1 to 1.
*
* Mathematically, atanh(x) = log( (1+x)/(1-x) ) / 2
*
*
* $(TABLE_DOMRG
* $(DOMAIN -$(INFIN)..$(INFIN))
* $(RANGE -1..1) )
* $(TABLE_SV
* $(SVH x, acosh(x) )
* $(SV $(NAN), $(NAN) )
* $(SV $(PLUSMN)0, $(PLUSMN)0)
* $(SV -$(INFIN), -0)
* )
*/
real atanh(real x) @safe pure nothrow
{
// log( (1+x)/(1-x) ) == log ( 1 + (2*x)/(1-x) )
return 0.5 * log1p( 2 * x / (1 - x) );
}
/// ditto
double atanh(double x) @safe pure nothrow { return atanh(cast(real)x); }
/// ditto
float atanh(float x) @safe pure nothrow { return atanh(cast(real)x); }
unittest
{
assert(isIdentical(atanh(0.0), 0.0));
assert(isIdentical(atanh(-0.0),-0.0));
assert(isNaN(atanh(real.nan)));
assert(isNaN(atanh(-real.infinity)));
assert(atanh(0.0) == 0);
assert(equalsDigit(atanh(tanh(0.5L)), 0.5, useDigits));
}
/*****************************************
* Returns x rounded to a long value using the current rounding mode.
* If the integer value of x is
* greater than long.max, the result is
* indeterminate.
*/
long rndtol(real x) @safe pure nothrow; /* intrinsic */
/*****************************************
* Returns x rounded to a long value using the FE_TONEAREST rounding mode.
* If the integer value of x is
* greater than long.max, the result is
* indeterminate.
*/
extern (C) real rndtonl(real x);
/***************************************
* Compute square root of x.
*
* $(TABLE_SV
* $(TR $(TH x) $(TH sqrt(x)) $(TH invalid?))
* $(TR $(TD -0.0) $(TD -0.0) $(TD no))
* $(TR $(TD $(LT)0.0) $(TD $(NAN)) $(TD yes))
* $(TR $(TD +$(INFIN)) $(TD +$(INFIN)) $(TD no))
* )
*/
float sqrt(float x) @safe pure nothrow; /* intrinsic */
/// ditto
double sqrt(double x) @safe pure nothrow; /* intrinsic */
/// ditto
real sqrt(real x) @safe pure nothrow; /* intrinsic */
unittest
{
//ctfe
enum ZX80 = sqrt(7.0f);
enum ZX81 = sqrt(7.0);
enum ZX82 = sqrt(7.0L);
}
creal sqrt(creal z) @safe pure nothrow
{
creal c;
real x,y,w,r;
if (z == 0)
{
c = 0 + 0i;
}
else
{
real z_re = z.re;
real z_im = z.im;
x = fabs(z_re);
y = fabs(z_im);
if (x >= y)
{
r = y / x;
w = sqrt(x) * sqrt(0.5 * (1 + sqrt(1 + r * r)));
}
else
{
r = x / y;
w = sqrt(y) * sqrt(0.5 * (r + sqrt(1 + r * r)));
}
if (z_re >= 0)
{
c = w + (z_im / (w + w)) * 1.0i;
}
else
{
if (z_im < 0)
w = -w;
c = z_im / (w + w) + w * 1.0i;
}
}
return c;
}
/**
* Calculates e$(SUP x).
*
* $(TABLE_SV
* $(TR $(TH x) $(TH e$(SUP x)) )
* $(TR $(TD +$(INFIN)) $(TD +$(INFIN)) )
* $(TR $(TD -$(INFIN)) $(TD +0.0) )
* $(TR $(TD $(NAN)) $(TD $(NAN)) )
* )
*/
real exp(real x) @trusted pure nothrow
{
version(D_InlineAsm_X86)
{
// e^^x = 2^^(LOG2E*x)
// (This is valid because the overflow & underflow limits for exp
// and exp2 are so similar).
return exp2(LOG2E*x);
}
else version(D_InlineAsm_X86_64)
{
// e^^x = 2^^(LOG2E*x)
// (This is valid because the overflow & underflow limits for exp
// and exp2 are so similar).
return exp2(LOG2E*x);
}
else
{
// Coefficients for exp(x)
static immutable real[3] P = [
9.9999999999999999991025E-1L,
3.0299440770744196129956E-2L,
1.2617719307481059087798E-4L,
];
static immutable real[4] Q = [
2.0000000000000000000897E0L,
2.2726554820815502876593E-1L,
2.5244834034968410419224E-3L,
3.0019850513866445504159E-6L,
];
// C1 + C2 = LN2.
enum real C1 = 6.9314575195312500000000E-1L;
enum real C2 = 1.428606820309417232121458176568075500134E-6L;
// Overflow and Underflow limits.
enum real OF = 1.1356523406294143949492E4L;
enum real UF = -1.1432769596155737933527E4L;
// Special cases.
if (isNaN(x))
return x;
if (x > OF)
return real.infinity;
if (x < UF)
return 0.0;
// Express: e^^x = e^^g * 2^^n
// = e^^g * e^^(n * LOG2E)
// = e^^(g + n * LOG2E)
int n = cast(int)floor(LOG2E * x + 0.5);
x -= n * C1;
x -= n * C2;
// Rational approximation for exponential of the fractional part:
// e^^x = 1 + 2x P(x^^2) / (Q(x^^2) - P(x^^2))
real xx = x * x;
real px = x * poly(xx, P);
x = px / (poly(xx, Q) - px);
x = 1.0 + ldexp(x, 1);
// Scale by power of 2.
x = ldexp(x, n);
return x;
}
}
/// ditto
double exp(double x) @safe pure nothrow { return exp(cast(real)x); }
/// ditto
float exp(float x) @safe pure nothrow { return exp(cast(real)x); }
unittest
{
assert(equalsDigit(exp(3.0L), E * E * E, useDigits));
}
/**
* Calculates the value of the natural logarithm base (e)
* raised to the power of x, minus 1.
*
* For very small x, expm1(x) is more accurate
* than exp(x)-1.
*
* $(TABLE_SV
* $(TR $(TH x) $(TH e$(SUP x)-1) )
* $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) )
* $(TR $(TD +$(INFIN)) $(TD +$(INFIN)) )
* $(TR $(TD -$(INFIN)) $(TD -1.0) )
* $(TR $(TD $(NAN)) $(TD $(NAN)) )
* )
*/
real expm1(real x) @trusted pure nothrow
{
version(D_InlineAsm_X86)
{
enum PARAMSIZE = (real.sizeof+3)&(0xFFFF_FFFC); // always a multiple of 4
asm
{
/* expm1() for x87 80-bit reals, IEEE754-2008 conformant.
* Author: Don Clugston.
*
* expm1(x) = 2^^(rndint(y))* 2^^(y-rndint(y)) - 1 where y = LN2*x.
* = 2rndy * 2ym1 + 2rndy - 1, where 2rndy = 2^^(rndint(y))
* and 2ym1 = (2^^(y-rndint(y))-1).
* If 2rndy < 0.5*real.epsilon, result is -1.
* Implementation is otherwise the same as for exp2()
*/
naked;
fld real ptr [ESP+4] ; // x
mov AX, [ESP+4+8]; // AX = exponent and sign
sub ESP, 12+8; // Create scratch space on the stack
// [ESP,ESP+2] = scratchint
// [ESP+4..+6, +8..+10, +10] = scratchreal
// set scratchreal mantissa = 1.0
mov dword ptr [ESP+8], 0;
mov dword ptr [ESP+8+4], 0x80000000;
and AX, 0x7FFF; // drop sign bit
cmp AX, 0x401D; // avoid InvalidException in fist
jae L_extreme;
fldl2e;
fmulp ST(1), ST; // y = x*log2(e)
fist dword ptr [ESP]; // scratchint = rndint(y)
fisub dword ptr [ESP]; // y - rndint(y)
// and now set scratchreal exponent
mov EAX, [ESP];
add EAX, 0x3fff;
jle short L_largenegative;
cmp EAX,0x8000;
jge short L_largepositive;
mov [ESP+8+8],AX;
f2xm1; // 2ym1 = 2^^(y-rndint(y)) -1
fld real ptr [ESP+8] ; // 2rndy = 2^^rndint(y)
fmul ST(1), ST; // ST=2rndy, ST(1)=2rndy*2ym1
fld1;
fsubp ST(1), ST; // ST = 2rndy-1, ST(1) = 2rndy * 2ym1 - 1
faddp ST(1), ST; // ST = 2rndy * 2ym1 + 2rndy - 1
add ESP,12+8;
ret PARAMSIZE;
L_extreme: // Extreme exponent. X is very large positive, very
// large negative, infinity, or NaN.
fxam;
fstsw AX;
test AX, 0x0400; // NaN_or_zero, but we already know x!=0
jz L_was_nan; // if x is NaN, returns x
test AX, 0x0200;
jnz L_largenegative;
L_largepositive:
// Set scratchreal = real.max.
// squaring it will create infinity, and set overflow flag.
mov word ptr [ESP+8+8], 0x7FFE;
fstp ST(0);
fld real ptr [ESP+8]; // load scratchreal
fmul ST(0), ST; // square it, to create havoc!
L_was_nan:
add ESP,12+8;
ret PARAMSIZE;
L_largenegative:
fstp ST(0);
fld1;
fchs; // return -1. Underflow flag is not set.
add ESP,12+8;
ret PARAMSIZE;
}
}
else version(D_InlineAsm_X86_64)
{
asm
{
naked;
}
version (Win64)
{
asm
{
fld real ptr [RCX]; // x
mov AX,[RCX+8]; // AX = exponent and sign
}
}
else
{
asm
{
fld real ptr [RSP+8]; // x
mov AX,[RSP+8+8]; // AX = exponent and sign
}
}
asm
{
/* expm1() for x87 80-bit reals, IEEE754-2008 conformant.
* Author: Don Clugston.
*
* expm1(x) = 2^(rndint(y))* 2^(y-rndint(y)) - 1 where y = LN2*x.
* = 2rndy * 2ym1 + 2rndy - 1, where 2rndy = 2^(rndint(y))
* and 2ym1 = (2^(y-rndint(y))-1).
* If 2rndy < 0.5*real.epsilon, result is -1.
* Implementation is otherwise the same as for exp2()
*/
sub RSP, 24; // Create scratch space on the stack
// [RSP,RSP+2] = scratchint
// [RSP+4..+6, +8..+10, +10] = scratchreal
// set scratchreal mantissa = 1.0
mov dword ptr [RSP+8], 0;
mov dword ptr [RSP+8+4], 0x80000000;
and AX, 0x7FFF; // drop sign bit
cmp AX, 0x401D; // avoid InvalidException in fist
jae L_extreme;
fldl2e;
fmul ; // y = x*log2(e)
fist dword ptr [RSP]; // scratchint = rndint(y)
fisub dword ptr [RSP]; // y - rndint(y)
// and now set scratchreal exponent
mov EAX, [RSP];
add EAX, 0x3fff;
jle short L_largenegative;
cmp EAX,0x8000;
jge short L_largepositive;
mov [RSP+8+8],AX;
f2xm1; // 2^(y-rndint(y)) -1
fld real ptr [RSP+8] ; // 2^rndint(y)
fmul ST(1), ST;
fld1;
fsubp ST(1), ST;
fadd;
add RSP,24;
ret;
L_extreme: // Extreme exponent. X is very large positive, very
// large negative, infinity, or NaN.
fxam;
fstsw AX;
test AX, 0x0400; // NaN_or_zero, but we already know x!=0
jz L_was_nan; // if x is NaN, returns x
test AX, 0x0200;
jnz L_largenegative;
L_largepositive:
// Set scratchreal = real.max.
// squaring it will create infinity, and set overflow flag.
mov word ptr [RSP+8+8], 0x7FFE;
fstp ST(0);
fld real ptr [RSP+8]; // load scratchreal
fmul ST(0), ST; // square it, to create havoc!
L_was_nan:
add RSP,24;
ret;
L_largenegative:
fstp ST(0);
fld1;
fchs; // return -1. Underflow flag is not set.
add RSP,24;
ret;
}
}
else
{
// Coefficients for exp(x) - 1
static immutable real[5] P = [
-1.586135578666346600772998894928250240826E4L,
2.642771505685952966904660652518429479531E3L,
-3.423199068835684263987132888286791620673E2L,
1.800826371455042224581246202420972737840E1L,
-5.238523121205561042771939008061958820811E-1L,
];
static immutable real[6] Q = [
-9.516813471998079611319047060563358064497E4L,
3.964866271411091674556850458227710004570E4L,
-7.207678383830091850230366618190187434796E3L,
7.206038318724600171970199625081491823079E2L,
-4.002027679107076077238836622982900945173E1L,
1.000000000000000000000000000000000000000E0L,
];
// C1 + C2 = LN2.
enum real C1 = 6.9314575195312500000000E-1L;
enum real C2 = 1.4286068203094172321215E-6L;
// Overflow and Underflow limits.
enum real OF = 1.1356523406294143949492E4L;
enum real UF = -4.5054566736396445112120088E1L;
// Special cases.
if (x > OF)
return real.infinity;
if (x == 0.0)
return x;
if (x < UF)
return -1.0;
// Express x = LN2 (n + remainder), remainder not exceeding 1/2.
int n = cast(int)floor(0.5 + x / LN2);
x -= n * C1;
x -= n * C2;
// Rational approximation:
// exp(x) - 1 = x + 0.5 x^^2 + x^^3 P(x) / Q(x)
real px = x * poly(x, P);
real qx = poly(x, Q);
real xx = x * x;
qx = x + (0.5 * xx + xx * px / qx);
// We have qx = exp(remainder LN2) - 1, so:
// exp(x) - 1 = 2^^n (qx + 1) - 1 = 2^^n qx + 2^^n - 1.
px = ldexp(1.0, n);
x = px * qx + (px - 1.0);
return x;
}
}
/**
* Calculates 2$(SUP x).
*
* $(TABLE_SV
* $(TR $(TH x) $(TH exp2(x)) )
* $(TR $(TD +$(INFIN)) $(TD +$(INFIN)) )
* $(TR $(TD -$(INFIN)) $(TD +0.0) )
* $(TR $(TD $(NAN)) $(TD $(NAN)) )
* )
*/
real exp2(real x) @trusted pure nothrow
{
version(D_InlineAsm_X86)
{
enum PARAMSIZE = (real.sizeof+3)&(0xFFFF_FFFC); // always a multiple of 4
asm
{
/* exp2() for x87 80-bit reals, IEEE754-2008 conformant.
* Author: Don Clugston.
*
* exp2(x) = 2^^(rndint(x))* 2^^(y-rndint(x))
* The trick for high performance is to avoid the fscale(28cycles on core2),
* frndint(19 cycles), leaving f2xm1(19 cycles) as the only slow instruction.
*
* We can do frndint by using fist. BUT we can't use it for huge numbers,
* because it will set the Invalid Operation flag if overflow or NaN occurs.
* Fortunately, whenever this happens the result would be zero or infinity.
*
* We can perform fscale by directly poking into the exponent. BUT this doesn't
* work for the (very rare) cases where the result is subnormal. So we fall back
* to the slow method in that case.
*/
naked;
fld real ptr [ESP+4] ; // x
mov AX, [ESP+4+8]; // AX = exponent and sign
sub ESP, 12+8; // Create scratch space on the stack
// [ESP,ESP+2] = scratchint
// [ESP+4..+6, +8..+10, +10] = scratchreal
// set scratchreal mantissa = 1.0
mov dword ptr [ESP+8], 0;
mov dword ptr [ESP+8+4], 0x80000000;
and AX, 0x7FFF; // drop sign bit
cmp AX, 0x401D; // avoid InvalidException in fist
jae L_extreme;
fist dword ptr [ESP]; // scratchint = rndint(x)
fisub dword ptr [ESP]; // x - rndint(x)
// and now set scratchreal exponent
mov EAX, [ESP];
add EAX, 0x3fff;
jle short L_subnormal;
cmp EAX,0x8000;
jge short L_overflow;
mov [ESP+8+8],AX;
L_normal:
f2xm1;
fld1;
faddp ST(1), ST; // 2^^(x-rndint(x))
fld real ptr [ESP+8] ; // 2^^rndint(x)
add ESP,12+8;
fmulp ST(1), ST;
ret PARAMSIZE;
L_subnormal:
// Result will be subnormal.
// In this rare case, the simple poking method doesn't work.
// The speed doesn't matter, so use the slow fscale method.
fild dword ptr [ESP]; // scratchint
fld1;
fscale;
fstp real ptr [ESP+8]; // scratchreal = 2^^scratchint
fstp ST(0); // drop scratchint
jmp L_normal;
L_extreme: // Extreme exponent. X is very large positive, very
// large negative, infinity, or NaN.
fxam;
fstsw AX;
test AX, 0x0400; // NaN_or_zero, but we already know x!=0
jz L_was_nan; // if x is NaN, returns x
// set scratchreal = real.min_normal
// squaring it will return 0, setting underflow flag
mov word ptr [ESP+8+8], 1;
test AX, 0x0200;
jnz L_waslargenegative;
L_overflow:
// Set scratchreal = real.max.
// squaring it will create infinity, and set overflow flag.
mov word ptr [ESP+8+8], 0x7FFE;
L_waslargenegative:
fstp ST(0);
fld real ptr [ESP+8]; // load scratchreal
fmul ST(0), ST; // square it, to create havoc!
L_was_nan:
add ESP,12+8;
ret PARAMSIZE;
}
}
else version(D_InlineAsm_X86_64)
{
asm
{
naked;
}
version (Win64)
{
asm
{
fld real ptr [RCX]; // x
mov AX,[RCX+8]; // AX = exponent and sign
}
}
else
{
asm
{
fld real ptr [RSP+8]; // x
mov AX,[RSP+8+8]; // AX = exponent and sign
}
}
asm
{
/* exp2() for x87 80-bit reals, IEEE754-2008 conformant.
* Author: Don Clugston.
*
* exp2(x) = 2^(rndint(x))* 2^(y-rndint(x))
* The trick for high performance is to avoid the fscale(28cycles on core2),
* frndint(19 cycles), leaving f2xm1(19 cycles) as the only slow instruction.
*
* We can do frndint by using fist. BUT we can't use it for huge numbers,
* because it will set the Invalid Operation flag is overflow or NaN occurs.
* Fortunately, whenever this happens the result would be zero or infinity.
*
* We can perform fscale by directly poking into the exponent. BUT this doesn't
* work for the (very rare) cases where the result is subnormal. So we fall back
* to the slow method in that case.
*/
sub RSP, 24; // Create scratch space on the stack
// [RSP,RSP+2] = scratchint
// [RSP+4..+6, +8..+10, +10] = scratchreal
// set scratchreal mantissa = 1.0
mov dword ptr [RSP+8], 0;
mov dword ptr [RSP+8+4], 0x80000000;
and AX, 0x7FFF; // drop sign bit
cmp AX, 0x401D; // avoid InvalidException in fist
jae L_extreme;
fist dword ptr [RSP]; // scratchint = rndint(x)
fisub dword ptr [RSP]; // x - rndint(x)
// and now set scratchreal exponent
mov EAX, [RSP];
add EAX, 0x3fff;
jle short L_subnormal;
cmp EAX,0x8000;
jge short L_overflow;
mov [RSP+8+8],AX;
L_normal:
f2xm1;
fld1;
fadd; // 2^(x-rndint(x))
fld real ptr [RSP+8] ; // 2^rndint(x)
add RSP,24;
fmulp ST(1), ST;
ret;
L_subnormal:
// Result will be subnormal.
// In this rare case, the simple poking method doesn't work.
// The speed doesn't matter, so use the slow fscale method.
fild dword ptr [RSP]; // scratchint
fld1;
fscale;
fstp real ptr [RSP+8]; // scratchreal = 2^scratchint
fstp ST(0); // drop scratchint
jmp L_normal;
L_extreme: // Extreme exponent. X is very large positive, very
// large negative, infinity, or NaN.
fxam;
fstsw AX;
test AX, 0x0400; // NaN_or_zero, but we already know x!=0
jz L_was_nan; // if x is NaN, returns x
// set scratchreal = real.min
// squaring it will return 0, setting underflow flag
mov word ptr [RSP+8+8], 1;
test AX, 0x0200;
jnz L_waslargenegative;
L_overflow:
// Set scratchreal = real.max.
// squaring it will create infinity, and set overflow flag.
mov word ptr [RSP+8+8], 0x7FFE;
L_waslargenegative:
fstp ST(0);
fld real ptr [RSP+8]; // load scratchreal
fmul ST(0), ST; // square it, to create havoc!
L_was_nan:
add RSP,24;
ret;
}
}
else
{
// Coefficients for exp2(x)
static immutable real[3] P = [
2.0803843631901852422887E6L,
3.0286971917562792508623E4L,
6.0614853552242266094567E1L,
];
static immutable real[4] Q = [
6.0027204078348487957118E6L,
3.2772515434906797273099E5L,
1.7492876999891839021063E3L,
1.0000000000000000000000E0L,
];
// Overflow and Underflow limits.
enum real OF = 16384.0L;
enum real UF = -16382.0L;
// Special cases.
if (isNaN(x))
return x;
if (x > OF)
return real.infinity;
if (x < UF)
return 0.0;
// Separate into integer and fractional parts.
int n = cast(int)floor(x + 0.5);
x -= n;
// Rational approximation:
// exp2(x) = 1.0 + 2x P(x^^2) / (Q(x^^2) - P(x^^2))
real xx = x * x;
real px = x * poly(xx, P);
x = px / (poly(xx, Q) - px);
x = 1.0 + ldexp(x, 1);
// Scale by power of 2.
x = ldexp(x, n);
return x;
}
}
unittest
{
assert(feqrel(exp2(0.5L), SQRT2) >= real.mant_dig -1);
assert(exp2(8.0L) == 256.0);
assert(exp2(-9.0L)== 1.0L/512.0);
version(Win64) {} else // aexp2/exp2f/exp2l not implemented
{
assert( core.stdc.math.exp2f(0.0f) == 1 );
assert( core.stdc.math.exp2 (0.0) == 1 );
assert( core.stdc.math.exp2l(0.0L) == 1 );
}
}
unittest
{
FloatingPointControl ctrl;
if(FloatingPointControl.hasExceptionTraps)
ctrl.disableExceptions(FloatingPointControl.allExceptions);
ctrl.rounding = FloatingPointControl.roundToNearest;
// @@BUG@@: Non-immutable array literals are ridiculous.
// Note that these are only valid for 80-bit reals: overflow will be different for 64-bit reals.
static const real [2][] exptestpoints =
[ // x, exp(x)
[1.0L, E ],
[0.5L, 0x1.A612_98E1_E069_BC97p+0L ],
[3.0L, E*E*E ],
[0x1.1p13L, 0x1.29aeffefc8ec645p+12557L ], // near overflow
[-0x1.18p13L, 0x1.5e4bf54b4806db9p-12927L ], // near underflow
[-0x1.625p13L, 0x1.a6bd68a39d11f35cp-16358L],
[-0x1p30L, 0 ], // underflow - subnormal
[-0x1.62DAFp13L, 0x1.96c53d30277021dp-16383L ],
[-0x1.643p13L, 0x1p-16444L ],
[-0x1.645p13L, 0 ], // underflow to zero
[0x1p80L, real.infinity ], // far overflow
[real.infinity, real.infinity ],
[0x1.7p13L, real.infinity ] // close overflow
];
real x;
IeeeFlags f;
for (int i=0; i<exptestpoints.length;++i)
{
resetIeeeFlags();
x = exp(exptestpoints[i][0]);
f = ieeeFlags;
assert(x == exptestpoints[i][1]);
// Check the overflow bit
assert(f.overflow == (fabs(x) == real.infinity));
// Check the underflow bit
assert(f.underflow == (fabs(x) < real.min_normal));
// Invalid and div by zero shouldn't be affected.
assert(!f.invalid);
assert(!f.divByZero);
}
// Ideally, exp(0) would not set the inexact flag.
// Unfortunately, fldl2e sets it!
// So it's not realistic to avoid setting it.
assert(exp(0.0L) == 1.0);
// NaN propagation. Doesn't set flags, bcos was already NaN.
resetIeeeFlags();
x = exp(real.nan);
f = ieeeFlags;
assert(isIdentical(abs(x), real.nan));
assert(f.flags == 0);
resetIeeeFlags();
x = exp(-real.nan);
f = ieeeFlags;
assert(isIdentical(abs(x), real.nan));
assert(f.flags == 0);
x = exp(NaN(0x123));
assert(isIdentical(x, NaN(0x123)));
// High resolution test
assert(exp(0.5L) == 0x1.A612_98E1_E069_BC97_2DFE_FAB6D_33Fp+0L);
}
/**
* Calculate cos(y) + i sin(y).
*
* On many CPUs (such as x86), this is a very efficient operation;
* almost twice as fast as calculating sin(y) and cos(y) separately,
* and is the preferred method when both are required.
*/
creal expi(real y) @trusted pure nothrow
{
version(InlineAsm_X86_Any)
{
version (Win64)
{
asm
{
naked;
fld real ptr [ECX];
fsincos;
fxch ST(1), ST(0);
ret;
}
}
else
{
asm
{
fld y;
fsincos;
fxch ST(1), ST(0);
}
}
}
else
{
return cos(y) + sin(y)*1i;
}
}
unittest
{
assert(expi(1.3e5L) == cos(1.3e5L) + sin(1.3e5L) * 1i);
assert(expi(0.0L) == 1L + 0.0Li);
}
/*********************************************************************
* Separate floating point value into significand and exponent.
*
* Returns:
* Calculate and return $(I x) and $(I exp) such that
* value =$(I x)*2$(SUP exp) and
* .5 $(LT)= |$(I x)| $(LT) 1.0
*
* $(I x) has same sign as value.
*
* $(TABLE_SV
* $(TR $(TH value) $(TH returns) $(TH exp))
* $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) $(TD 0))
* $(TR $(TD +$(INFIN)) $(TD +$(INFIN)) $(TD int.max))
* $(TR $(TD -$(INFIN)) $(TD -$(INFIN)) $(TD int.min))
* $(TR $(TD $(PLUSMN)$(NAN)) $(TD $(PLUSMN)$(NAN)) $(TD int.min))
* )
*/
real frexp(real value, out int exp) @trusted pure nothrow
{
ushort* vu = cast(ushort*)&value;
long* vl = cast(long*)&value;
int ex;
alias F = floatTraits!(real);
ex = vu[F.EXPPOS_SHORT] & F.EXPMASK;
static if (real.mant_dig == 64) // real80
{
if (ex)
{ // If exponent is non-zero
if (ex == F.EXPMASK) // infinity or NaN
{
if (*vl & 0x7FFF_FFFF_FFFF_FFFF) // NaN
{
*vl |= 0xC000_0000_0000_0000; // convert NaNS to NaNQ
exp = int.min;
}
else if (vu[F.EXPPOS_SHORT] & 0x8000) // negative infinity
exp = int.min;
else // positive infinity
exp = int.max;
}
else
{
exp = ex - F.EXPBIAS;
vu[F.EXPPOS_SHORT] = (0x8000 & vu[F.EXPPOS_SHORT]) | 0x3FFE;
}
}
else if (!*vl)
{
// value is +-0.0
exp = 0;
}
else
{
// subnormal
value *= F.RECIP_EPSILON;
ex = vu[F.EXPPOS_SHORT] & F.EXPMASK;
exp = ex - F.EXPBIAS - real.mant_dig + 1;
vu[F.EXPPOS_SHORT] = (0x8000 & vu[F.EXPPOS_SHORT]) | 0x3FFE;
}
return value;
}
else static if (real.mant_dig == 113) // quadruple
{
if (ex) // If exponent is non-zero
{
if (ex == F.EXPMASK)
{ // infinity or NaN
if (vl[MANTISSA_LSB] |
( vl[MANTISSA_MSB] & 0x0000_FFFF_FFFF_FFFF)) // NaN
{
// convert NaNS to NaNQ
vl[MANTISSA_MSB] |= 0x0000_8000_0000_0000;
exp = int.min;
}
else if (vu[F.EXPPOS_SHORT] & 0x8000) // negative infinity
exp = int.min;
else // positive infinity
exp = int.max;
}
else
{
exp = ex - F.EXPBIAS;
vu[F.EXPPOS_SHORT] =
cast(ushort)((0x8000 & vu[F.EXPPOS_SHORT]) | 0x3FFE);
}
}
else if ((vl[MANTISSA_LSB]
|(vl[MANTISSA_MSB] & 0x0000_FFFF_FFFF_FFFF)) == 0)
{
// value is +-0.0
exp = 0;
}
else
{
// subnormal
value *= F.RECIP_EPSILON;
ex = vu[F.EXPPOS_SHORT] & F.EXPMASK;
exp = ex - F.EXPBIAS - real.mant_dig + 1;
vu[F.EXPPOS_SHORT] =
cast(ushort)((0x8000 & vu[F.EXPPOS_SHORT]) | 0x3FFE);
}
return value;
}
else static if (real.mant_dig==53) // real is double
{
if (ex) // If exponent is non-zero
{
if (ex == F.EXPMASK) // infinity or NaN
{
if (*vl == 0x7FF0_0000_0000_0000) // positive infinity
{
exp = int.max;
}
else if (*vl == 0xFFF0_0000_0000_0000) // negative infinity
exp = int.min;
else
{ // NaN
*vl |= 0x0008_0000_0000_0000; // convert NaNS to NaNQ
exp = int.min;
}
}
else
{
exp = (ex - F.EXPBIAS) >> 4;
vu[F.EXPPOS_SHORT] = cast(ushort)((0x800F & vu[F.EXPPOS_SHORT]) | 0x3FE0);
}
}
else if (!(*vl & 0x7FFF_FFFF_FFFF_FFFF))
{
// value is +-0.0
exp = 0;
}
else
{
// subnormal
value *= F.RECIP_EPSILON;
ex = vu[F.EXPPOS_SHORT] & F.EXPMASK;
exp = ((ex - F.EXPBIAS)>> 4) - real.mant_dig + 1;
vu[F.EXPPOS_SHORT] =
cast(ushort)((0x8000 & vu[F.EXPPOS_SHORT]) | 0x3FE0);
}
return value;
}
else // static if (real.mant_dig==106) // real is doubledouble
{
assert (0, "frexp not implemented");
}
}
unittest
{
static real[3][] vals = // x,frexp,exp
[
[0.0, 0.0, 0],
[-0.0, -0.0, 0],
[1.0, .5, 1],
[-1.0, -.5, 1],
[2.0, .5, 2],
[double.min_normal/2.0, .5, -1022],
[real.infinity,real.infinity,int.max],
[-real.infinity,-real.infinity,int.min],
[real.nan,real.nan,int.min],
[-real.nan,-real.nan,int.min],
];
int i;
for (i = 0; i < vals.length; i++)
{
real x = vals[i][0];
real e = vals[i][1];
int exp = cast(int)vals[i][2];
int eptr;
real v = frexp(x, eptr);
assert(isIdentical(e, v));
assert(exp == eptr);
}
static if (real.mant_dig == 64)
{
static real[3][] extendedvals = [ // x,frexp,exp
[0x1.a5f1c2eb3fe4efp+73L, 0x1.A5F1C2EB3FE4EFp-1L, 74], // normal
[0x1.fa01712e8f0471ap-1064L, 0x1.fa01712e8f0471ap-1L, -1063],
[real.min_normal, .5, -16381],
[real.min_normal/2.0L, .5, -16382] // subnormal
];
for (i = 0; i < extendedvals.length; i++)
{
real x = extendedvals[i][0];
real e = extendedvals[i][1];
int exp = cast(int)extendedvals[i][2];
int eptr;
real v = frexp(x, eptr);
assert(isIdentical(e, v));
assert(exp == eptr);
}
}
}
unittest
{
int exp;
real mantissa = frexp(123.456, exp);
assert(equalsDigit(mantissa * pow(2.0L, cast(real)exp), 123.456, 19));
assert(frexp(-real.nan, exp) && exp == int.min);
assert(frexp(real.nan, exp) && exp == int.min);
assert(frexp(-real.infinity, exp) == -real.infinity && exp == int.min);
assert(frexp(real.infinity, exp) == real.infinity && exp == int.max);
assert(frexp(-0.0, exp) == -0.0 && exp == 0);
assert(frexp(0.0, exp) == 0.0 && exp == 0);
}
/******************************************
* Extracts the exponent of x as a signed integral value.
*
* If x is not a special value, the result is the same as
* $(D cast(int)logb(x)).
*
* $(TABLE_SV
* $(TR $(TH x) $(TH ilogb(x)) $(TH Range error?))
* $(TR $(TD 0) $(TD FP_ILOGB0) $(TD yes))
* $(TR $(TD $(PLUSMN)$(INFIN)) $(TD int.max) $(TD no))
* $(TR $(TD $(NAN)) $(TD FP_ILOGBNAN) $(TD no))
* )
*/
int ilogb(real x) @trusted nothrow
{
version (Win64)
{
asm
{
naked ;
fld real ptr [RCX] ;
fxam ;
fstsw AX ;
and AH,0x45 ;
cmp AH,0x40 ;
jz Lzeronan ;
cmp AH,5 ;
jz Linfinity ;
cmp AH,1 ;
jz Lzeronan ;
fxtract ;
fstp ST(0) ;
fistp dword ptr 8[RSP] ;
mov EAX,8[RSP] ;
ret ;
Lzeronan:
mov EAX,0x80000000 ;
fstp ST(0) ;
ret ;
Linfinity:
mov EAX,0x7FFFFFFF ;
fstp ST(0) ;
ret ;
}
}
else
return core.stdc.math.ilogbl(x);
}
alias FP_ILOGB0 = core.stdc.math.FP_ILOGB0;
alias FP_ILOGBNAN = core.stdc.math.FP_ILOGBNAN;
/*******************************************
* Compute n * 2$(SUP exp)
* References: frexp
*/
real ldexp(real n, int exp) @safe pure nothrow; /* intrinsic */
unittest
{
static if(real.mant_dig == 64)
{
assert(ldexp(1, -16384) == 0x1p-16384L);
assert(ldexp(1, -16382) == 0x1p-16382L);
int x;
real n = frexp(0x1p-16384L, x);
assert(n==0.5L);
assert(x==-16383);
assert(ldexp(n, x)==0x1p-16384L);
}
else static if(real.mant_dig == 53)
{
assert(ldexp(1, -1024) == 0x1p-1024L);
assert(ldexp(1, -1022) == 0x1p-1022L);
int x;
real n = frexp(0x1p-1024L, x);
assert(n==0.5L);
assert(x==-1023);
assert(ldexp(n, x)==0x1p-1024L);
}
else static assert(false, "Floating point type real not supported");
}
unittest
{
static real[3][] vals = // value,exp,ldexp
[
[ 0, 0, 0],
[ 1, 0, 1],
[ -1, 0, -1],
[ 1, 1, 2],
[ 123, 10, 125952],
[ real.max, int.max, real.infinity],
[ real.max, -int.max, 0],
[ real.min_normal, -int.max, 0],
];
int i;
for (i = 0; i < vals.length; i++)
{
real x = vals[i][0];
int exp = cast(int)vals[i][1];
real z = vals[i][2];
real l = ldexp(x, exp);
assert(equalsDigit(z, l, 7));
}
}
unittest
{
real r;
r = ldexp(3.0L, 3);
assert(r == 24);
r = ldexp(cast(real) 3.0, cast(int) 3);
assert(r == 24);
real n = 3.0;
int exp = 3;
r = ldexp(n, exp);
assert(r == 24);
}
/**************************************
* Calculate the natural logarithm of x.
*
* $(TABLE_SV
* $(TR $(TH x) $(TH log(x)) $(TH divide by 0?) $(TH invalid?))
* $(TR $(TD $(PLUSMN)0.0) $(TD -$(INFIN)) $(TD yes) $(TD no))
* $(TR $(TD $(LT)0.0) $(TD $(NAN)) $(TD no) $(TD yes))
* $(TR $(TD +$(INFIN)) $(TD +$(INFIN)) $(TD no) $(TD no))
* )
*/
real log(real x) @safe pure nothrow
{
version (INLINE_YL2X)
return yl2x(x, LN2);
else
{
// Coefficients for log(1 + x)
static immutable real[7] P = [
2.0039553499201281259648E1L,
5.7112963590585538103336E1L,
6.0949667980987787057556E1L,
2.9911919328553073277375E1L,
6.5787325942061044846969E0L,
4.9854102823193375972212E-1L,
4.5270000862445199635215E-5L,
];
static immutable real[7] Q = [
6.0118660497603843919306E1L,
2.1642788614495947685003E2L,
3.0909872225312059774938E2L,
2.2176239823732856465394E2L,
8.3047565967967209469434E1L,
1.5062909083469192043167E1L,
1.0000000000000000000000E0L,
];
// Coefficients for log(x)
static immutable real[4] R = [
-3.5717684488096787370998E1L,
1.0777257190312272158094E1L,
-7.1990767473014147232598E-1L,
1.9757429581415468984296E-3L,
];
static immutable real[4] S = [
-4.2861221385716144629696E2L,
1.9361891836232102174846E2L,
-2.6201045551331104417768E1L,
1.0000000000000000000000E0L,
];
// C1 + C2 = LN2.
enum real C1 = 6.9314575195312500000000E-1L;
enum real C2 = 1.4286068203094172321215E-6L;
// Special cases.
if (isNaN(x))
return x;
if (isInfinity(x) && !signbit(x))
return x;
if (x == 0.0)
return -real.infinity;
if (x < 0.0)
return real.nan;
// Separate mantissa from exponent.
// Note, frexp is used so that denormal numbers will be handled properly.
real y, z;
int exp;
x = frexp(x, exp);
// Logarithm using log(x) = z + z^^3 P(z) / Q(z),
// where z = 2(x - 1)/(x + 1)
if((exp > 2) || (exp < -2))
{
if(x < SQRT1_2)
{ // 2(2x - 1)/(2x + 1)
exp -= 1;
z = x - 0.5;
y = 0.5 * z + 0.5;
}
else
{ // 2(x - 1)/(x + 1)
z = x - 0.5;
z -= 0.5;
y = 0.5 * x + 0.5;
}
x = z / y;
z = x * x;
z = x * (z * poly(z, R) / poly(z, S));
z += exp * C2;
z += x;
z += exp * C1;
return z;
}
// Logarithm using log(1 + x) = x - .5x^^2 + x^^3 P(x) / Q(x)
if (x < SQRT1_2)
{ // 2x - 1
exp -= 1;
x = ldexp(x, 1) - 1.0;
}
else
{
x = x - 1.0;
}
z = x * x;
y = x * (z * poly(x, P) / poly(x, Q));
y += exp * C2;
z = y - ldexp(z, -1);
// Note, the sum of above terms does not exceed x/4,
// so it contributes at most about 1/4 lsb to the error.
z += x;
z += exp * C1;
return z;
}
}
unittest
{
assert(log(E) == 1);
}
/**************************************
* Calculate the base-10 logarithm of x.
*
* $(TABLE_SV
* $(TR $(TH x) $(TH log10(x)) $(TH divide by 0?) $(TH invalid?))
* $(TR $(TD $(PLUSMN)0.0) $(TD -$(INFIN)) $(TD yes) $(TD no))
* $(TR $(TD $(LT)0.0) $(TD $(NAN)) $(TD no) $(TD yes))
* $(TR $(TD +$(INFIN)) $(TD +$(INFIN)) $(TD no) $(TD no))
* )
*/
real log10(real x) @safe pure nothrow
{
version (INLINE_YL2X)
return yl2x(x, LOG2);
else
{
// Coefficients for log(1 + x)
static immutable real[7] P = [
2.0039553499201281259648E1L,
5.7112963590585538103336E1L,
6.0949667980987787057556E1L,
2.9911919328553073277375E1L,
6.5787325942061044846969E0L,
4.9854102823193375972212E-1L,
4.5270000862445199635215E-5L,
];
static immutable real[7] Q = [
6.0118660497603843919306E1L,
2.1642788614495947685003E2L,
3.0909872225312059774938E2L,
2.2176239823732856465394E2L,
8.3047565967967209469434E1L,
1.5062909083469192043167E1L,
1.0000000000000000000000E0L,
];
// Coefficients for log(x)
static immutable real[4] R = [
-3.5717684488096787370998E1L,
1.0777257190312272158094E1L,
-7.1990767473014147232598E-1L,
1.9757429581415468984296E-3L,
];
static immutable real[4] S = [
-4.2861221385716144629696E2L,
1.9361891836232102174846E2L,
-2.6201045551331104417768E1L,
1.0000000000000000000000E0L,
];
// log10(2) split into two parts.
enum real L102A = 0.3125L;
enum real L102B = -1.14700043360188047862611052755069732318101185E-2L;
// log10(e) split into two parts.
enum real L10EA = 0.5L;
enum real L10EB = -6.570551809674817234887108108339491770560299E-2L;
// Special cases are the same as for log.
if (isNaN(x))
return x;
if (isInfinity(x) && !signbit(x))
return x;
if (x == 0.0)
return -real.infinity;
if (x < 0.0)
return real.nan;
// Separate mantissa from exponent.
// Note, frexp is used so that denormal numbers will be handled properly.
real y, z;
int exp;
x = frexp(x, exp);
// Logarithm using log(x) = z + z^^3 P(z) / Q(z),
// where z = 2(x - 1)/(x + 1)
if((exp > 2) || (exp < -2))
{
if(x < SQRT1_2)
{ // 2(2x - 1)/(2x + 1)
exp -= 1;
z = x - 0.5;
y = 0.5 * z + 0.5;
}
else
{ // 2(x - 1)/(x + 1)
z = x - 0.5;
z -= 0.5;
y = 0.5 * x + 0.5;
}
x = z / y;
z = x * x;
y = x * (z * poly(z, R) / poly(z, S));
goto Ldone;
}
// Logarithm using log(1 + x) = x - .5x^^2 + x^^3 P(x) / Q(x)
if (x < SQRT1_2)
{ // 2x - 1
exp -= 1;
x = ldexp(x, 1) - 1.0;
}
else
x = x - 1.0;
z = x * x;
y = x * (z * poly(x, P) / poly(x, Q));
y = y - ldexp(z, -1);
// Multiply log of fraction by log10(e) and base 2 exponent by log10(2).
// This sequence of operations is critical and it may be horribly
// defeated by some compiler optimizers.
Ldone:
z = y * L10EB;
z += x * L10EB;
z += exp * L102B;
z += y * L10EA;
z += x * L10EA;
z += exp * L102A;
return z;
}
}
unittest
{
//printf("%Lg\n", log10(1000) - 3);
assert(fabs(log10(1000) - 3) < .000001);
}
/******************************************
* Calculates the natural logarithm of 1 + x.
*
* For very small x, log1p(x) will be more accurate than
* log(1 + x).
*
* $(TABLE_SV
* $(TR $(TH x) $(TH log1p(x)) $(TH divide by 0?) $(TH invalid?))
* $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) $(TD no) $(TD no))
* $(TR $(TD -1.0) $(TD -$(INFIN)) $(TD yes) $(TD no))
* $(TR $(TD $(LT)-1.0) $(TD $(NAN)) $(TD no) $(TD yes))
* $(TR $(TD +$(INFIN)) $(TD -$(INFIN)) $(TD no) $(TD no))
* )
*/
real log1p(real x) @safe pure nothrow
{
version(INLINE_YL2X)
{
// On x87, yl2xp1 is valid if and only if -0.5 <= lg(x) <= 0.5,
// ie if -0.29<=x<=0.414
return (fabs(x) <= 0.25) ? yl2xp1(x, LN2) : yl2x(x+1, LN2);
}
else
{
// Special cases.
if (isNaN(x) || x == 0.0)
return x;
if (isInfinity(x) && !signbit(x))
return x;
if (x == -1.0)
return -real.infinity;
if (x < -1.0)
return real.nan;
return log(x + 1.0);
}
}
/***************************************
* Calculates the base-2 logarithm of x:
* $(SUB log, 2)x
*
* $(TABLE_SV
* $(TR $(TH x) $(TH log2(x)) $(TH divide by 0?) $(TH invalid?))
* $(TR $(TD $(PLUSMN)0.0) $(TD -$(INFIN)) $(TD yes) $(TD no) )
* $(TR $(TD $(LT)0.0) $(TD $(NAN)) $(TD no) $(TD yes) )
* $(TR $(TD +$(INFIN)) $(TD +$(INFIN)) $(TD no) $(TD no) )
* )
*/
real log2(real x) @safe pure nothrow
{
version (INLINE_YL2X)
return yl2x(x, 1);
else
{
// Coefficients for log(1 + x)
static immutable real[7] P = [
2.0039553499201281259648E1L,
5.7112963590585538103336E1L,
6.0949667980987787057556E1L,
2.9911919328553073277375E1L,
6.5787325942061044846969E0L,
4.9854102823193375972212E-1L,
4.5270000862445199635215E-5L,
];
static immutable real[7] Q = [
6.0118660497603843919306E1L,
2.1642788614495947685003E2L,
3.0909872225312059774938E2L,
2.2176239823732856465394E2L,
8.3047565967967209469434E1L,
1.5062909083469192043167E1L,
1.0000000000000000000000E0L,
];
// Coefficients for log(x)
static immutable real[4] R = [
-3.5717684488096787370998E1L,
1.0777257190312272158094E1L,
-7.1990767473014147232598E-1L,
1.9757429581415468984296E-3L,
];
static immutable real[4] S = [
-4.2861221385716144629696E2L,
1.9361891836232102174846E2L,
-2.6201045551331104417768E1L,
1.0000000000000000000000E0L,
];
// Special cases are the same as for log.
if (isNaN(x))
return x;
if (isInfinity(x) && !signbit(x))
return x;
if (x == 0.0)
return -real.infinity;
if (x < 0.0)
return real.nan;
// Separate mantissa from exponent.
// Note, frexp is used so that denormal numbers will be handled properly.
real y, z;
int exp;
x = frexp(x, exp);
// Logarithm using log(x) = z + z^^3 P(z) / Q(z),
// where z = 2(x - 1)/(x + 1)
if((exp > 2) || (exp < -2))
{
if(x < SQRT1_2)
{ // 2(2x - 1)/(2x + 1)
exp -= 1;
z = x - 0.5;
y = 0.5 * z + 0.5;
}
else
{ // 2(x - 1)/(x + 1)
z = x - 0.5;
z -= 0.5;
y = 0.5 * x + 0.5;
}
x = z / y;
z = x * x;
y = x * (z * poly(z, R) / poly(z, S));
goto Ldone;
}
// Logarithm using log(1 + x) = x - .5x^^2 + x^^3 P(x) / Q(x)
if (x < SQRT1_2)
{ // 2x - 1
exp -= 1;
x = ldexp(x, 1) - 1.0;
}
else
x = x - 1.0;
z = x * x;
y = x * (z * poly(x, P) / poly(x, Q));
y = y - ldexp(z, -1);
// Multiply log of fraction by log10(e) and base 2 exponent by log10(2).
// This sequence of operations is critical and it may be horribly
// defeated by some compiler optimizers.
Ldone:
z = y * (LOG2E - 1.0);
z += x * (LOG2E - 1.0);
z += y;
z += x;
z += exp;
return z;
}
}
unittest
{
assert(equalsDigit(log2(1024), 10, 19));
}
/*****************************************
* Extracts the exponent of x as a signed integral value.
*
* If x is subnormal, it is treated as if it were normalized.
* For a positive, finite x:
*
* 1 $(LT)= $(I x) * FLT_RADIX$(SUP -logb(x)) $(LT) FLT_RADIX
*
* $(TABLE_SV
* $(TR $(TH x) $(TH logb(x)) $(TH divide by 0?) )
* $(TR $(TD $(PLUSMN)$(INFIN)) $(TD +$(INFIN)) $(TD no))
* $(TR $(TD $(PLUSMN)0.0) $(TD -$(INFIN)) $(TD yes) )
* )
*/
real logb(real x) @trusted nothrow
{
version (Win64)
{
asm
{
naked ;
fld real ptr [RCX] ;
fxtract ;
fstp ST(0) ;
ret ;
}
}
else
return core.stdc.math.logbl(x);
}
/************************************
* Calculates the remainder from the calculation x/y.
* Returns:
* The value of x - i * y, where i is the number of times that y can
* be completely subtracted from x. The result has the same sign as x.
*
* $(TABLE_SV
* $(TR $(TH x) $(TH y) $(TH fmod(x, y)) $(TH invalid?))
* $(TR $(TD $(PLUSMN)0.0) $(TD not 0.0) $(TD $(PLUSMN)0.0) $(TD no))
* $(TR $(TD $(PLUSMNINF)) $(TD anything) $(TD $(NAN)) $(TD yes))
* $(TR $(TD anything) $(TD $(PLUSMN)0.0) $(TD $(NAN)) $(TD yes))
* $(TR $(TD !=$(PLUSMNINF)) $(TD $(PLUSMNINF)) $(TD x) $(TD no))
* )
*/
real fmod(real x, real y) @trusted nothrow
{
version (Win64)
{
return x % y;
}
else
return core.stdc.math.fmodl(x, y);
}
/************************************
* Breaks x into an integral part and a fractional part, each of which has
* the same sign as x. The integral part is stored in i.
* Returns:
* The fractional part of x.
*
* $(TABLE_SV
* $(TR $(TH x) $(TH i (on input)) $(TH modf(x, i)) $(TH i (on return)))
* $(TR $(TD $(PLUSMNINF)) $(TD anything) $(TD $(PLUSMN)0.0) $(TD $(PLUSMNINF)))
* )
*/
real modf(real x, ref real i) @trusted nothrow
{
version (Win64)
{
i = trunc(x);
return copysign(isInfinity(x) ? 0.0 : x - i, x);
}
else
return core.stdc.math.modfl(x,&i);
}
/*************************************
* Efficiently calculates x * 2$(SUP n).
*
* scalbn handles underflow and overflow in
* the same fashion as the basic arithmetic operators.
*
* $(TABLE_SV
* $(TR $(TH x) $(TH scalb(x)))
* $(TR $(TD $(PLUSMNINF)) $(TD $(PLUSMNINF)) )
* $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) )
* )
*/
real scalbn(real x, int n) @trusted nothrow
{
version(InlineAsm_X86_Any) {
// scalbnl is not supported on DMD-Windows, so use asm.
version (Win64)
{
asm {
naked ;
mov 16[RSP],RCX ;
fild word ptr 16[RSP] ;
fld real ptr [RDX] ;
fscale ;
fstp ST(1) ;
ret ;
}
}
else
{
asm {
fild n;
fld x;
fscale;
fstp ST(1);
}
}
}
else
{
return core.stdc.math.scalbnl(x, n);
}
}
unittest
{
assert(scalbn(-real.infinity, 5) == -real.infinity);
}
/***************
* Calculates the cube root of x.
*
* $(TABLE_SV
* $(TR $(TH $(I x)) $(TH cbrt(x)) $(TH invalid?))
* $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) $(TD no) )
* $(TR $(TD $(NAN)) $(TD $(NAN)) $(TD yes) )
* $(TR $(TD $(PLUSMN)$(INFIN)) $(TD $(PLUSMN)$(INFIN)) $(TD no) )
* )
*/
real cbrt(real x) @trusted nothrow
{
version (Win64)
{
return copysign(exp2(yl2x(fabs(x), 1.0L/3.0L)), x);
}
else
return core.stdc.math.cbrtl(x);
}
/*******************************
* Returns |x|
*
* $(TABLE_SV
* $(TR $(TH x) $(TH fabs(x)))
* $(TR $(TD $(PLUSMN)0.0) $(TD +0.0) )
* $(TR $(TD $(PLUSMN)$(INFIN)) $(TD +$(INFIN)) )
* )
*/
real fabs(real x) @safe pure nothrow; /* intrinsic */
/***********************************************************************
* Calculates the length of the
* hypotenuse of a right-angled triangle with sides of length x and y.
* The hypotenuse is the value of the square root of
* the sums of the squares of x and y:
*
* sqrt($(POWER x, 2) + $(POWER y, 2))
*
* Note that hypot(x, y), hypot(y, x) and
* hypot(x, -y) are equivalent.
*
* $(TABLE_SV
* $(TR $(TH x) $(TH y) $(TH hypot(x, y)) $(TH invalid?))
* $(TR $(TD x) $(TD $(PLUSMN)0.0) $(TD |x|) $(TD no))
* $(TR $(TD $(PLUSMNINF)) $(TD y) $(TD +$(INFIN)) $(TD no))
* $(TR $(TD $(PLUSMNINF)) $(TD $(NAN)) $(TD +$(INFIN)) $(TD no))
* )
*/
real hypot(real x, real y) @safe pure nothrow
{
// Scale x and y to avoid underflow and overflow.
// If one is huge and the other tiny, return the larger.
// If both are huge, avoid overflow by scaling by 1/sqrt(real.max/2).
// If both are tiny, avoid underflow by scaling by sqrt(real.min_normal*real.epsilon).
enum real SQRTMIN = 0.5 * sqrt(real.min_normal); // This is a power of 2.
enum real SQRTMAX = 1.0L / SQRTMIN; // 2^^((max_exp)/2) = nextUp(sqrt(real.max))
static assert(2*(SQRTMAX/2)*(SQRTMAX/2) <= real.max);
// Proves that sqrt(real.max) ~~ 0.5/sqrt(real.min_normal)
static assert(real.min_normal*real.max > 2 && real.min_normal*real.max <= 4);
real u = fabs(x);
real v = fabs(y);
if (!(u >= v)) // check for NaN as well.
{
v = u;
u = fabs(y);
if (u == real.infinity) return u; // hypot(inf, nan) == inf
if (v == real.infinity) return v; // hypot(nan, inf) == inf
}
// Now u >= v, or else one is NaN.
if (v >= SQRTMAX*0.5)
{
// hypot(huge, huge) -- avoid overflow
u *= SQRTMIN*0.5;
v *= SQRTMIN*0.5;
return sqrt(u*u + v*v) * SQRTMAX * 2.0;
}
if (u <= SQRTMIN)
{
// hypot (tiny, tiny) -- avoid underflow
// This is only necessary to avoid setting the underflow
// flag.
u *= SQRTMAX / real.epsilon;
v *= SQRTMAX / real.epsilon;
return sqrt(u*u + v*v) * SQRTMIN * real.epsilon;
}
if (u * real.epsilon > v)
{
// hypot (huge, tiny) = huge
return u;
}
// both are in the normal range
return sqrt(u*u + v*v);
}
unittest
{
static real[3][] vals = // x,y,hypot
[
[ 0.0, 0.0, 0.0],
[ 0.0, -0.0, 0.0],
[ -0.0, -0.0, 0.0],
[ 3.0, 4.0, 5.0],
[ -300, -400, 500],
[0.0, 7.0, 7.0],
[9.0, 9*real.epsilon, 9.0],
[88/(64*sqrt(real.min_normal)), 105/(64*sqrt(real.min_normal)), 137/(64*sqrt(real.min_normal))],
[88/(128*sqrt(real.min_normal)), 105/(128*sqrt(real.min_normal)), 137/(128*sqrt(real.min_normal))],
[3*real.min_normal*real.epsilon, 4*real.min_normal*real.epsilon, 5*real.min_normal*real.epsilon],
[ real.min_normal, real.min_normal, sqrt(2.0L)*real.min_normal],
[ real.max/sqrt(2.0L), real.max/sqrt(2.0L), real.max],
[ real.infinity, real.nan, real.infinity],
[ real.nan, real.infinity, real.infinity],
[ real.nan, real.nan, real.nan],
[ real.nan, real.max, real.nan],
[ real.max, real.nan, real.nan],
];
for (int i = 0; i < vals.length; i++)
{
real x = vals[i][0];
real y = vals[i][1];
real z = vals[i][2];
real h = hypot(x, y);
assert(isIdentical(z,h) || feqrel(z, h) >= real.mant_dig - 1);
}
}
/**************************************
* Returns the value of x rounded upward to the next integer
* (toward positive infinity).
*/
real ceil(real x) @trusted pure nothrow
{
version (Win64)
{
asm
{
naked ;
fld real ptr [RCX] ;
fstcw 8[RSP] ;
mov AL,9[RSP] ;
mov DL,AL ;
and AL,0xC3 ;
or AL,0x08 ; // round to +infinity
mov 9[RSP],AL ;
fldcw 8[RSP] ;
frndint ;
mov 9[RSP],DL ;
fldcw 8[RSP] ;
ret ;
}
}
else
{
// Special cases.
if (isNaN(x) || isInfinity(x))
return x;
real y = floor(x);
if (y < x)
y += 1.0;
return y;
}
}
unittest
{
assert(ceil(+123.456) == +124);
assert(ceil(-123.456) == -123);
assert(ceil(-1.234) == -1);
assert(ceil(-0.123) == 0);
assert(ceil(0.0) == 0);
assert(ceil(+0.123) == 1);
assert(ceil(+1.234) == 2);
assert(ceil(real.infinity) == real.infinity);
assert(isNaN(ceil(real.nan)));
assert(isNaN(ceil(real.init)));
}
/**************************************
* Returns the value of x rounded downward to the next integer
* (toward negative infinity).
*/
real floor(real x) @trusted pure nothrow
{
version (Win64)
{
asm
{
naked ;
fld real ptr [RCX] ;
fstcw 8[RSP] ;
mov AL,9[RSP] ;
mov DL,AL ;
and AL,0xC3 ;
or AL,0x04 ; // round to -infinity
mov 9[RSP],AL ;
fldcw 8[RSP] ;
frndint ;
mov 9[RSP],DL ;
fldcw 8[RSP] ;
ret ;
}
}
else
{
// Bit clearing masks.
static immutable ushort[17] BMASK = [
0xffff, 0xfffe, 0xfffc, 0xfff8,
0xfff0, 0xffe0, 0xffc0, 0xff80,
0xff00, 0xfe00, 0xfc00, 0xf800,
0xf000, 0xe000, 0xc000, 0x8000,
0x0000,
];
// Special cases.
if (isNaN(x) || isInfinity(x) || x == 0.0)
return x;
alias F = floatTraits!(real);
auto vu = *cast(ushort[real.sizeof/2]*)(&x);
// Find the exponent (power of 2)
static if (real.mant_dig == 53)
{
int exp = ((vu[F.EXPPOS_SHORT] >> 4) & 0x7ff) - 0x3ff;
version (LittleEndian)
int pos = 0;
else
int pos = 3;
}
else static if (real.mant_dig == 64)
{
int exp = (vu[F.EXPPOS_SHORT] & 0x7fff) - 0x3fff;
version (LittleEndian)
int pos = 0;
else
int pos = 4;
}
else if (real.mant_dig == 113)
{
int exp = (vu[F.EXPPOS_SHORT] & 0x7fff) - 0x3fff;
version (LittleEndian)
int pos = 0;
else
int pos = 7;
}
else
static assert(false, "Only 64-bit, 80-bit, and 128-bit reals are supported by floor()");
if (exp < 0)
{
if (x < 0.0)
return -1.0;
else
return 0.0;
}
exp = (real.mant_dig - 1) - exp;
// Clean out 16 bits at a time.
while (exp >= 16)
{
version (LittleEndian)
vu[pos++] = 0;
else
vu[pos--] = 0;
exp -= 16;
}
// Clear the remaining bits.
if (exp > 0)
vu[pos] &= BMASK[exp];
real y = *cast(real*)(&vu);
if ((x < 0.0) && (x != y))
y -= 1.0;
return y;
}
}
unittest
{
assert(floor(+123.456) == +123);
assert(floor(-123.456) == -124);
assert(floor(-1.234) == -2);
assert(floor(-0.123) == -1);
assert(floor(0.0) == 0);
assert(floor(+0.123) == 0);
assert(floor(+1.234) == 1);
assert(floor(real.infinity) == real.infinity);
assert(isNaN(floor(real.nan)));
assert(isNaN(floor(real.init)));
}
/******************************************
* Rounds x to the nearest integer value, using the current rounding
* mode.
*
* Unlike the rint functions, nearbyint does not raise the
* FE_INEXACT exception.
*/
real nearbyint(real x) @trusted nothrow
{
version (Win64)
{
assert(0); // not implemented in C library
}
else
return core.stdc.math.nearbyintl(x);
}
/**********************************
* Rounds x to the nearest integer value, using the current rounding
* mode.
* If the return value is not equal to x, the FE_INEXACT
* exception is raised.
* $(B nearbyint) performs
* the same operation, but does not set the FE_INEXACT exception.
*/
real rint(real x) @safe pure nothrow; /* intrinsic */
/***************************************
* Rounds x to the nearest integer value, using the current rounding
* mode.
*
* This is generally the fastest method to convert a floating-point number
* to an integer. Note that the results from this function
* depend on the rounding mode, if the fractional part of x is exactly 0.5.
* If using the default rounding mode (ties round to even integers)
* lrint(4.5) == 4, lrint(5.5)==6.
*/
long lrint(real x) @trusted pure nothrow
{
version(InlineAsm_X86_Any)
{
version (Win64)
{
asm
{
naked;
fld real ptr [RCX];
fistp qword ptr 8[RSP];
mov RAX,8[RSP];
ret;
}
}
else
{
long n;
asm
{
fld x;
fistp n;
}
return n;
}
}
else
{
static if (real.mant_dig == 53)
{
long result;
// Rounding limit when casting from real(double) to ulong.
enum real OF = 4.50359962737049600000E15L;
uint* vi = cast(uint*)(&x);
// Find the exponent and sign
uint msb = vi[MANTISSA_MSB];
uint lsb = vi[MANTISSA_LSB];
int exp = ((msb >> 20) & 0x7ff) - 0x3ff;
int sign = msb >> 31;
msb &= 0xfffff;
msb |= 0x100000;
if (exp < 63)
{
if (exp >= 52)
result = (cast(long) msb << (exp - 20)) | (lsb << (exp - 52));
else
{
// Adjust x and check result.
real j = sign ? -OF : OF;
x = (j + x) - j;
msb = vi[MANTISSA_MSB];
lsb = vi[MANTISSA_LSB];
exp = ((msb >> 20) & 0x7ff) - 0x3ff;
msb &= 0xfffff;
msb |= 0x100000;
if (exp < 0)
result = 0;
else if (exp < 20)
result = cast(long) msb >> (20 - exp);
else if (exp == 20)
result = cast(long) msb;
else
result = (cast(long) msb << (exp - 20)) | (lsb >> (52 - exp));
}
}
else
{
// It is left implementation defined when the number is too large.
return cast(long) x;
}
return sign ? -result : result;
}
else static if (real.mant_dig == 64)
{
alias F = floatTraits!(real);
long result;
// Rounding limit when casting from real(80-bit) to ulong.
enum real OF = 9.22337203685477580800E18L;
ushort* vu = cast(ushort*)(&x);
uint* vi = cast(uint*)(&x);
// Find the exponent and sign
int exp = (vu[F.EXPPOS_SHORT] & 0x7fff) - 0x3fff;
int sign = (vu[F.EXPPOS_SHORT] >> 15) & 1;
if (exp < 63)
{
// Adjust x and check result.
real j = sign ? -OF : OF;
x = (j + x) - j;
exp = (vu[F.EXPPOS_SHORT] & 0x7fff) - 0x3fff;
version (LittleEndian)
{
if (exp < 0)
result = 0;
else if (exp <= 31)
result = vi[1] >> (31 - exp);
else
result = (cast(long) vi[1] << (exp - 31)) | (vi[0] >> (63 - exp));
}
else
{
if (exp < 0)
result = 0;
else if (exp <= 31)
result = vi[1] >> (31 - exp);
else
result = (cast(long) vi[1] << (exp - 31)) | (vi[2] >> (63 - exp));
}
}
else
{
// It is left implementation defined when the number is too large
// to fit in a 64bit long.
return cast(long) x;
}
return sign ? -result : result;
}
else
{
static assert(false, "Only 64-bit and 80-bit reals are supported by lrint()");
}
}
}
unittest
{
assert(lrint(4.5) == 4);
assert(lrint(5.5) == 6);
assert(lrint(-4.5) == -4);
assert(lrint(-5.5) == -6);
assert(lrint(int.max - 0.5) == 2147483646L);
assert(lrint(int.max + 0.5) == 2147483648L);
assert(lrint(int.min - 0.5) == -2147483648L);
assert(lrint(int.min + 0.5) == -2147483648L);
}
/*******************************************
* Return the value of x rounded to the nearest integer.
* If the fractional part of x is exactly 0.5, the return value is rounded to
* the even integer.
*/
real round(real x) @trusted nothrow
{
version (Win64)
{
auto old = FloatingPointControl.getControlState();
FloatingPointControl.setControlState((old & ~FloatingPointControl.ROUNDING_MASK) | FloatingPointControl.roundToZero);
x = rint((x >= 0) ? x + 0.5 : x - 0.5);
FloatingPointControl.setControlState(old);
return x;
}
else
return core.stdc.math.roundl(x);
}
/**********************************************
* Return the value of x rounded to the nearest integer.
*
* If the fractional part of x is exactly 0.5, the return value is rounded
* away from zero.
*/
long lround(real x) @trusted nothrow
{
version (Posix)
return core.stdc.math.llroundl(x);
else
assert (0, "lround not implemented");
}
version(Posix)
{
unittest
{
assert(lround(0.49) == 0);
assert(lround(0.5) == 1);
assert(lround(1.5) == 2);
}
}
/****************************************************
* Returns the integer portion of x, dropping the fractional portion.
*
* This is also known as "chop" rounding.
*/
real trunc(real x) @trusted nothrow
{
version (Win64)
{
asm
{
naked ;
fld real ptr [RCX] ;
fstcw 8[RSP] ;
mov AL,9[RSP] ;
mov DL,AL ;
and AL,0xC3 ;
or AL,0x0C ; // round to 0
mov 9[RSP],AL ;
fldcw 8[RSP] ;
frndint ;
mov 9[RSP],DL ;
fldcw 8[RSP] ;
ret ;
}
}
else
return core.stdc.math.truncl(x);
}
/****************************************************
* Calculate the remainder x REM y, following IEC 60559.
*
* REM is the value of x - y * n, where n is the integer nearest the exact
* value of x / y.
* If |n - x / y| == 0.5, n is even.
* If the result is zero, it has the same sign as x.
* Otherwise, the sign of the result is the sign of x / y.
* Precision mode has no effect on the remainder functions.
*
* remquo returns n in the parameter n.
*
* $(TABLE_SV
* $(TR $(TH x) $(TH y) $(TH remainder(x, y)) $(TH n) $(TH invalid?))
* $(TR $(TD $(PLUSMN)0.0) $(TD not 0.0) $(TD $(PLUSMN)0.0) $(TD 0.0) $(TD no))
* $(TR $(TD $(PLUSMNINF)) $(TD anything) $(TD $(NAN)) $(TD ?) $(TD yes))
* $(TR $(TD anything) $(TD $(PLUSMN)0.0) $(TD $(NAN)) $(TD ?) $(TD yes))
* $(TR $(TD != $(PLUSMNINF)) $(TD $(PLUSMNINF)) $(TD x) $(TD ?) $(TD no))
* )
*
* Note: remquo not supported on windows
*/
real remainder(real x, real y) @trusted nothrow
{
version (Win64)
{
int n;
return remquo(x, y, n);
}
else
return core.stdc.math.remainderl(x, y);
}
real remquo(real x, real y, out int n) @trusted nothrow /// ditto
{
version (Posix)
return core.stdc.math.remquol(x, y, &n);
else
assert (0, "remquo not implemented");
}
/** IEEE exception status flags ('sticky bits')
These flags indicate that an exceptional floating-point condition has occurred.
They indicate that a NaN or an infinity has been generated, that a result
is inexact, or that a signalling NaN has been encountered. If floating-point
exceptions are enabled (unmasked), a hardware exception will be generated
instead of setting these flags.
Example:
----
real a=3.5;
// Set all the flags to zero
resetIeeeFlags();
assert(!ieeeFlags.divByZero);
// Perform a division by zero.
a/=0.0L;
assert(a==real.infinity);
assert(ieeeFlags.divByZero);
// Create a NaN
a*=0.0L;
assert(ieeeFlags.invalid);
assert(isNaN(a));
// Check that calling func() has no effect on the
// status flags.
IeeeFlags f = ieeeFlags;
func();
assert(ieeeFlags == f);
----
*/
struct IeeeFlags
{
private:
// The x87 FPU status register is 16 bits.
// The Pentium SSE2 status register is 32 bits.
uint flags;
version (X86_Any)
{
// Applies to both x87 status word (16 bits) and SSE2 status word(32 bits).
enum : int
{
INEXACT_MASK = 0x20,
UNDERFLOW_MASK = 0x10,
OVERFLOW_MASK = 0x08,
DIVBYZERO_MASK = 0x04,
INVALID_MASK = 0x01
}
// Don't bother about subnormals, they are not supported on most CPUs.
// SUBNORMAL_MASK = 0x02;
}
else version (PPC)
{
// PowerPC FPSCR is a 32-bit register.
enum : int
{
INEXACT_MASK = 0x600,
UNDERFLOW_MASK = 0x010,
OVERFLOW_MASK = 0x008,
DIVBYZERO_MASK = 0x020,
INVALID_MASK = 0xF80 // PowerPC has five types of invalid exceptions.
}
}
else version (PPC64)
{
// PowerPC FPSCR is a 32-bit register.
enum : int
{
INEXACT_MASK = 0x600,
UNDERFLOW_MASK = 0x010,
OVERFLOW_MASK = 0x008,
DIVBYZERO_MASK = 0x020,
INVALID_MASK = 0xF80 // PowerPC has five types of invalid exceptions.
}
}
else version (ARM)
{
// TODO: Fill this in for VFP.
}
else version(SPARC)
{
// SPARC FSR is a 32bit register
//(64 bits for Sparc 7 & 8, but high 32 bits are uninteresting).
enum : int
{
INEXACT_MASK = 0x020,
UNDERFLOW_MASK = 0x080,
OVERFLOW_MASK = 0x100,
DIVBYZERO_MASK = 0x040,
INVALID_MASK = 0x200
}
}
else
static assert(0, "Not implemented");
private:
static uint getIeeeFlags()
{
version(D_InlineAsm_X86)
{
asm
{
fstsw AX;
// NOTE: If compiler supports SSE2, need to OR the result with
// the SSE2 status register.
// Clear all irrelevant bits
and EAX, 0x03D;
}
}
else version(D_InlineAsm_X86_64)
{
asm
{
fstsw AX;
// NOTE: If compiler supports SSE2, need to OR the result with
// the SSE2 status register.
// Clear all irrelevant bits
and RAX, 0x03D;
}
}
else version (SPARC)
{
/*
int retval;
asm { st %fsr, retval; }
return retval;
*/
assert(0, "Not yet supported");
}
else version (ARM)
{
assert(false, "Not yet supported.");
}
else
assert(0, "Not yet supported");
}
static void resetIeeeFlags()
{
version(InlineAsm_X86_Any)
{
asm
{
fnclex;
}
}
else
{
/* SPARC:
int tmpval;
asm { st %fsr, tmpval; }
tmpval &=0xFFFF_FC00;
asm { ld tmpval, %fsr; }
*/
assert(0, "Not yet supported");
}
}
public:
version (IeeeFlagsSupport) {
/// The result cannot be represented exactly, so rounding occurred.
/// (example: x = sin(0.1); )
@property bool inexact() { return (flags & INEXACT_MASK) != 0; }
/// A zero was generated by underflow (example: x = real.min*real.epsilon/2;)
@property bool underflow() { return (flags & UNDERFLOW_MASK) != 0; }
/// An infinity was generated by overflow (example: x = real.max*2;)
@property bool overflow() { return (flags & OVERFLOW_MASK) != 0; }
/// An infinity was generated by division by zero (example: x = 3/0.0; )
@property bool divByZero() { return (flags & DIVBYZERO_MASK) != 0; }
/// A machine NaN was generated. (example: x = real.infinity * 0.0; )
@property bool invalid() { return (flags & INVALID_MASK) != 0; }
}
}
version(X86_Any)
{
version = IeeeFlagsSupport;
}
else version(ARM)
{
version = IeeeFlagsSupport;
}
/// Set all of the floating-point status flags to false.
void resetIeeeFlags() { IeeeFlags.resetIeeeFlags(); }
/// Return a snapshot of the current state of the floating-point status flags.
@property IeeeFlags ieeeFlags()
{
return IeeeFlags(IeeeFlags.getIeeeFlags());
}
/** Control the Floating point hardware
Change the IEEE754 floating-point rounding mode and the floating-point
hardware exceptions.
By default, the rounding mode is roundToNearest and all hardware exceptions
are disabled. For most applications, debugging is easier if the $(I division
by zero), $(I overflow), and $(I invalid operation) exceptions are enabled.
These three are combined into a $(I severeExceptions) value for convenience.
Note in particular that if $(I invalidException) is enabled, a hardware trap
will be generated whenever an uninitialized floating-point variable is used.
All changes are temporary. The previous state is restored at the
end of the scope.
Example:
----
{
FloatingPointControl fpctrl;
// Enable hardware exceptions for division by zero, overflow to infinity,
// invalid operations, and uninitialized floating-point variables.
fpctrl.enableExceptions(FloatingPointControl.severeExceptions);
// This will generate a hardware exception, if x is a
// default-initialized floating point variable:
real x; // Add `= 0` or even `= real.nan` to not throw the exception.
real y = x * 3.0;
// The exception is only thrown for default-uninitialized NaN-s.
// NaN-s with other payload are valid:
real z = y * real.nan; // ok
// Changing the rounding mode:
fpctrl.rounding = FloatingPointControl.roundUp;
assert(rint(1.1) == 2);
// The set hardware exceptions will be disabled when leaving this scope.
// The original rounding mode will also be restored.
}
// Ensure previous values are returned:
assert(!FloatingPointControl.enabledExceptions);
assert(FloatingPointControl.rounding == FloatingPointControl.roundToNearest);
assert(rint(1.1) == 1);
----
*/
struct FloatingPointControl
{
alias RoundingMode = uint;
/** IEEE rounding modes.
* The default mode is roundToNearest.
*/
version(ARM)
{
enum : RoundingMode
{
roundToNearest = 0x000000,
roundDown = 0x400000,
roundUp = 0x800000,
roundToZero = 0xC00000
}
}
else
{
enum : RoundingMode
{
roundToNearest = 0x0000,
roundDown = 0x0400,
roundUp = 0x0800,
roundToZero = 0x0C00
}
}
/** IEEE hardware exceptions.
* By default, all exceptions are masked (disabled).
*/
version(ARM)
{
enum : uint
{
subnormalException = 0x8000,
inexactException = 0x1000,
underflowException = 0x0800,
overflowException = 0x0400,
divByZeroException = 0x0200,
invalidException = 0x0100,
/// Severe = The overflow, division by zero, and invalid exceptions.
severeExceptions = overflowException | divByZeroException
| invalidException,
allExceptions = severeExceptions | underflowException
| inexactException | subnormalException,
}
}
else
{
enum : uint
{
inexactException = 0x20,
underflowException = 0x10,
overflowException = 0x08,
divByZeroException = 0x04,
subnormalException = 0x02,
invalidException = 0x01,
/// Severe = The overflow, division by zero, and invalid exceptions.
severeExceptions = overflowException | divByZeroException
| invalidException,
allExceptions = severeExceptions | underflowException
| inexactException | subnormalException,
}
}
private:
version(ARM)
{
enum uint EXCEPTION_MASK = 0x9F00;
enum uint ROUNDING_MASK = 0xC00000;
}
else version(X86)
{
enum ushort EXCEPTION_MASK = 0x3F;
enum ushort ROUNDING_MASK = 0xC00;
}
else version(X86_64)
{
enum ushort EXCEPTION_MASK = 0x3F;
enum ushort ROUNDING_MASK = 0xC00;
}
else
static assert(false, "Architecture not supported");
public:
/// Returns true if the current FPU supports exception trapping
@property static bool hasExceptionTraps() @safe nothrow
{
version(X86)
return true;
else version(X86_64)
return true;
else version(ARM)
{
auto oldState = getControlState();
// If exceptions are not supported, we set the bit but read it back as zero
// https://sourceware.org/ml/libc-ports/2012-06/msg00091.html
setControlState(oldState | (divByZeroException & EXCEPTION_MASK));
bool result = (getControlState() & EXCEPTION_MASK) != 0;
setControlState(oldState);
return result;
}
else
static assert(false, "Not implemented for this architecture");
}
/// Enable (unmask) specific hardware exceptions. Multiple exceptions may be ORed together.
void enableExceptions(uint exceptions)
{
assert(hasExceptionTraps);
initialize();
version(ARM)
setControlState(getControlState() | (exceptions & EXCEPTION_MASK));
else
setControlState(getControlState() & ~(exceptions & EXCEPTION_MASK));
}
/// Disable (mask) specific hardware exceptions. Multiple exceptions may be ORed together.
void disableExceptions(uint exceptions)
{
assert(hasExceptionTraps);
initialize();
version(ARM)
setControlState(getControlState() & ~(exceptions & EXCEPTION_MASK));
else
setControlState(getControlState() | (exceptions & EXCEPTION_MASK));
}
//// Change the floating-point hardware rounding mode
@property void rounding(RoundingMode newMode)
{
initialize();
setControlState((getControlState() & ~ROUNDING_MASK) | (newMode & ROUNDING_MASK));
}
/// Return the exceptions which are currently enabled (unmasked)
@property static uint enabledExceptions()
{
assert(hasExceptionTraps);
version(ARM)
return (getControlState() & EXCEPTION_MASK);
else
return (getControlState() & EXCEPTION_MASK) ^ EXCEPTION_MASK;
}
/// Return the currently active rounding mode
@property static RoundingMode rounding()
{
return cast(RoundingMode)(getControlState() & ROUNDING_MASK);
}
/// Clear all pending exceptions, then restore the original exception state and rounding mode.
~this()
{
clearExceptions();
if (initialized)
setControlState(savedState);
}
private:
ControlState savedState;
bool initialized = false;
version(ARM)
{
alias ControlState = uint;
}
else
{
alias ControlState = ushort;
}
void initialize()
{
// BUG: This works around the absence of this() constructors.
if (initialized) return;
clearExceptions();
savedState = getControlState();
initialized = true;
}
// Clear all pending exceptions
static void clearExceptions()
{
version (InlineAsm_X86_Any)
{
asm
{
fclex;
}
}
else
assert(0, "Not yet supported");
}
// Read from the control register
static ushort getControlState() @trusted nothrow
{
version (D_InlineAsm_X86)
{
short cont;
asm
{
xor EAX, EAX;
fstcw cont;
}
return cont;
}
else
version (D_InlineAsm_X86_64)
{
short cont;
asm
{
xor RAX, RAX;
fstcw cont;
}
return cont;
}
else
assert(0, "Not yet supported");
}
// Set the control register
static void setControlState(ushort newState) @trusted nothrow
{
version (InlineAsm_X86_Any)
{
version (Win64)
{
asm
{
naked;
mov 8[RSP],RCX;
fclex;
fldcw 8[RSP];
ret;
}
}
else
{
asm
{
fclex;
fldcw newState;
}
}
}
else
assert(0, "Not yet supported");
}
}
unittest
{
void ensureDefaults()
{
assert(FloatingPointControl.rounding
== FloatingPointControl.roundToNearest);
if(FloatingPointControl.hasExceptionTraps)
assert(FloatingPointControl.enabledExceptions == 0);
}
{
FloatingPointControl ctrl;
}
ensureDefaults();
{
FloatingPointControl ctrl;
ctrl.rounding = FloatingPointControl.roundDown;
assert(FloatingPointControl.rounding == FloatingPointControl.roundDown);
}
ensureDefaults();
if(FloatingPointControl.hasExceptionTraps)
{
FloatingPointControl ctrl;
ctrl.enableExceptions(FloatingPointControl.divByZeroException
| FloatingPointControl.overflowException);
assert(ctrl.enabledExceptions ==
(FloatingPointControl.divByZeroException
| FloatingPointControl.overflowException));
ctrl.rounding = FloatingPointControl.roundUp;
assert(FloatingPointControl.rounding == FloatingPointControl.roundUp);
}
ensureDefaults();
}
/*********************************
* Returns !=0 if e is a NaN.
*/
bool isNaN(real x) @trusted pure nothrow
{
alias F = floatTraits!(real);
static if (real.mant_dig == 53) // double
{
ulong* p = cast(ulong *)&x;
return ((*p & 0x7FF0_0000_0000_0000) == 0x7FF0_0000_0000_0000)
&& *p & 0x000F_FFFF_FFFF_FFFF;
}
else static if (real.mant_dig == 64) // real80
{
ushort e = F.EXPMASK & (cast(ushort *)&x)[F.EXPPOS_SHORT];
ulong* ps = cast(ulong *)&x;
return e == F.EXPMASK &&
*ps & 0x7FFF_FFFF_FFFF_FFFF; // not infinity
}
else static if (real.mant_dig == 113) // quadruple
{
ushort e = F.EXPMASK & (cast(ushort *)&x)[F.EXPPOS_SHORT];
ulong* ps = cast(ulong *)&x;
return e == F.EXPMASK &&
(ps[MANTISSA_LSB] | (ps[MANTISSA_MSB]& 0x0000_FFFF_FFFF_FFFF))!=0;
}
else
{
return x!=x;
}
}
unittest
{
assert(isNaN(float.nan));
assert(isNaN(-double.nan));
assert(isNaN(real.nan));
assert(!isNaN(53.6));
assert(!isNaN(float.infinity));
}
/*********************************
* Returns !=0 if e is finite (not infinite or $(NAN)).
*/
int isFinite(real e) @trusted pure nothrow
{
alias F = floatTraits!(real);
ushort* pe = cast(ushort *)&e;
return (pe[F.EXPPOS_SHORT] & F.EXPMASK) != F.EXPMASK;
}
unittest
{
assert(isFinite(1.23));
assert(!isFinite(double.infinity));
assert(!isFinite(float.nan));
}
/*********************************
* Returns !=0 if x is normalized (not zero, subnormal, infinite, or $(NAN)).
*/
/* Need one for each format because subnormal floats might
* be converted to normal reals.
*/
int isNormal(X)(X x) @trusted pure nothrow
{
alias F = floatTraits!(X);
static if(real.mant_dig == 106) // doubledouble
{
// doubledouble is normal if the least significant part is normal.
return isNormal((cast(double*)&x)[MANTISSA_LSB]);
}
else
{
ushort e = F.EXPMASK & (cast(ushort *)&x)[F.EXPPOS_SHORT];
return (e != F.EXPMASK && e!=0);
}
}
unittest
{
float f = 3;
double d = 500;
real e = 10e+48;
assert(isNormal(f));
assert(isNormal(d));
assert(isNormal(e));
f = d = e = 0;
assert(!isNormal(f));
assert(!isNormal(d));
assert(!isNormal(e));
assert(!isNormal(real.infinity));
assert(isNormal(-real.max));
assert(!isNormal(real.min_normal/4));
}
/*********************************
* Is number subnormal? (Also called "denormal".)
* Subnormals have a 0 exponent and a 0 most significant mantissa bit.
*/
/* Need one for each format because subnormal floats might
* be converted to normal reals.
*/
int isSubnormal(float f) @trusted pure nothrow
{
uint *p = cast(uint *)&f;
return (*p & 0x7F80_0000) == 0 && *p & 0x007F_FFFF;
}
unittest
{
float f = 3.0;
for (f = 1.0; !isSubnormal(f); f /= 2)
assert(f != 0);
}
/// ditto
int isSubnormal(double d) @trusted pure nothrow
{
uint *p = cast(uint *)&d;
return (p[MANTISSA_MSB] & 0x7FF0_0000) == 0
&& (p[MANTISSA_LSB] || p[MANTISSA_MSB] & 0x000F_FFFF);
}
unittest
{
double f;
for (f = 1; !isSubnormal(f); f /= 2)
assert(f != 0);
}
/// ditto
int isSubnormal(real x) @trusted pure nothrow
{
alias F = floatTraits!(real);
static if (real.mant_dig == 53)
{
// double
return isSubnormal(cast(double)x);
}
else static if (real.mant_dig == 113)
{
// quadruple
ushort e = F.EXPMASK & (cast(ushort *)&x)[F.EXPPOS_SHORT];
long* ps = cast(long *)&x;
return (e == 0 &&
(((ps[MANTISSA_LSB]|(ps[MANTISSA_MSB]& 0x0000_FFFF_FFFF_FFFF))) !=0));
}
else static if (real.mant_dig==64)
{
// real80
ushort* pe = cast(ushort *)&x;
long* ps = cast(long *)&x;
return (pe[F.EXPPOS_SHORT] & F.EXPMASK) == 0 && *ps > 0;
}
else
{
// double double
return isSubnormal((cast(double*)&x)[MANTISSA_MSB]);
}
}
unittest
{
real f;
for (f = 1; !isSubnormal(f); f /= 2)
assert(f != 0);
}
/*********************************
* Return !=0 if e is $(PLUSMN)$(INFIN).
*/
bool isInfinity(real x) @trusted pure nothrow
{
alias F = floatTraits!(real);
static if (real.mant_dig == 53)
{
// double
return ((*cast(ulong *)&x) & 0x7FFF_FFFF_FFFF_FFFF)
== 0x7FF0_0000_0000_0000;
}
else static if(real.mant_dig == 106)
{
//doubledouble
return (((cast(ulong *)&x)[MANTISSA_MSB]) & 0x7FFF_FFFF_FFFF_FFFF)
== 0x7FF8_0000_0000_0000;
}
else static if (real.mant_dig == 113)
{
// quadruple
long* ps = cast(long *)&x;
return (ps[MANTISSA_LSB] == 0)
&& (ps[MANTISSA_MSB] & 0x7FFF_FFFF_FFFF_FFFF) == 0x7FFF_0000_0000_0000;
}
else
{
// real80
ushort e = cast(ushort)(F.EXPMASK & (cast(ushort *)&x)[F.EXPPOS_SHORT]);
ulong* ps = cast(ulong *)&x;
// On Motorola 68K, infinity can have hidden bit = 1 or 0. On x86, it is always 1.
return e == F.EXPMASK && (*ps & 0x7FFF_FFFF_FFFF_FFFF) == 0;
}
}
unittest
{
assert(isInfinity(float.infinity));
assert(!isInfinity(float.nan));
assert(isInfinity(double.infinity));
assert(isInfinity(-real.infinity));
assert(isInfinity(-1.0 / 0.0));
}
/*********************************
* Is the binary representation of x identical to y?
*
* Same as ==, except that positive and negative zero are not identical,
* and two $(NAN)s are identical if they have the same 'payload'.
*/
bool isIdentical(real x, real y) @trusted pure nothrow
{
// We're doing a bitwise comparison so the endianness is irrelevant.
long* pxs = cast(long *)&x;
long* pys = cast(long *)&y;
static if (real.mant_dig == 53)
{
//double
return pxs[0] == pys[0];
}
else static if (real.mant_dig == 113 || real.mant_dig==106)
{
// quadruple or doubledouble
return pxs[0] == pys[0] && pxs[1] == pys[1];
}
else
{
// real80
ushort* pxe = cast(ushort *)&x;
ushort* pye = cast(ushort *)&y;
return pxe[4] == pye[4] && pxs[0] == pys[0];
}
}
/*********************************
* Return 1 if sign bit of e is set, 0 if not.
*/
int signbit(real x) @trusted pure nothrow
{
return ((cast(ubyte *)&x)[floatTraits!(real).SIGNPOS_BYTE] & 0x80) != 0;
}
unittest
{
debug (math) printf("math.signbit.unittest\n");
assert(!signbit(float.nan));
assert(signbit(-float.nan));
assert(!signbit(168.1234));
assert(signbit(-168.1234));
assert(!signbit(0.0));
assert(signbit(-0.0));
assert(signbit(-double.max));
assert(!signbit(double.max));
}
/*********************************
* Return a value composed of to with from's sign bit.
*/
real copysign(real to, real from) @trusted pure nothrow
{
ubyte* pto = cast(ubyte *)&to;
const ubyte* pfrom = cast(ubyte *)&from;
alias F = floatTraits!(real);
pto[F.SIGNPOS_BYTE] &= 0x7F;
pto[F.SIGNPOS_BYTE] |= pfrom[F.SIGNPOS_BYTE] & 0x80;
return to;
}
unittest
{
real e;
e = copysign(21, 23.8);
assert(e == 21);
e = copysign(-21, 23.8);
assert(e == 21);
e = copysign(21, -23.8);
assert(e == -21);
e = copysign(-21, -23.8);
assert(e == -21);
e = copysign(real.nan, -23.8);
assert(isNaN(e) && signbit(e));
}
/*********************************
Returns $(D -1) if $(D x < 0), $(D x) if $(D x == 0), $(D 1) if
$(D x > 0), and $(NAN) if x==$(NAN).
*/
F sgn(F)(F x) @safe pure nothrow
{
// @@@TODO@@@: make this faster
return x > 0 ? 1 : x < 0 ? -1 : x;
}
unittest
{
debug (math) printf("math.sgn.unittest\n");
assert(sgn(168.1234) == 1);
assert(sgn(-168.1234) == -1);
assert(sgn(0.0) == 0);
assert(sgn(-0.0) == 0);
}
// Functions for NaN payloads
/*
* A 'payload' can be stored in the significand of a $(NAN). One bit is required
* to distinguish between a quiet and a signalling $(NAN). This leaves 22 bits
* of payload for a float; 51 bits for a double; 62 bits for an 80-bit real;
* and 111 bits for a 128-bit quad.
*/
/**
* Create a quiet $(NAN), storing an integer inside the payload.
*
* For floats, the largest possible payload is 0x3F_FFFF.
* For doubles, it is 0x3_FFFF_FFFF_FFFF.
* For 80-bit or 128-bit reals, it is 0x3FFF_FFFF_FFFF_FFFF.
*/
real NaN(ulong payload) @trusted pure nothrow
{
static if (real.mant_dig == 64)
{
//real80 (in x86 real format, the implied bit is actually
//not implied but a real bit which is stored in the real)
ulong v = 3; // implied bit = 1, quiet bit = 1
}
else
{
ulong v = 1; // no implied bit. quiet bit = 1
}
ulong a = payload;
// 22 Float bits
ulong w = a & 0x3F_FFFF;
a -= w;
v <<=22;
v |= w;
a >>=22;
// 29 Double bits
v <<=29;
w = a & 0xFFF_FFFF;
v |= w;
a -= w;
a >>=29;
static if (real.mant_dig == 53)
{
// double
v |=0x7FF0_0000_0000_0000;
real x;
* cast(ulong *)(&x) = v;
return x;
}
else
{
v <<=11;
a &= 0x7FF;
v |= a;
real x = real.nan;
// Extended real bits
static if (real.mant_dig == 113)
{
//quadruple
v<<=1; // there's no implicit bit
version(LittleEndian)
{
*cast(ulong*)(6+cast(ubyte*)(&x)) = v;
}
else
{
*cast(ulong*)(2+cast(ubyte*)(&x)) = v;
}
}
else
{
// real80
* cast(ulong *)(&x) = v;
}
return x;
}
}
unittest
{
static if (real.mant_dig == 53)
{
auto x = NaN(1);
auto xl = *cast(ulong*)&x;
assert(xl & 0x8_0000_0000_0000UL); //non-signaling bit, bit 52
assert((xl & 0x7FF0_0000_0000_0000UL) == 0x7FF0_0000_0000_0000UL); //all exp bits set
}
}
/**
* Extract an integral payload from a $(NAN).
*
* Returns:
* the integer payload as a ulong.
*
* For floats, the largest possible payload is 0x3F_FFFF.
* For doubles, it is 0x3_FFFF_FFFF_FFFF.
* For 80-bit or 128-bit reals, it is 0x3FFF_FFFF_FFFF_FFFF.
*/
ulong getNaNPayload(real x) @trusted pure nothrow
{
// assert(isNaN(x));
static if (real.mant_dig == 53)
{
ulong m = *cast(ulong *)(&x);
// Make it look like an 80-bit significand.
// Skip exponent, and quiet bit
m &= 0x0007_FFFF_FFFF_FFFF;
m <<= 10;
}
else static if (real.mant_dig==113)
{
// quadruple
version(LittleEndian)
{
ulong m = *cast(ulong*)(6+cast(ubyte*)(&x));
}
else
{
ulong m = *cast(ulong*)(2+cast(ubyte*)(&x));
}
m >>= 1; // there's no implicit bit
}
else
{
ulong m = *cast(ulong *)(&x);
}
// ignore implicit bit and quiet bit
ulong f = m & 0x3FFF_FF00_0000_0000L;
ulong w = f >>> 40;
w |= (m & 0x00FF_FFFF_F800L) << (22 - 11);
w |= (m & 0x7FF) << 51;
return w;
}
debug(UnitTest)
{
unittest
{
real nan4 = NaN(0x789_ABCD_EF12_3456);
static if (real.mant_dig == 64 || real.mant_dig == 113)
{
assert (getNaNPayload(nan4) == 0x789_ABCD_EF12_3456);
}
else
{
assert (getNaNPayload(nan4) == 0x1_ABCD_EF12_3456);
}
double nan5 = nan4;
assert (getNaNPayload(nan5) == 0x1_ABCD_EF12_3456);
float nan6 = nan4;
assert (getNaNPayload(nan6) == 0x12_3456);
nan4 = NaN(0xFABCD);
assert (getNaNPayload(nan4) == 0xFABCD);
nan6 = nan4;
assert (getNaNPayload(nan6) == 0xFABCD);
nan5 = NaN(0x100_0000_0000_3456);
assert(getNaNPayload(nan5) == 0x0000_0000_3456);
}
}
/**
* Calculate the next largest floating point value after x.
*
* Return the least number greater than x that is representable as a real;
* thus, it gives the next point on the IEEE number line.
*
* $(TABLE_SV
* $(SVH x, nextUp(x) )
* $(SV -$(INFIN), -real.max )
* $(SV $(PLUSMN)0.0, real.min_normal*real.epsilon )
* $(SV real.max, $(INFIN) )
* $(SV $(INFIN), $(INFIN) )
* $(SV $(NAN), $(NAN) )
* )
*/
real nextUp(real x) @trusted pure nothrow
{
alias F = floatTraits!(real);
static if (real.mant_dig == 53)
{
// double
return nextUp(cast(double)x);
}
else static if (real.mant_dig == 113)
{
// quadruple
ushort e = F.EXPMASK & (cast(ushort *)&x)[F.EXPPOS_SHORT];
if (e == F.EXPMASK)
{
// NaN or Infinity
if (x == -real.infinity) return -real.max;
return x; // +Inf and NaN are unchanged.
}
ulong* ps = cast(ulong *)&e;
if (ps[MANTISSA_LSB] & 0x8000_0000_0000_0000)
{
// Negative number
if (ps[MANTISSA_LSB] == 0
&& ps[MANTISSA_MSB] == 0x8000_0000_0000_0000)
{
// it was negative zero, change to smallest subnormal
ps[MANTISSA_LSB] = 0x0000_0000_0000_0001;
ps[MANTISSA_MSB] = 0;
return x;
}
--*ps;
if (ps[MANTISSA_LSB]==0) --ps[MANTISSA_MSB];
}
else
{
// Positive number
++ps[MANTISSA_LSB];
if (ps[MANTISSA_LSB]==0) ++ps[MANTISSA_MSB];
}
return x;
}
else static if(real.mant_dig==64) // real80
{
// For 80-bit reals, the "implied bit" is a nuisance...
ushort *pe = cast(ushort *)&x;
ulong *ps = cast(ulong *)&x;
if ((pe[F.EXPPOS_SHORT] & F.EXPMASK) == F.EXPMASK)
{
// First, deal with NANs and infinity
if (x == -real.infinity) return -real.max;
return x; // +Inf and NaN are unchanged.
}
if (pe[F.EXPPOS_SHORT] & 0x8000)
{
// Negative number -- need to decrease the significand
--*ps;
// Need to mask with 0x7FFF... so subnormals are treated correctly.
if ((*ps & 0x7FFF_FFFF_FFFF_FFFF) == 0x7FFF_FFFF_FFFF_FFFF)
{
if (pe[F.EXPPOS_SHORT] == 0x8000) // it was negative zero
{
*ps = 1;
pe[F.EXPPOS_SHORT] = 0; // smallest subnormal.
return x;
}
--pe[F.EXPPOS_SHORT];
if (pe[F.EXPPOS_SHORT] == 0x8000)
return x; // it's become a subnormal, implied bit stays low.
*ps = 0xFFFF_FFFF_FFFF_FFFF; // set the implied bit
return x;
}
return x;
}
else
{
// Positive number -- need to increase the significand.
// Works automatically for positive zero.
++*ps;
if ((*ps & 0x7FFF_FFFF_FFFF_FFFF) == 0)
{
// change in exponent
++pe[F.EXPPOS_SHORT];
*ps = 0x8000_0000_0000_0000; // set the high bit
}
}
return x;
}
else // static if (real.mant_dig==106) // real is doubledouble
{
assert (0, "nextUp not implemented");
}
}
/** ditto */
double nextUp(double x) @trusted pure nothrow
{
ulong *ps = cast(ulong *)&x;
if ((*ps & 0x7FF0_0000_0000_0000) == 0x7FF0_0000_0000_0000)
{
// First, deal with NANs and infinity
if (x == -x.infinity) return -x.max;
return x; // +INF and NAN are unchanged.
}
if (*ps & 0x8000_0000_0000_0000) // Negative number
{
if (*ps == 0x8000_0000_0000_0000) // it was negative zero
{
*ps = 0x0000_0000_0000_0001; // change to smallest subnormal
return x;
}
--*ps;
}
else
{ // Positive number
++*ps;
}
return x;
}
/** ditto */
float nextUp(float x) @trusted pure nothrow
{
uint *ps = cast(uint *)&x;
if ((*ps & 0x7F80_0000) == 0x7F80_0000)
{
// First, deal with NANs and infinity
if (x == -x.infinity) return -x.max;
return x; // +INF and NAN are unchanged.
}
if (*ps & 0x8000_0000) // Negative number
{
if (*ps == 0x8000_0000) // it was negative zero
{
*ps = 0x0000_0001; // change to smallest subnormal
return x;
}
--*ps;
}
else
{
// Positive number
++*ps;
}
return x;
}
/**
* Calculate the next smallest floating point value before x.
*
* Return the greatest number less than x that is representable as a real;
* thus, it gives the previous point on the IEEE number line.
*
* $(TABLE_SV
* $(SVH x, nextDown(x) )
* $(SV $(INFIN), real.max )
* $(SV $(PLUSMN)0.0, -real.min_normal*real.epsilon )
* $(SV -real.max, -$(INFIN) )
* $(SV -$(INFIN), -$(INFIN) )
* $(SV $(NAN), $(NAN) )
* )
*/
real nextDown(real x) @safe pure nothrow
{
return -nextUp(-x);
}
/** ditto */
double nextDown(double x) @safe pure nothrow
{
return -nextUp(-x);
}
/** ditto */
float nextDown(float x) @safe pure nothrow
{
return -nextUp(-x);
}
unittest
{
assert( nextDown(1.0 + real.epsilon) == 1.0);
}
unittest
{
static if (real.mant_dig == 64)
{
// Tests for 80-bit reals
assert(isIdentical(nextUp(NaN(0xABC)), NaN(0xABC)));
// negative numbers
assert( nextUp(-real.infinity) == -real.max );
assert( nextUp(-1.0L-real.epsilon) == -1.0 );
assert( nextUp(-2.0L) == -2.0 + real.epsilon);
// subnormals and zero
assert( nextUp(-real.min_normal) == -real.min_normal*(1-real.epsilon) );
assert( nextUp(-real.min_normal*(1-real.epsilon)) == -real.min_normal*(1-2*real.epsilon) );
assert( isIdentical(-0.0L, nextUp(-real.min_normal*real.epsilon)) );
assert( nextUp(-0.0L) == real.min_normal*real.epsilon );
assert( nextUp(0.0L) == real.min_normal*real.epsilon );
assert( nextUp(real.min_normal*(1-real.epsilon)) == real.min_normal );
assert( nextUp(real.min_normal) == real.min_normal*(1+real.epsilon) );
// positive numbers
assert( nextUp(1.0L) == 1.0 + real.epsilon );
assert( nextUp(2.0L-real.epsilon) == 2.0 );
assert( nextUp(real.max) == real.infinity );
assert( nextUp(real.infinity)==real.infinity );
}
double n = NaN(0xABC);
assert(isIdentical(nextUp(n), n));
// negative numbers
assert( nextUp(-double.infinity) == -double.max );
assert( nextUp(-1-double.epsilon) == -1.0 );
assert( nextUp(-2.0) == -2.0 + double.epsilon);
// subnormals and zero
assert( nextUp(-double.min_normal) == -double.min_normal*(1-double.epsilon) );
assert( nextUp(-double.min_normal*(1-double.epsilon)) == -double.min_normal*(1-2*double.epsilon) );
assert( isIdentical(-0.0, nextUp(-double.min_normal*double.epsilon)) );
assert( nextUp(0.0) == double.min_normal*double.epsilon );
assert( nextUp(-0.0) == double.min_normal*double.epsilon );
assert( nextUp(double.min_normal*(1-double.epsilon)) == double.min_normal );
assert( nextUp(double.min_normal) == double.min_normal*(1+double.epsilon) );
// positive numbers
assert( nextUp(1.0) == 1.0 + double.epsilon );
assert( nextUp(2.0-double.epsilon) == 2.0 );
assert( nextUp(double.max) == double.infinity );
float fn = NaN(0xABC);
assert(isIdentical(nextUp(fn), fn));
float f = -float.min_normal*(1-float.epsilon);
float f1 = -float.min_normal;
assert( nextUp(f1) == f);
f = 1.0f+float.epsilon;
f1 = 1.0f;
assert( nextUp(f1) == f );
f1 = -0.0f;
assert( nextUp(f1) == float.min_normal*float.epsilon);
assert( nextUp(float.infinity)==float.infinity );
assert(nextDown(1.0L+real.epsilon)==1.0);
assert(nextDown(1.0+double.epsilon)==1.0);
f = 1.0f+float.epsilon;
assert(nextDown(f)==1.0);
assert(nextafter(1.0+real.epsilon, -real.infinity)==1.0);
}
/******************************************
* Calculates the next representable value after x in the direction of y.
*
* If y > x, the result will be the next largest floating-point value;
* if y < x, the result will be the next smallest value.
* If x == y, the result is y.
*
* Remarks:
* This function is not generally very useful; it's almost always better to use
* the faster functions nextUp() or nextDown() instead.
*
* The FE_INEXACT and FE_OVERFLOW exceptions will be raised if x is finite and
* the function result is infinite. The FE_INEXACT and FE_UNDERFLOW
* exceptions will be raised if the function value is subnormal, and x is
* not equal to y.
*/
T nextafter(T)(T x, T y) @safe pure nothrow
{
if (x==y) return y;
return ((y>x) ? nextUp(x) : nextDown(x));
}
unittest
{
float a = 1;
assert(is(typeof(nextafter(a, a)) == float));
assert(nextafter(a, a.infinity) > a);
double b = 2;
assert(is(typeof(nextafter(b, b)) == double));
assert(nextafter(b, b.infinity) > b);
real c = 3;
assert(is(typeof(nextafter(c, c)) == real));
assert(nextafter(c, c.infinity) > c);
}
//real nexttoward(real x, real y) { return core.stdc.math.nexttowardl(x, y); }
/*******************************************
* Returns the positive difference between x and y.
* Returns:
* $(TABLE_SV
* $(TR $(TH x, y) $(TH fdim(x, y)))
* $(TR $(TD x $(GT) y) $(TD x - y))
* $(TR $(TD x $(LT)= y) $(TD +0.0))
* )
*/
real fdim(real x, real y) @safe pure nothrow { return (x > y) ? x - y : +0.0; }
/****************************************
* Returns the larger of x and y.
*/
real fmax(real x, real y) @safe pure nothrow { return x > y ? x : y; }
/****************************************
* Returns the smaller of x and y.
*/
real fmin(real x, real y) @safe pure nothrow { return x < y ? x : y; }
/**************************************
* Returns (x * y) + z, rounding only once according to the
* current rounding mode.
*
* BUGS: Not currently implemented - rounds twice.
*/
real fma(real x, real y, real z) @safe pure nothrow { return (x * y) + z; }
/*******************************************************************
* Compute the value of x $(SUP n), where n is an integer
*/
Unqual!F pow(F, G)(F x, G n) @trusted pure nothrow
if (isFloatingPoint!(F) && isIntegral!(G))
{
real p = 1.0, v = void;
Unsigned!(Unqual!G) m = n;
if (n < 0)
{
switch (n)
{
case -1:
return 1 / x;
case -2:
return 1 / (x * x);
default:
}
m = -n;
v = p / x;
}
else
{
switch (n)
{
case 0:
return 1.0;
case 1:
return x;
case 2:
return x * x;
default:
}
v = x;
}
while (1)
{
if (m & 1)
p *= v;
m >>= 1;
if (!m)
break;
v *= v;
}
return p;
}
unittest
{
// Make sure it instantiates and works properly on immutable values and
// with various integer and float types.
immutable real x = 46;
immutable float xf = x;
immutable double xd = x;
immutable uint one = 1;
immutable ushort two = 2;
immutable ubyte three = 3;
immutable ulong eight = 8;
immutable int neg1 = -1;
immutable short neg2 = -2;
immutable byte neg3 = -3;
immutable long neg8 = -8;
assert(pow(x,0) == 1.0);
assert(pow(xd,one) == x);
assert(pow(xf,two) == x * x);
assert(pow(x,three) == x * x * x);
assert(pow(x,eight) == (x * x) * (x * x) * (x * x) * (x * x));
assert(pow(x, neg1) == 1 / x);
version(X86_64)
{
pragma(msg, "test disabled on x86_64, see bug 5628");
}
else version(ARM)
{
pragma(msg, "test disabled on ARM, see bug 5628");
}
else
{
assert(pow(xd, neg2) == 1 / (x * x));
assert(pow(xf, neg8) == 1 / ((x * x) * (x * x) * (x * x) * (x * x)));
}
assert(feqrel(pow(x, neg3), 1 / (x * x * x)) >= real.mant_dig - 1);
}
unittest
{
assert(equalsDigit(pow(2.0L, 10.0L), 1024, 19));
}
/** Compute the value of an integer x, raised to the power of a positive
* integer n.
*
* If both x and n are 0, the result is 1.
* If n is negative, an integer divide error will occur at runtime,
* regardless of the value of x.
*/
typeof(Unqual!(F).init * Unqual!(G).init) pow(F, G)(F x, G n) @trusted pure nothrow
if (isIntegral!(F) && isIntegral!(G))
{
if (n<0) return x/0; // Only support positive powers
typeof(return) p, v = void;
Unqual!G m = n;
switch (m)
{
case 0:
p = 1;
break;
case 1:
p = x;
break;
case 2:
p = x * x;
break;
default:
v = x;
p = 1;
while (1){
if (m & 1)
p *= v;
m >>= 1;
if (!m)
break;
v *= v;
}
break;
}
return p;
}
unittest
{
immutable int one = 1;
immutable byte two = 2;
immutable ubyte three = 3;
immutable short four = 4;
immutable long ten = 10;
assert(pow(two, three) == 8);
assert(pow(two, ten) == 1024);
assert(pow(one, ten) == 1);
assert(pow(ten, four) == 10_000);
assert(pow(four, 10) == 1_048_576);
assert(pow(three, four) == 81);
}
/**Computes integer to floating point powers.*/
real pow(I, F)(I x, F y) @trusted pure nothrow
if(isIntegral!I && isFloatingPoint!F)
{
return pow(cast(real) x, cast(Unqual!F) y);
}
/*********************************************
* Calculates x$(SUP y).
*
* $(TABLE_SV
* $(TR $(TH x) $(TH y) $(TH pow(x, y))
* $(TH div 0) $(TH invalid?))
* $(TR $(TD anything) $(TD $(PLUSMN)0.0) $(TD 1.0)
* $(TD no) $(TD no) )
* $(TR $(TD |x| $(GT) 1) $(TD +$(INFIN)) $(TD +$(INFIN))
* $(TD no) $(TD no) )
* $(TR $(TD |x| $(LT) 1) $(TD +$(INFIN)) $(TD +0.0)
* $(TD no) $(TD no) )
* $(TR $(TD |x| $(GT) 1) $(TD -$(INFIN)) $(TD +0.0)
* $(TD no) $(TD no) )
* $(TR $(TD |x| $(LT) 1) $(TD -$(INFIN)) $(TD +$(INFIN))
* $(TD no) $(TD no) )
* $(TR $(TD +$(INFIN)) $(TD $(GT) 0.0) $(TD +$(INFIN))
* $(TD no) $(TD no) )
* $(TR $(TD +$(INFIN)) $(TD $(LT) 0.0) $(TD +0.0)
* $(TD no) $(TD no) )
* $(TR $(TD -$(INFIN)) $(TD odd integer $(GT) 0.0) $(TD -$(INFIN))
* $(TD no) $(TD no) )
* $(TR $(TD -$(INFIN)) $(TD $(GT) 0.0, not odd integer) $(TD +$(INFIN))
* $(TD no) $(TD no))
* $(TR $(TD -$(INFIN)) $(TD odd integer $(LT) 0.0) $(TD -0.0)
* $(TD no) $(TD no) )
* $(TR $(TD -$(INFIN)) $(TD $(LT) 0.0, not odd integer) $(TD +0.0)
* $(TD no) $(TD no) )
* $(TR $(TD $(PLUSMN)1.0) $(TD $(PLUSMN)$(INFIN)) $(TD $(NAN))
* $(TD no) $(TD yes) )
* $(TR $(TD $(LT) 0.0) $(TD finite, nonintegral) $(TD $(NAN))
* $(TD no) $(TD yes))
* $(TR $(TD $(PLUSMN)0.0) $(TD odd integer $(LT) 0.0) $(TD $(PLUSMNINF))
* $(TD yes) $(TD no) )
* $(TR $(TD $(PLUSMN)0.0) $(TD $(LT) 0.0, not odd integer) $(TD +$(INFIN))
* $(TD yes) $(TD no))
* $(TR $(TD $(PLUSMN)0.0) $(TD odd integer $(GT) 0.0) $(TD $(PLUSMN)0.0)
* $(TD no) $(TD no) )
* $(TR $(TD $(PLUSMN)0.0) $(TD $(GT) 0.0, not odd integer) $(TD +0.0)
* $(TD no) $(TD no) )
* )
*/
Unqual!(Largest!(F, G)) pow(F, G)(F x, G y) @trusted pure nothrow
if (isFloatingPoint!(F) && isFloatingPoint!(G))
{
alias Float = typeof(return);
static real impl(real x, real y) pure nothrow
{
// Special cases.
if (isNaN(y))
return y;
if (isNaN(x) && y != 0.0)
return x;
// Even if x is NaN.
if (y == 0.0)
return 1.0;
if (y == 1.0)
return x;
if (isInfinity(y))
{
if (fabs(x) > 1)
{
if (signbit(y))
return +0.0;
else
return F.infinity;
}
else if (fabs(x) == 1)
{
return y * 0; // generate NaN.
}
else // < 1
{
if (signbit(y))
return F.infinity;
else
return +0.0;
}
}
if (isInfinity(x))
{
if (signbit(x))
{
long i = cast(long)y;
if (y > 0.0)
{
if (i == y && i & 1)
return -F.infinity;
else
return F.infinity;
}
else if (y < 0.0)
{
if (i == y && i & 1)
return -0.0;
else
return +0.0;
}
}
else
{
if (y > 0.0)
return F.infinity;
else if (y < 0.0)
return +0.0;
}
}
if (x == 0.0)
{
if (signbit(x))
{
long i = cast(long)y;
if (y > 0.0)
{
if (i == y && i & 1)
return -0.0;
else
return +0.0;
}
else if (y < 0.0)
{
if (i == y && i & 1)
return -F.infinity;
else
return F.infinity;
}
}
else
{
if (y > 0.0)
return +0.0;
else if (y < 0.0)
return F.infinity;
}
}
if (x == 1.0)
return 1.0;
if (y >= F.max)
{
if ((x > 0.0 && x < 1.0) || (x > -1.0 && x < 0.0))
return 0.0;
if (x > 1.0 || x < -1.0)
return F.infinity;
}
if (y <= -F.max)
{
if ((x > 0.0 && x < 1.0) || (x > -1.0 && x < 0.0))
return F.infinity;
if (x > 1.0 || x < -1.0)
return 0.0;
}
if (x >= F.max)
{
if (y > 0.0)
return F.infinity;
else
return 0.0;
}
if (x <= -F.max)
{
long i = cast(long)y;
if (y > 0.0)
{
if (i == y && i & 1)
return -F.infinity;
else
return F.infinity;
}
else if (y < 0.0)
{
if (i == y && i & 1)
return -0.0;
else
return +0.0;
}
}
// Integer power of x.
long iy = cast(long)y;
if (iy == y && fabs(y) < 32768.0)
return pow(x, iy);
double sign = 1.0;
if (x < 0)
{
// Result is real only if y is an integer
// Check for a non-zero fractional part
if (y > -1.0 / real.epsilon && y < 1.0 / real.epsilon)
{
long w = cast(long)y;
if (w != y)
return sqrt(x); // Complex result -- create a NaN
if (w & 1) sign = -1.0;
}
x = -x;
}
version(INLINE_YL2X)
{
// If x > 0, x ^^ y == 2 ^^ ( y * log2(x) )
// TODO: This is not accurate in practice. A fast and accurate
// (though complicated) method is described in:
// "An efficient rounding boundary test for pow(x, y)
// in double precision", C.Q. Lauter and V. Lefèvre, INRIA (2007).
return sign * exp2( yl2x(x, y) );
}
else
{
// If x > 0, x ^^ y == 2 ^^ ( y * log2(x) )
// TODO: This is not accurate in practice. A fast and accurate
// (though complicated) method is described in:
// "An efficient rounding boundary test for pow(x, y)
// in double precision", C.Q. Lauter and V. Lefèvre, INRIA (2007).
Float w = exp2(y * log2(x));
return sign * w;
}
}
return impl(x, y);
}
unittest
{
// Test all the special values. These unittests can be run on Windows
// by temporarily changing the version(linux) to version(all).
immutable float zero = 0;
immutable real one = 1;
immutable double two = 2;
immutable float three = 3;
immutable float fnan = float.nan;
immutable double dnan = double.nan;
immutable real rnan = real.nan;
immutable dinf = double.infinity;
immutable rninf = -real.infinity;
assert(pow(fnan, zero) == 1);
assert(pow(dnan, zero) == 1);
assert(pow(rnan, zero) == 1);
assert(pow(two, dinf) == double.infinity);
assert(isIdentical(pow(0.2f, dinf), +0.0));
assert(pow(0.99999999L, rninf) == real.infinity);
assert(isIdentical(pow(1.000000001, rninf), +0.0));
assert(pow(dinf, 0.001) == dinf);
assert(isIdentical(pow(dinf, -0.001), +0.0));
assert(pow(rninf, 3.0L) == rninf);
assert(pow(rninf, 2.0L) == real.infinity);
assert(isIdentical(pow(rninf, -3.0), -0.0));
assert(isIdentical(pow(rninf, -2.0), +0.0));
// @@@BUG@@@ somewhere
version(OSX) {} else assert(isNaN(pow(one, dinf)));
version(OSX) {} else assert(isNaN(pow(-one, dinf)));
assert(isNaN(pow(-0.2, PI)));
// boundary cases. Note that epsilon == 2^^-n for some n,
// so 1/epsilon == 2^^n is always even.
assert(pow(-1.0L, 1/real.epsilon - 1.0L) == -1.0L);
assert(pow(-1.0L, 1/real.epsilon) == 1.0L);
assert(isNaN(pow(-1.0L, 1/real.epsilon-0.5L)));
assert(isNaN(pow(-1.0L, -1/real.epsilon+0.5L)));
assert(pow(0.0, -3.0) == double.infinity);
assert(pow(-0.0, -3.0) == -double.infinity);
assert(pow(0.0, -PI) == double.infinity);
assert(pow(-0.0, -PI) == double.infinity);
assert(isIdentical(pow(0.0, 5.0), 0.0));
assert(isIdentical(pow(-0.0, 5.0), -0.0));
assert(isIdentical(pow(0.0, 6.0), 0.0));
assert(isIdentical(pow(-0.0, 6.0), 0.0));
// Now, actual numbers.
assert(approxEqual(pow(two, three), 8.0));
assert(approxEqual(pow(two, -2.5), 0.1767767));
// Test integer to float power.
immutable uint twoI = 2;
assert(approxEqual(pow(twoI, three), 8.0));
}
/**************************************
* To what precision is x equal to y?
*
* Returns: the number of mantissa bits which are equal in x and y.
* eg, 0x1.F8p+60 and 0x1.F1p+60 are equal to 5 bits of precision.
*
* $(TABLE_SV
* $(TR $(TH x) $(TH y) $(TH feqrel(x, y)))
* $(TR $(TD x) $(TD x) $(TD real.mant_dig))
* $(TR $(TD x) $(TD $(GT)= 2*x) $(TD 0))
* $(TR $(TD x) $(TD $(LT)= x/2) $(TD 0))
* $(TR $(TD $(NAN)) $(TD any) $(TD 0))
* $(TR $(TD any) $(TD $(NAN)) $(TD 0))
* )
*/
int feqrel(X)(X x, X y) @trusted pure nothrow
if (isFloatingPoint!(X))
{
/* Public Domain. Author: Don Clugston, 18 Aug 2005.
*/
static if (X.mant_dig == 106) // doubledouble
{
if (cast(double*)(&x)[MANTISSA_MSB] == cast(double*)(&y)[MANTISSA_MSB])
{
return double.mant_dig
+ feqrel(cast(double*)(&x)[MANTISSA_LSB],
cast(double*)(&y)[MANTISSA_LSB]);
}
else
{
return feqrel(cast(double*)(&x)[MANTISSA_MSB],
cast(double*)(&y)[MANTISSA_MSB]);
}
}
else
{
static assert( X.mant_dig == 64 || X.mant_dig == 113
|| X.mant_dig == double.mant_dig || X.mant_dig == float.mant_dig);
if (x == y)
return X.mant_dig; // ensure diff!=0, cope with INF.
X diff = fabs(x - y);
ushort *pa = cast(ushort *)(&x);
ushort *pb = cast(ushort *)(&y);
ushort *pd = cast(ushort *)(&diff);
alias F = floatTraits!(X);
// The difference in abs(exponent) between x or y and abs(x-y)
// is equal to the number of significand bits of x which are
// equal to y. If negative, x and y have different exponents.
// If positive, x and y are equal to 'bitsdiff' bits.
// AND with 0x7FFF to form the absolute value.
// To avoid out-by-1 errors, we subtract 1 so it rounds down
// if the exponents were different. This means 'bitsdiff' is
// always 1 lower than we want, except that if bitsdiff==0,
// they could have 0 or 1 bits in common.
static if (X.mant_dig == 64 || X.mant_dig == 113)
{ // real80 or quadruple
int bitsdiff = ( ((pa[F.EXPPOS_SHORT] & F.EXPMASK)
+ (pb[F.EXPPOS_SHORT] & F.EXPMASK) - 1) >> 1)
- pd[F.EXPPOS_SHORT];
}
else static if (X.mant_dig == double.mant_dig)
{ // double
int bitsdiff = (( ((pa[F.EXPPOS_SHORT]&0x7FF0)
+ (pb[F.EXPPOS_SHORT]&0x7FF0)-0x10)>>1)
- (pd[F.EXPPOS_SHORT]&0x7FF0))>>4;
}
else static if (X.mant_dig == float.mant_dig)
{ // float
int bitsdiff = (( ((pa[F.EXPPOS_SHORT]&0x7F80)
+ (pb[F.EXPPOS_SHORT]&0x7F80)-0x80)>>1)
- (pd[F.EXPPOS_SHORT]&0x7F80))>>7;
}
if ( (pd[F.EXPPOS_SHORT] & F.EXPMASK) == 0)
{ // Difference is subnormal
// For subnormals, we need to add the number of zeros that
// lie at the start of diff's significand.
// We do this by multiplying by 2^^real.mant_dig
diff *= F.RECIP_EPSILON;
return bitsdiff + X.mant_dig - pd[F.EXPPOS_SHORT];
}
if (bitsdiff > 0)
return bitsdiff + 1; // add the 1 we subtracted before
// Avoid out-by-1 errors when factor is almost 2.
static if (X.mant_dig == 64 || X.mant_dig == 113)
{ // real80 or quadruple
return (bitsdiff == 0) ? (pa[F.EXPPOS_SHORT] == pb[F.EXPPOS_SHORT]) : 0;
}
else static if (X.mant_dig == double.mant_dig || X.mant_dig == float.mant_dig)
{
if (bitsdiff == 0
&& !((pa[F.EXPPOS_SHORT] ^ pb[F.EXPPOS_SHORT]) & F.EXPMASK))
{
return 1;
} else return 0;
}
}
}
unittest
{
void testFeqrel(F)()
{
// Exact equality
assert(feqrel(F.max, F.max) == F.mant_dig);
assert(feqrel!(F)(0.0, 0.0) == F.mant_dig);
assert(feqrel(F.infinity, F.infinity) == F.mant_dig);
// a few bits away from exact equality
F w=1;
for (int i = 1; i < F.mant_dig - 1; ++i)
{
assert(feqrel!(F)(1.0 + w * F.epsilon, 1.0) == F.mant_dig-i);
assert(feqrel!(F)(1.0 - w * F.epsilon, 1.0) == F.mant_dig-i);
assert(feqrel!(F)(1.0, 1 + (w-1) * F.epsilon) == F.mant_dig - i + 1);
w*=2;
}
assert(feqrel!(F)(1.5+F.epsilon, 1.5) == F.mant_dig-1);
assert(feqrel!(F)(1.5-F.epsilon, 1.5) == F.mant_dig-1);
assert(feqrel!(F)(1.5-F.epsilon, 1.5+F.epsilon) == F.mant_dig-2);
// Numbers that are close
assert(feqrel!(F)(0x1.Bp+84, 0x1.B8p+84) == 5);
assert(feqrel!(F)(0x1.8p+10, 0x1.Cp+10) == 2);
assert(feqrel!(F)(1.5 * (1 - F.epsilon), 1.0L) == 2);
assert(feqrel!(F)(1.5, 1.0) == 1);
assert(feqrel!(F)(2 * (1 - F.epsilon), 1.0L) == 1);
// Factors of 2
assert(feqrel(F.max, F.infinity) == 0);
assert(feqrel!(F)(2 * (1 - F.epsilon), 1.0L) == 1);
assert(feqrel!(F)(1.0, 2.0) == 0);
assert(feqrel!(F)(4.0, 1.0) == 0);
// Extreme inequality
assert(feqrel(F.nan, F.nan) == 0);
assert(feqrel!(F)(0.0L, -F.nan) == 0);
assert(feqrel(F.nan, F.infinity) == 0);
assert(feqrel(F.infinity, -F.infinity) == 0);
assert(feqrel(F.max, -F.max) == 0);
}
assert(feqrel(7.1824L, 7.1824L) == real.mant_dig);
static if(real.mant_dig == 64)
{
assert(feqrel(real.min_normal / 8, real.min_normal / 17) == 3);
}
testFeqrel!(real)();
testFeqrel!(double)();
testFeqrel!(float)();
}
package: // Not public yet
/* Return the value that lies halfway between x and y on the IEEE number line.
*
* Formally, the result is the arithmetic mean of the binary significands of x
* and y, multiplied by the geometric mean of the binary exponents of x and y.
* x and y must have the same sign, and must not be NaN.
* Note: this function is useful for ensuring O(log n) behaviour in algorithms
* involving a 'binary chop'.
*
* Special cases:
* If x and y are within a factor of 2, (ie, feqrel(x, y) > 0), the return value
* is the arithmetic mean (x + y) / 2.
* If x and y are even powers of 2, the return value is the geometric mean,
* ieeeMean(x, y) = sqrt(x * y).
*
*/
T ieeeMean(T)(T x, T y) @trusted pure nothrow
in
{
// both x and y must have the same sign, and must not be NaN.
assert(signbit(x) == signbit(y));
assert(x==x && y==y);
}
body
{
// Runtime behaviour for contract violation:
// If signs are opposite, or one is a NaN, return 0.
if (!((x>=0 && y>=0) || (x<=0 && y<=0))) return 0.0;
// The implementation is simple: cast x and y to integers,
// average them (avoiding overflow), and cast the result back to a floating-point number.
alias F = floatTraits!(real);
T u;
static if (T.mant_dig==64)
{ // real80
// There's slight additional complexity because they are actually
// 79-bit reals...
ushort *ue = cast(ushort *)&u;
ulong *ul = cast(ulong *)&u;
ushort *xe = cast(ushort *)&x;
ulong *xl = cast(ulong *)&x;
ushort *ye = cast(ushort *)&y;
ulong *yl = cast(ulong *)&y;
// Ignore the useless implicit bit. (Bonus: this prevents overflows)
ulong m = ((*xl) & 0x7FFF_FFFF_FFFF_FFFFL) + ((*yl) & 0x7FFF_FFFF_FFFF_FFFFL);
// @@@ BUG? @@@
// Cast shouldn't be here
ushort e = cast(ushort) ((xe[F.EXPPOS_SHORT] & F.EXPMASK)
+ (ye[F.EXPPOS_SHORT] & F.EXPMASK));
if (m & 0x8000_0000_0000_0000L)
{
++e;
m &= 0x7FFF_FFFF_FFFF_FFFFL;
}
// Now do a multi-byte right shift
uint c = e & 1; // carry
e >>= 1;
m >>>= 1;
if (c)
m |= 0x4000_0000_0000_0000L; // shift carry into significand
if (e)
*ul = m | 0x8000_0000_0000_0000L; // set implicit bit...
else
*ul = m; // ... unless exponent is 0 (subnormal or zero).
ue[4]= e | (xe[F.EXPPOS_SHORT]& 0x8000); // restore sign bit
}
else static if(T.mant_dig == 113)
{ //quadruple
// This would be trivial if 'ucent' were implemented...
ulong *ul = cast(ulong *)&u;
ulong *xl = cast(ulong *)&x;
ulong *yl = cast(ulong *)&y;
// Multi-byte add, then multi-byte right shift.
ulong mh = ((xl[MANTISSA_MSB] & 0x7FFF_FFFF_FFFF_FFFFL)
+ (yl[MANTISSA_MSB] & 0x7FFF_FFFF_FFFF_FFFFL));
// Discard the lowest bit (to avoid overflow)
ulong ml = (xl[MANTISSA_LSB]>>>1) + (yl[MANTISSA_LSB]>>>1);
// add the lowest bit back in, if necessary.
if (xl[MANTISSA_LSB] & yl[MANTISSA_LSB] & 1)
{
++ml;
if (ml==0) ++mh;
}
mh >>>=1;
ul[MANTISSA_MSB] = mh | (xl[MANTISSA_MSB] & 0x8000_0000_0000_0000);
ul[MANTISSA_LSB] = ml;
}
else static if (T.mant_dig == double.mant_dig)
{
ulong *ul = cast(ulong *)&u;
ulong *xl = cast(ulong *)&x;
ulong *yl = cast(ulong *)&y;
ulong m = (((*xl) & 0x7FFF_FFFF_FFFF_FFFFL)
+ ((*yl) & 0x7FFF_FFFF_FFFF_FFFFL)) >>> 1;
m |= ((*xl) & 0x8000_0000_0000_0000L);
*ul = m;
}
else static if (T.mant_dig == float.mant_dig)
{
uint *ul = cast(uint *)&u;
uint *xl = cast(uint *)&x;
uint *yl = cast(uint *)&y;
uint m = (((*xl) & 0x7FFF_FFFF) + ((*yl) & 0x7FFF_FFFF)) >>> 1;
m |= ((*xl) & 0x8000_0000);
*ul = m;
}
else
{
assert(0, "Not implemented");
}
return u;
}
unittest
{
assert(ieeeMean(-0.0,-1e-20)<0);
assert(ieeeMean(0.0,1e-20)>0);
assert(ieeeMean(1.0L,4.0L)==2L);
assert(ieeeMean(2.0*1.013,8.0*1.013)==4*1.013);
assert(ieeeMean(-1.0L,-4.0L)==-2L);
assert(ieeeMean(-1.0,-4.0)==-2);
assert(ieeeMean(-1.0f,-4.0f)==-2f);
assert(ieeeMean(-1.0,-2.0)==-1.5);
assert(ieeeMean(-1*(1+8*real.epsilon),-2*(1+8*real.epsilon))
==-1.5*(1+5*real.epsilon));
assert(ieeeMean(0x1p60,0x1p-10)==0x1p25);
static if (real.mant_dig == 64)
{
assert(ieeeMean(1.0L,real.infinity)==0x1p8192L);
assert(ieeeMean(0.0L,real.infinity)==1.5);
}
assert(ieeeMean(0.5*real.min_normal*(1-4*real.epsilon),0.5*real.min_normal)
== 0.5*real.min_normal*(1-2*real.epsilon));
}
public:
/***********************************
* Evaluate polynomial A(x) = $(SUB a, 0) + $(SUB a, 1)x + $(SUB a, 2)$(POWER x,2)
* + $(SUB a,3)$(POWER x,3); ...
*
* Uses Horner's rule A(x) = $(SUB a, 0) + x($(SUB a, 1) + x($(SUB a, 2)
* + x($(SUB a, 3) + ...)))
* Params:
* x = the value to evaluate.
* A = array of coefficients $(SUB a, 0), $(SUB a, 1), etc.
*/
real poly(real x, const real[] A) @trusted pure nothrow
in
{
assert(A.length > 0);
}
body
{
version (D_InlineAsm_X86)
{
version (Windows)
{
// BUG: This code assumes a frame pointer in EBP.
asm // assembler by W. Bright
{
// EDX = (A.length - 1) * real.sizeof
mov ECX,A[EBP] ; // ECX = A.length
dec ECX ;
lea EDX,[ECX][ECX*8] ;
add EDX,ECX ;
add EDX,A+4[EBP] ;
fld real ptr [EDX] ; // ST0 = coeff[ECX]
jecxz return_ST ;
fld x[EBP] ; // ST0 = x
fxch ST(1) ; // ST1 = x, ST0 = r
align 4 ;
L2: fmul ST,ST(1) ; // r *= x
fld real ptr -10[EDX] ;
sub EDX,10 ; // deg--
faddp ST(1),ST ;
dec ECX ;
jne L2 ;
fxch ST(1) ; // ST1 = r, ST0 = x
fstp ST(0) ; // dump x
align 4 ;
return_ST: ;
;
}
}
else version (linux)
{
asm // assembler by W. Bright
{
// EDX = (A.length - 1) * real.sizeof
mov ECX,A[EBP] ; // ECX = A.length
dec ECX ;
lea EDX,[ECX*8] ;
lea EDX,[EDX][ECX*4] ;
add EDX,A+4[EBP] ;
fld real ptr [EDX] ; // ST0 = coeff[ECX]
jecxz return_ST ;
fld x[EBP] ; // ST0 = x
fxch ST(1) ; // ST1 = x, ST0 = r
align 4 ;
L2: fmul ST,ST(1) ; // r *= x
fld real ptr -12[EDX] ;
sub EDX,12 ; // deg--
faddp ST(1),ST ;
dec ECX ;
jne L2 ;
fxch ST(1) ; // ST1 = r, ST0 = x
fstp ST(0) ; // dump x
align 4 ;
return_ST: ;
;
}
}
else version (OSX)
{
asm // assembler by W. Bright
{
// EDX = (A.length - 1) * real.sizeof
mov ECX,A[EBP] ; // ECX = A.length
dec ECX ;
lea EDX,[ECX*8] ;
add EDX,EDX ;
add EDX,A+4[EBP] ;
fld real ptr [EDX] ; // ST0 = coeff[ECX]
jecxz return_ST ;
fld x[EBP] ; // ST0 = x
fxch ST(1) ; // ST1 = x, ST0 = r
align 4 ;
L2: fmul ST,ST(1) ; // r *= x
fld real ptr -16[EDX] ;
sub EDX,16 ; // deg--
faddp ST(1),ST ;
dec ECX ;
jne L2 ;
fxch ST(1) ; // ST1 = r, ST0 = x
fstp ST(0) ; // dump x
align 4 ;
return_ST: ;
;
}
}
else version (FreeBSD)
{
asm // assembler by W. Bright
{
// EDX = (A.length - 1) * real.sizeof
mov ECX,A[EBP] ; // ECX = A.length
dec ECX ;
lea EDX,[ECX*8] ;
lea EDX,[EDX][ECX*4] ;
add EDX,A+4[EBP] ;
fld real ptr [EDX] ; // ST0 = coeff[ECX]
jecxz return_ST ;
fld x[EBP] ; // ST0 = x
fxch ST(1) ; // ST1 = x, ST0 = r
align 4 ;
L2: fmul ST,ST(1) ; // r *= x
fld real ptr -12[EDX] ;
sub EDX,12 ; // deg--
faddp ST(1),ST ;
dec ECX ;
jne L2 ;
fxch ST(1) ; // ST1 = r, ST0 = x
fstp ST(0) ; // dump x
align 4 ;
return_ST: ;
;
}
}
else
{
static assert(0);
}
}
else
{
ptrdiff_t i = A.length - 1;
real r = A[i];
while (--i >= 0)
{
r *= x;
r += A[i];
}
return r;
}
}
unittest
{
debug (math) printf("math.poly.unittest\n");
real x = 3.1;
static real[] pp = [56.1, 32.7, 6];
assert( poly(x, pp) == (56.1L + (32.7L + 6L * x) * x) );
}
/**
Computes whether $(D lhs) is approximately equal to $(D rhs)
admitting a maximum relative difference $(D maxRelDiff) and a
maximum absolute difference $(D maxAbsDiff).
If the two inputs are ranges, $(D approxEqual) returns true if and
only if the ranges have the same number of elements and if $(D
approxEqual) evaluates to $(D true) for each pair of elements.
*/
bool approxEqual(T, U, V)(T lhs, U rhs, V maxRelDiff, V maxAbsDiff = 1e-5)
{
import std.range;
static if (isInputRange!T)
{
static if (isInputRange!U)
{
// Two ranges
for (;; lhs.popFront(), rhs.popFront())
{
if (lhs.empty) return rhs.empty;
if (rhs.empty) return lhs.empty;
if (!approxEqual(lhs.front, rhs.front, maxRelDiff, maxAbsDiff))
return false;
}
}
else
{
// lhs is range, rhs is number
for (; !lhs.empty; lhs.popFront())
{
if (!approxEqual(lhs.front, rhs, maxRelDiff, maxAbsDiff))
return false;
}
return true;
}
}
else
{
static if (isInputRange!U)
{
// lhs is number, rhs is array
return approxEqual(rhs, lhs, maxRelDiff, maxAbsDiff);
}
else
{
// two numbers
//static assert(is(T : real) && is(U : real));
if (rhs == 0)
{
return fabs(lhs) <= maxAbsDiff;
}
static if (is(typeof(lhs.infinity)) && is(typeof(rhs.infinity)))
{
if (lhs == lhs.infinity && rhs == rhs.infinity ||
lhs == -lhs.infinity && rhs == -rhs.infinity) return true;
}
return fabs((lhs - rhs) / rhs) <= maxRelDiff
|| maxAbsDiff != 0 && fabs(lhs - rhs) <= maxAbsDiff;
}
}
}
/**
Returns $(D approxEqual(lhs, rhs, 1e-2, 1e-5)).
*/
bool approxEqual(T, U)(T lhs, U rhs)
{
return approxEqual(lhs, rhs, 1e-2, 1e-5);
}
unittest
{
assert(approxEqual(1.0, 1.0099));
assert(!approxEqual(1.0, 1.011));
float[] arr1 = [ 1.0, 2.0, 3.0 ];
double[] arr2 = [ 1.001, 1.999, 3 ];
assert(approxEqual(arr1, arr2));
real num = real.infinity;
assert(num == real.infinity); // Passes.
assert(approxEqual(num, real.infinity)); // Fails.
num = -real.infinity;
assert(num == -real.infinity); // Passes.
assert(approxEqual(num, -real.infinity)); // Fails.
}
// Included for backwards compatibility with Phobos1
alias isnan = isNaN;
alias isfinite = isFinite;
alias isnormal = isNormal;
alias issubnormal = isSubnormal;
alias isinf = isInfinity;
/* **********************************
* Building block functions, they
* translate to a single x87 instruction.
*/
real yl2x(real x, real y) @safe pure nothrow; // y * log2(x)
real yl2xp1(real x, real y) @safe pure nothrow; // y * log2(x + 1)
unittest
{
version (INLINE_YL2X)
{
assert(yl2x(1024, 1) == 10);
assert(yl2xp1(1023, 1) == 10);
}
}
unittest
{
real num = real.infinity;
assert(num == real.infinity); // Passes.
assert(approxEqual(num, real.infinity)); // Fails.
}
unittest
{
float f = sqrt(2.0f);
assert(fabs(f * f - 2.0f) < .00001);
double d = sqrt(2.0);
assert(fabs(d * d - 2.0) < .00001);
real r = sqrt(2.0L);
assert(fabs(r * r - 2.0) < .00001);
}
unittest
{
float f = fabs(-2.0f);
assert(f == 2);
double d = fabs(-2.0);
assert(d == 2);
real r = fabs(-2.0L);
assert(r == 2);
}
unittest
{
float f = sin(-2.0f);
assert(fabs(f - -0.909297f) < .00001);
double d = sin(-2.0);
assert(fabs(d - -0.909297f) < .00001);
real r = sin(-2.0L);
assert(fabs(r - -0.909297f) < .00001);
}
unittest
{
float f = cos(-2.0f);
assert(fabs(f - -0.416147f) < .00001);
double d = cos(-2.0);
assert(fabs(d - -0.416147f) < .00001);
real r = cos(-2.0L);
assert(fabs(r - -0.416147f) < .00001);
}
unittest
{
float f = tan(-2.0f);
assert(fabs(f - 2.18504f) < .00001);
double d = tan(-2.0);
assert(fabs(d - 2.18504f) < .00001);
real r = tan(-2.0L);
assert(fabs(r - 2.18504f) < .00001);
}
pure @safe nothrow unittest
{
// issue 6381: floor/ceil should be usable in pure function.
auto x = floor(1.2);
auto y = ceil(1.2);
}
|
D
|
module android.java.android.print.PrintAttributes_MediaSize_d_interface;
import arsd.jni : IJavaObjectImplementation, JavaPackageId, JavaName, IJavaObject, ImportExportImpl, JavaInterfaceMembers;
static import arsd.jni;
import import1 = android.java.android.print.PrintAttributes_MediaSize_d_interface;
import import2 = android.java.java.lang.Class_d_interface;
import import0 = android.java.android.content.pm.PackageManager_d_interface;
@JavaName("PrintAttributes$MediaSize")
final class PrintAttributes_MediaSize : IJavaObject {
static immutable string[] _d_canCastTo = [
];
@Import this(string, string, int, int);
@Import string getId();
@Import string getLabel(import0.PackageManager);
@Import int getWidthMils();
@Import int getHeightMils();
@Import bool isPortrait();
@Import import1.PrintAttributes_MediaSize asPortrait();
@Import import1.PrintAttributes_MediaSize asLandscape();
@Import int hashCode();
@Import bool equals(IJavaObject);
@Import @JavaName("toString") string toString_();
override string toString() { return arsd.jni.javaObjectToString(this); }
@Import import2.Class getClass();
@Import void notify();
@Import void notifyAll();
@Import void wait(long);
@Import void wait(long, int);
@Import void wait();
mixin IJavaObjectImplementation!(false);
public static immutable string _javaParameterString = "Landroid/print/PrintAttributes$MediaSize;";
}
|
D
|
instance VLK_481_Buerger(Npc_Default)
{
name[0] = NAME_Buerger;
guild = GIL_VLK;
id = 481;
voice = 6;
flags = 0;
npcType = NPCTYPE_AMBIENT;
aivar[AIV_ToughGuy] = TRUE;
B_SetAttributesToChapter(self,1);
level = 1;
fight_tactic = FAI_HUMAN_COWARD;
aivar[AIV_MM_RestStart] = TRUE;
EquipItem(self,ItMw_1h_Vlk_Dagger);
B_CreateAmbientInv(self);
B_SetNpcVisual(self,MALE,"Hum_Head_Bald",Face_N_Normal20,BodyTex_N,ITAR_Vlk_L);
Mdl_SetModelFatness(self,0);
Mdl_ApplyOverlayMds(self,"Humans_Tired.mds");
B_GiveNpcTalents(self);
B_SetFightSkills(self,30);
daily_routine = Rtn_Start_481;
};
func void Rtn_Start_481()
{
TA_Cook_Cauldron(5,5,12,5,"NW_CITY_PATH_HABOUR_13_C");
TA_Smalltalk(12,5,15,55,"NW_CITY_HABOUR_SMALLTALK_02");
TA_Cook_Cauldron(15,55,20,5,"NW_CITY_PATH_HABOUR_13_C");
TA_Smalltalk(20,5,23,55,"NW_CITY_HABOUR_SMALLTALK_02");
TA_Sleep(23,55,5,5,"NW_CITY_HABOUR_HUT_06_BED_02");
};
|
D
|
module hunt.wechat.bean.datacube.article.Usershare;
class Usershare {
private string ref_date;
private Integer ref_hour;
private Integer share_scene;
private Integer share_count;
private Integer share_user;
public string getRef_date() {
return ref_date;
}
public void setRef_date(string ref_date) {
this.ref_date = ref_date;
}
public Integer getRef_hour() {
return ref_hour;
}
public void setRef_hour(Integer ref_hour) {
this.ref_hour = ref_hour;
}
public Integer getShare_scene() {
return share_scene;
}
public void setShare_scene(Integer share_scene) {
this.share_scene = share_scene;
}
public Integer getShare_count() {
return share_count;
}
public void setShare_count(Integer share_count) {
this.share_count = share_count;
}
public Integer getShare_user() {
return share_user;
}
public void setShare_user(Integer share_user) {
this.share_user = share_user;
}
}
|
D
|
module org.serviio.external.io.OutputTextReader;
import java.lang.String;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.serviio.external.ProcessExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.serviio.external.io.OutputReader;
public class OutputTextReader : OutputReader
{
private static immutable Logger log = LoggerFactory.getLogger!(OutputTextReader)();
private List!(String) lines = new ArrayList!(String)();
private Object linesLock;
private ProcessExecutor executor;
public this(ProcessExecutor executor, InputStream inputStream)
{
super(inputStream);
linesLock = new Object();
this.executor = executor;
}
override protected void processOutput()
{
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(inputStream, Charset.defaultCharset()));
String line = null;
while ((line = br.readLine()) !is null)
if (line.length() > 0) {
addLine(line);
executor.notifyListenersOutputUpdated(line);
log.trace(line);
}
}
catch (IOException e) {
log.warn(String.format("Error reading output of an external command:" + e.getMessage(), new Object[0]));
} finally {
if (br !is null)
try {
br.close(); } catch (Exception e) {
}
}
}
override public ByteArrayOutputStream getOutputStream() {
return null;
}
override public List!(String) getResults() {
List!(String) clonedResults = new ArrayList!(String)();
synchronized (linesLock) {
clonedResults.addAll(lines);
}
return clonedResults;
}
private void addLine(String line)
{
synchronized (linesLock) {
lines.add(line);
}
}
}
/* Location: D:\Program Files\Serviio\lib\serviio.jar
* Qualified Name: org.serviio.external.io.OutputTextReader
* JD-Core Version: 0.6.2
*/
|
D
|
/home/hedayat/holo/tutorial/art_game/zomes/game/code/target/rls/debug/deps/fake_simd-b1149a7ef0b1fdfe.rmeta: /home/hedayat/.cargo/registry/src/github.com-1ecc6299db9ec823/fake-simd-0.1.2/src/lib.rs
/home/hedayat/holo/tutorial/art_game/zomes/game/code/target/rls/debug/deps/fake_simd-b1149a7ef0b1fdfe.d: /home/hedayat/.cargo/registry/src/github.com-1ecc6299db9ec823/fake-simd-0.1.2/src/lib.rs
/home/hedayat/.cargo/registry/src/github.com-1ecc6299db9ec823/fake-simd-0.1.2/src/lib.rs:
|
D
|
class A {
string f() {
return 123;
}
}
int main() {
A a;
a = new A;
Print("Hiii");
Print(a.f());
}
|
D
|
/** Authors: Lars Tandle Kyllingstad
Copyright: Copyright (c) 2009, Lars T. Kyllingstad. All rights reserved.
License: Boost License 1.0
*/
module scid.ports.quadpack.qawf;
import std.conv;
import scid.ports.quadpack.qawfe;
version(unittest)
{
import std.math;
import scid.core.testing;
}
///
void qawf(Real, Func)(Func f, Real a, Real omega, int integr, Real epsabs,
out Real result, out Real abserr, out int neval, out int ier,
int limlst, out int lst, int leniw, int maxp1, int lenw,
int* iwork, Real* work)
{
//***begin prologue dqawf
//***date written 800101 (yymmdd)
//***revision date 830518 (yymmdd)
//***category no. h2a3a1
//***keywords automatic integrator, special-purpose,fourier
// integral, integration between zeros with dqawoe,
// convergence acceleration with dqelg
//***author piessens,robert ,appl. math. & progr. div. - k.u.leuven
// de doncker,elise,appl. math & progr. div. - k.u.leuven
//***purpose the routine calculates an approximation result to a given
// fourier integral i=integral of f(x)*w(x) over (a,infinity)
// where w(x) = cos(omega*x) or w(x) = sin(omega*x).
// hopefully satisfying following claim for accuracy
// abs(i-result).le.epsabs.
//***description
//
// computation of fourier integrals
// standard fortran subroutine
// double precision version
//
//
// parameters
// on entry
// f - double precision
// function subprogram defining the integrand
// function f(x). the actual name for f needs to be
// declared e x t e r n a l in the driver program.
//
// a - double precision
// lower limit of integration
//
// omega - double precision
// parameter in the integrand weight function
//
// integr - integer
// indicates which of the weight functions is used
// integr = 1 w(x) = cos(omega*x)
// integr = 2 w(x) = sin(omega*x)
// if integr.ne.1.and.integr.ne.2, the routine
// will end with ier = 6.
//
// epsabs - double precision
// absolute accuracy requested, epsabs.gt.0.
// if epsabs.le.0, the routine will end with ier = 6.
//
// on return
// result - double precision
// approximation to the integral
//
// abserr - double precision
// estimate of the modulus of the absolute error,
// which should equal or exceed abs(i-result)
//
// neval - integer
// number of integrand evaluations
//
// ier - integer
// ier = 0 normal and reliable termination of the
// routine. it is assumed that the requested
// accuracy has been achieved.
// ier.gt.0 abnormal termination of the routine.
// the estimates for integral and error are
// less reliable. it is assumed that the
// requested accuracy has not been achieved.
// error messages
// if omega.ne.0
// ier = 1 maximum number of cycles allowed
// has been achieved, i.e. of subintervals
// (a+(k-1)c,a+kc) where
// c = (2*int(abs(omega))+1)*pi/abs(omega),
// for k = 1, 2, ..., lst.
// one can allow more cycles by increasing
// the value of limlst (and taking the
// according dimension adjustments into
// account). examine the array iwork which
// contains the error flags on the cycles, in
// order to look for eventual local
// integration difficulties.
// if the position of a local difficulty
// can be determined (e.g. singularity,
// discontinuity within the interval) one
// will probably gain from splitting up the
// interval at this point and calling
// appropriate integrators on the subranges.
// = 4 the extrapolation table constructed for
// convergence accelaration of the series
// formed by the integral contributions over
// the cycles, does not converge to within
// the requested accuracy.
// as in the case of ier = 1, it is advised
// to examine the array iwork which contains
// the error flags on the cycles.
// = 6 the input is invalid because
// (integr.ne.1 and integr.ne.2) or
// epsabs.le.0 or limlst.lt.1 or
// leniw.lt.(limlst+2) or maxp1.lt.1 or
// lenw.lt.(leniw*2+maxp1*25).
// result, abserr, neval, lst are set to
// zero.
// = 7 bad integrand behaviour occurs within
// one or more of the cycles. location and
// type of the difficulty involved can be
// determined from the first lst elements of
// vector iwork. here lst is the number of
// cycles actually needed (see below).
// iwork(k) = 1 the maximum number of
// subdivisions (=(leniw-limlst)
// /2) has been achieved on the
// k th cycle.
// = 2 occurrence of roundoff error
// is detected and prevents the
// tolerance imposed on the k th
// cycle, from being achieved
// on this cycle.
// = 3 extremely bad integrand
// behaviour occurs at some
// points of the k th cycle.
// = 4 the integration procedure
// over the k th cycle does
// not converge (to within the
// required accuracy) due to
// roundoff in the extrapolation
// procedure invoked on this
// cycle. it is assumed that the
// result on this interval is
// the best which can be
// obtained.
// = 5 the integral over the k th
// cycle is probably divergent
// or slowly convergent. it must
// be noted that divergence can
// occur with any other value of
// iwork(k).
// if omega = 0 and integr = 1,
// the integral is calculated by means of dqagie,
// and ier = iwork(1) (with meaning as described
// for iwork(k),k = 1).
//
// dimensioning parameters
// limlst - integer
// limlst gives an upper bound on the number of
// cycles, limlst.ge.3.
// if limlst.lt.3, the routine will end with ier = 6.
//
// lst - integer
// on return, lst indicates the number of cycles
// actually needed for the integration.
// if omega = 0, then lst is set to 1.
//
// leniw - integer
// dimensioning parameter for iwork. on entry,
// (leniw-limlst)/2 equals the maximum number of
// subintervals allowed in the partition of each
// cycle, leniw.ge.(limlst+2).
// if leniw.lt.(limlst+2), the routine will end with
// ier = 6.
//
// maxp1 - integer
// maxp1 gives an upper bound on the number of
// chebyshev moments which can be stored, i.e. for
// the intervals of lengths abs(b-a)*2**(-l),
// l = 0,1, ..., maxp1-2, maxp1.ge.1.
// if maxp1.lt.1, the routine will end with ier = 6.
// lenw - integer
// dimensioning parameter for work
// lenw must be at least leniw*2+maxp1*25.
// if lenw.lt.(leniw*2+maxp1*25), the routine will
// end with ier = 6.
//
// work arrays
// iwork - integer
// vector of dimension at least leniw
// on return, iwork(k) for k = 1, 2, ..., lst
// contain the error flags on the cycles.
//
// work - double precision
// vector of dimension at least
// on return,
// work(1), ..., work(lst) contain the integral
// approximations over the cycles,
// work(limlst+1), ..., work(limlst+lst) contain
// the error extimates over the cycles.
// further elements of work have no specific
// meaning for the user.
//
//***references (none)
//***routines called dqawfe,xerror
//***end prologue dqawf
//
int last, limit, ll2,l1,l2,l3,l4,l5,l6;
//
// check validity of limlst, leniw, maxp1 and lenw.
//
//***first executable statement dqawf
ier = 6;
neval = 0;
last = 0;
result = 0.0;
abserr = 0.0;
if(limlst < 3 || leniw < (limlst+2) || maxp1 < 1 || lenw <
(leniw*2+maxp1*25)) goto l10;
//
// prepare call for dqawfe
//
limit = (leniw-limlst)/2;
l1 = limlst;
l2 = limlst+l1;
l3 = limit+l2;
l4 = limit+l3;
l5 = limit+l4;
l6 = limit+l5;
ll2 = limit+l1;
qawfe!(Real,Func)(f,a,omega,integr,epsabs,limlst,limit,maxp1,result,
abserr,neval,ier,work,work+l1,iwork,lst,work+l2,
work+l3,work+l4,work+l5,iwork+l1,iwork+ll2,work+l6);
//
// call error handler if necessary
//
l10: if(ier != 0)
throw new Exception("abnormal return from qawf: "~to!string(ier));
return;
}
unittest
{
alias qawf!(float, float delegate(float)) fqawf;
alias qawf!(double, double delegate(double)) dqawf;
alias qawf!(double, double function(double)) dfqawf;
alias qawf!(real, real delegate(real)) rqawf;
}
unittest
{
double f(double x) { return x > 0.0 ? 1/sqrt(x) : 0.0; }
enum : double
{
a = 0.0,
omega = PI_2,
epsabs = 1e-8,
}
double result, abserr;
int neval, ier, lst;
enum
{
integr = 1, // cos(pi x/2)
limlst = 50,
leniw = 1050,
maxp1 = 21,
lenw = leniw*2 + maxp1*25
}
int[leniw] iwork;
double[lenw] work;
qawf(&f, a, omega, integr, epsabs, result, abserr, neval, ier, limlst,
lst, leniw, maxp1, lenw, iwork.ptr, work.ptr);
}
unittest
{
// This is integral 14 in the QUADPACK book.
real alpha;
real f(real x) { return x <= 0.0 ? 0.0 : exp(-(2.0L^^(-alpha))*x)/sqrt(x); }
enum real omega = 1.0;
enum integr = 1; // cos(x)
enum : real
{
a = 0.0,
epsabs = 1e-8
}
real result, abserr;
int neval, ier, lst;
enum
{
limlst = 50,
leniw = 1050,
maxp1 = 21,
lenw = leniw*2 + maxp1*25
}
int[leniw] iwork;
real[lenw] work;
alpha = 0.0;
qawf(&f, a, omega, integr, epsabs, result, abserr, neval, ier, limlst,
lst, leniw, maxp1, lenw, iwork.ptr, work.ptr);
real ans = sqrt(PI) * ((1+(4.0L^^(-alpha)))^^(-0.25L))
* cos(atan(2.0L^^alpha)/2);
check (isAccurate(result, abserr, ans, 0.0L, epsabs));
}
|
D
|
// Copyright © 2010-2011, Bernard Helyer. All rights reserved.
// Copyright © 2012, Jakob Bornecrantz. All rights reserved.
// See copyright notice in src/volt/license.d (BOOST ver. 1.0).
module volt.token.token;
import volt.token.location;
/* If you're adding a new token, be sure to update:
* - the tokenToString array. Keep it alphabetical, and update its length.
* - the TokenType enum, again keep it alphabetical. It's _vital_ that the order
* is the same in the TokenType enum and the tokenToString array.
* - if you're adding a keyword, add it to identifierType.
*
* Removing is the same thing in reverse. When modifying tokenToString, be sure
* to keep commas between elements -- two string literals straight after one
* another are implicitly concatenated. I warn you of this out of experience.
*/
string[181] tokenToString = [
"none", "identifier", "string literal", "character literal",
"integer literal", "float literal", "abstract", "alias", "align",
"asm", "assert", "auto", "body", "bool", "break", "byte", "case",
"cast", "catch", "cdouble", "cent", "cfloat", "char", "class",
"const", "continue", "creal", "dchar", "debug", "default",
"delegate", "delete", "deprecated", "do", "double", "else", "enum",
"export", "extern", "false", "final", "finally", "float", "for",
"foreach", "foreach_reverse", "function", "global", "goto", "idouble", "if",
"ifloat", "immutable", "import", "in", "inout", "int", "interface",
"invariant", "ireal", "is", "lazy", "local", "long", "macro", "mixin", "module",
"new", "nothrow", "null", "out", "override", "package", "pragma",
"private", "protected", "public", "pure", "real", "ref", "return",
"scope", "shared", "short", "static", "struct", "super",
"switch", "synchronized", "template", "this", "throw", "true",
"try", "typedef", "typeid", "typeof", "ubyte", "ucent", "uint",
"ulong", "union", "unittest", "ushort", "version", "void", "volatile",
"wchar", "while", "with", "__FILE__", "__FUNCTION__", "__LINE__", "__PRETTY_FUNCTION__",
"__thread", "__traits",
"/", "/=", ".", "..", "...", "&", "&=", "&&", "|", "|=", "||",
"-", "-=", "--", "+", "+=", "++", "<", "<=", "<<", "<<=", "<>", "<>=",
">", ">=", ">>=", ">>>=", ">>", ">>>", "!", "!=", "!<>", "!<>=", "!<",
"!<=", "!>", "!>=", "(", ")", "[", "]", "{", "}", "?", ",", ";",
":", "$", "=", "==", "*", "*=", "%", "%=", "^", "^=", "^^", "^^=", "~", "~=",
"@",
"symbol", "number", "BEGIN", "EOF"
];
/**
* Ensure that the above list and following enum stay in sync,
* and that the enum starts at zero and increases sequentially
* (i.e. adding a member increases TokenType.max).
*/
static assert(TokenType.min == 0);
static assert(tokenToString.length == TokenType.max + 1, "the tokenToString array and TokenType enum are out of sync.");
static assert(TokenType.max + 1 == __traits(allMembers, TokenType).length, "all TokenType enum members must be sequential.");
enum TokenType
{
None = 0,
// Literals
Identifier,
StringLiteral,
CharacterLiteral,
IntegerLiteral,
FloatLiteral,
// Keywords
Abstract, Alias, Align, Asm, Assert, Auto,
Body, Bool, Break, Byte,
Case, Cast, Catch, Cdouble, Cent, Cfloat, Char,
Class, Const, Continue, Creal,
Dchar, Debug, Default, Delegate, Delete,
Deprecated, Do, Double,
Else, Enum, Export, Extern,
False, Final, Finally, Float, For, Foreach,
ForeachReverse, Function,
Global, Goto,
Idouble, If, Ifloat, Immutable, Import, In,
Inout, Int, Interface, Invariant, Ireal, Is,
Lazy, Local, Long,
Macro, Mixin, Module,
New, Nothrow, Null,
Out, Override,
Package, Pragma, Private, Protected, Public, Pure,
Real, Ref, Return,
Scope, Shared, Short, Static, Struct, Super,
Switch, Synchronized,
Template, This, Throw, True, Try, Typedef,
Typeid, Typeof,
Ubyte, Ucent, Uint, Ulong, Union, Unittest, Ushort,
Version, Void, Volatile,
Wchar, While, With,
__File__, __Function__, __Line__, __Pretty_Function__, __Thread, __Traits,
/// Symbols.
Slash, // /
SlashAssign, // /=
Dot, // .
DoubleDot, // ..
TripleDot, // ...
Ampersand, // &
AmpersandAssign, // &=
DoubleAmpersand, // &&
Pipe, // |
PipeAssign, // |=
DoublePipe, // ||
Dash, // -
DashAssign, // -=
DoubleDash, // --
Plus, // +
PlusAssign, // +=
DoublePlus, // ++
Less, // <
LessAssign, // <=
DoubleLess, // <<
DoubleLessAssign, // <<=
LessGreater, // <>
LessGreaterAssign, // <>=
Greater, // >
GreaterAssign, // >=
DoubleGreaterAssign, // >>=
TripleGreaterAssign, // >>>=
DoubleGreater, // >>
TripleGreater, // >>>
Bang, // !
BangAssign, // !=
BangLessGreater, // !<>
BangLessGreaterAssign, // !<>=
BangLess, // !<
BangLessAssign, // !<=
BangGreater, // !>
BangGreaterAssign, // !>=
OpenParen, // (
CloseParen, // )
OpenBracket, // [
CloseBracket, // ]
OpenBrace, // {
CloseBrace, // }
QuestionMark, // ?
Comma, // ,
Semicolon, // ;
Colon, // :
Dollar, // $
Assign, // =
DoubleAssign, // ==
Asterix, // *
AsterixAssign, // *=
Percent, // %
PercentAssign, // %=
Caret, // ^
CaretAssign, // ^=
DoubleCaret, // ^^
DoubleCaretAssign, // ^^=
Tilde, // ~
TildeAssign, // ~=
At, // @
Symbol,
Number,
Begin,
End,
}
/**
* Holds the type, the actual string and location within the source file.
*/
final class Token
{
TokenType type;
string value;
Location location;
}
/**
* Go from a string identifier to a TokenType.
*
* Side-effects:
* None.
*
* Returns:
* Always a TokenType, for unknown ones TokenType.Identifier.
*/
TokenType identifierType(string ident)
{
switch(ident) with (TokenType) {
case "abstract": return Abstract;
case "alias": return Alias;
case "align": return Align;
case "asm": return Asm;
case "assert": return Assert;
case "auto": return Auto;
case "body": return Body;
case "bool": return Bool;
case "break": return Break;
case "byte": return Byte;
case "case": return Case;
case "cast": return Cast;
case "catch": return Catch;
case "cdouble": return Cdouble;
case "cent": return Cent;
case "cfloat": return Cfloat;
case "char": return Char;
case "class": return Class;
case "const": return Const;
case "continue": return Continue;
case "creal": return Creal;
case "dchar": return Dchar;
case "debug": return Debug;
case "default": return Default;
case "delegate": return Delegate;
case "delete": return Delete;
case "deprecated": return Deprecated;
case "do": return Do;
case "double": return Double;
case "else": return Else;
case "enum": return Enum;
case "export": return Export;
case "extern": return Extern;
case "false": return False;
case "final": return Final;
case "finally": return Finally;
case "float": return Float;
case "for": return For;
case "foreach": return Foreach;
case "foreach_reverse": return ForeachReverse;
case "function": return Function;
case "global": return Global;
case "goto": return Goto;
case "idouble": return Idouble;
case "if": return If;
case "ifloat": return Ifloat;
case "immutable": return Immutable;
case "import": return Import;
case "in": return In;
case "inout": return Inout;
case "int": return Int;
case "interface": return Interface;
case "invariant": return Invariant;
case "ireal": return Ireal;
case "is": return Is;
case "lazy": return Lazy;
case "local": return Local;
case "long": return Long;
case "macro": return Macro;
case "mixin": return Mixin;
case "module": return Module;
case "new": return New;
case "nothrow": return Nothrow;
case "null": return Null;
case "out": return Out;
case "override": return Override;
case "package": return Package;
case "pragma": return Pragma;
case "private": return Private;
case "protected": return Protected;
case "public": return Public;
case "pure": return Pure;
case "real": return Real;
case "ref": return Ref;
case "return": return Return;
case "scope": return Scope;
case "shared": return Shared;
case "short": return Short;
case "static": return Static;
case "struct": return Struct;
case "super": return Super;
case "switch": return Switch;
case "synchronized": return Synchronized;
case "template": return Template;
case "this": return This;
case "throw": return Throw;
case "true": return True;
case "try": return Try;
case "typedef": return Typedef;
case "typeid": return Typeid;
case "typeof": return Typeof;
case "ubyte": return Ubyte;
case "ucent": return Ucent;
case "uint": return Uint;
case "ulong": return Ulong;
case "union": return Union;
case "unittest": return Unittest;
case "ushort": return Ushort;
case "version": return Version;
case "void": return Void;
case "volatile": return Volatile;
case "wchar": return Wchar;
case "while": return While;
case "with": return With;
case "__FILE__": return __File__;
case "__FUNCTION__": return __Function__;
case "__LINE__": return __Line__;
case "__PRETTY_FUNCTION__": return __Pretty_Function__;
case "__thread": return __Thread;
case "__traits": return __Traits;
default: return Identifier;
}
}
|
D
|
/Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/MarathonCore.build/Create.swift.o : /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Add.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Command.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Codable+TypeInference.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Package.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Executable.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/MarathonFile.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Update.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Create.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Remove.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Task.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Install.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Perform.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/URL+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/String+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Folder+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/ShellOut+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Array+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Run.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Help.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/PackageManager.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/ScriptManager.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/ZshAutocompleteInstaller.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/FishAutocompleteInstaller.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Printer.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/PrintableError.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Edit.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Script.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/List.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Require.swiftmodule /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Files.swiftmodule /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Releases.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/ShellOut.swiftmodule /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/RunnerLib.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Require.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/MarathonCore.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Logger.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Danger.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/DangerShellExecutor.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Files.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/DangerFixtures.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Releases.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/OctoKit.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/RequestKit.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/dangertest.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/ShellOut.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/MarathonCore.build/Create~partial.swiftmodule : /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Add.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Command.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Codable+TypeInference.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Package.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Executable.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/MarathonFile.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Update.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Create.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Remove.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Task.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Install.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Perform.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/URL+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/String+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Folder+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/ShellOut+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Array+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Run.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Help.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/PackageManager.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/ScriptManager.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/ZshAutocompleteInstaller.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/FishAutocompleteInstaller.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Printer.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/PrintableError.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Edit.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Script.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/List.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Require.swiftmodule /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Files.swiftmodule /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Releases.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/ShellOut.swiftmodule /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/RunnerLib.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Require.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/MarathonCore.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Logger.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Danger.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/DangerShellExecutor.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Files.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/DangerFixtures.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Releases.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/OctoKit.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/RequestKit.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/dangertest.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/ShellOut.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/MarathonCore.build/Create~partial.swiftdoc : /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Add.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Command.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Codable+TypeInference.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Package.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Executable.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/MarathonFile.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Update.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Create.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Remove.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Task.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Install.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Perform.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/URL+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/String+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Folder+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/ShellOut+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Array+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Run.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Help.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/PackageManager.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/ScriptManager.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/ZshAutocompleteInstaller.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/FishAutocompleteInstaller.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Printer.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/PrintableError.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Edit.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Script.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/List.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Require.swiftmodule /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Files.swiftmodule /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Releases.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/ShellOut.swiftmodule /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/RunnerLib.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Require.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/MarathonCore.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Logger.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Danger.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/DangerShellExecutor.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Files.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/DangerFixtures.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Releases.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/OctoKit.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/RequestKit.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/dangertest.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/ShellOut.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/MarathonCore.build/Create~partial.swiftsourceinfo : /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Add.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Command.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Codable+TypeInference.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Package.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Executable.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/MarathonFile.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Update.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Create.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Remove.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Task.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Install.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Perform.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/URL+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/String+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Folder+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/ShellOut+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Array+Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Marathon.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Run.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Help.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/PackageManager.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/ScriptManager.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/ZshAutocompleteInstaller.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/FishAutocompleteInstaller.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Printer.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/PrintableError.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Edit.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/Script.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/checkouts/Marathon/Sources/MarathonCore/List.swift /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Require.swiftmodule /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Files.swiftmodule /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Releases.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/ShellOut.swiftmodule /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/RunnerLib.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Require.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/MarathonCore.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Logger.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Danger.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/DangerShellExecutor.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Files.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/DangerFixtures.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/Releases.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/OctoKit.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/RequestKit.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/dangertest.build/module.modulemap /Users/angelo/Developer/DroppedBits/DangerTest/.build/x86_64-apple-macosx/debug/ShellOut.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
|
D
|
// for optional dependency
// for VT on Windows P s = 1 8 → Report the size of the text area in characters as CSI 8 ; height ; width t
// could be used to have the TE volunteer the size
/++
Module for interacting with the user's terminal, including color output, cursor manipulation, and full-featured real-time mouse and keyboard input. Also includes high-level convenience methods, like [Terminal.getline], which gives the user a line editor with history, completion, etc. See the [#examples].
The main interface for this module is the Terminal struct, which
encapsulates the output functions and line-buffered input of the terminal, and
RealTimeConsoleInput, which gives real time input.
Creating an instance of these structs will perform console initialization. When the struct
goes out of scope, any changes in console settings will be automatically reverted.
Note: on Posix, it traps SIGINT and translates it into an input event. You should
keep your event loop moving and keep an eye open for this to exit cleanly; simply break
your event loop upon receiving a UserInterruptionEvent. (Without
the signal handler, ctrl+c can leave your terminal in a bizarre state.)
As a user, if you have to forcibly kill your program and the event doesn't work, there's still ctrl+\
On old Mac Terminal btw, a lot of hacks are needed and mouse support doesn't work. Most functions basically
work now with newer Mac OS versions though.
Future_Roadmap:
$(LIST
* The CharacterEvent and NonCharacterKeyEvent types will be removed. Instead, use KeyboardEvent
on new programs.
* The ScrollbackBuffer will be expanded to be easier to use to partition your screen. It might even
handle input events of some sort. Its API may change.
* getline I want to be really easy to use both for code and end users. It will need multi-line support
eventually.
* I might add an expandable event loop and base level widget classes. This may be Linux-specific in places and may overlap with similar functionality in simpledisplay.d. If I can pull it off without a third module, I want them to be compatible with each other too so the two modules can be combined easily. (Currently, they are both compatible with my eventloop.d and can be easily combined through it, but that is a third module.)
* More advanced terminal features as functions, where available, like cursor changing and full-color functions.
* More documentation.
)
WHAT I WON'T DO:
$(LIST
* support everything under the sun. If it isn't default-installed on an OS I or significant number of other people
might actually use, and isn't written by me, I don't really care about it. This means the only supported terminals are:
$(LIST
* xterm (and decently xterm compatible emulators like Konsole)
* Windows console
* rxvt (to a lesser extent)
* Linux console
* My terminal emulator family of applications https://github.com/adamdruppe/terminal-emulator
)
Anything else is cool if it does work, but I don't want to go out of my way for it.
* Use other libraries, unless strictly optional. terminal.d is a stand-alone module by default and
always will be.
* Do a full TUI widget set. I might do some basics and lay a little groundwork, but a full TUI
is outside the scope of this module (unless I can do it really small.)
)
+/
module arsd.terminal;
// FIXME: needs to support VT output on Windows too in certain situations
// detect VT on windows by trying to set the flag. if this succeeds, ask it for caps. if this replies with my code we good to do extended output.
/++
$(H3 Get Line)
This example will demonstrate the high-level getline interface.
The user will be able to type a line and navigate around it with cursor keys and even the mouse on some systems, as well as perform editing as they expect (e.g. the backspace and delete keys work normally) until they press enter. Then, the final line will be returned to your program, which the example will simply print back to the user.
+/
version(demos) unittest {
import arsd.terminal;
void main() {
auto terminal = Terminal(ConsoleOutputType.linear);
string line = terminal.getline();
terminal.writeln("You wrote: ", line);
}
main; // exclude from docs
}
/++
$(H3 Color)
This example demonstrates color output, using [Terminal.color]
and the output functions like [Terminal.writeln].
+/
version(demos) unittest {
import arsd.terminal;
void main() {
auto terminal = Terminal(ConsoleOutputType.linear);
terminal.color(Color.green, Color.black);
terminal.writeln("Hello world, in green on black!");
terminal.color(Color.DEFAULT, Color.DEFAULT);
terminal.writeln("And back to normal.");
}
main; // exclude from docs
}
/++
$(H3 Single Key)
This shows how to get one single character press using
the [RealTimeConsoleInput] structure.
+/
version(demos) unittest {
import arsd.terminal;
void main() {
auto terminal = Terminal(ConsoleOutputType.linear);
auto input = RealTimeConsoleInput(&terminal, ConsoleInputFlags.raw);
terminal.writeln("Press any key to continue...");
auto ch = input.getch();
terminal.writeln("You pressed ", ch);
}
main; // exclude from docs
}
/*
Widgets:
tab widget
scrollback buffer
partitioned canvas
*/
// FIXME: ctrl+d eof on stdin
// FIXME: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686016%28v=vs.85%29.aspx
/++
A function the sigint handler will call (if overridden - which is the
case when [RealTimeConsoleInput] is active on Posix or if you compile with
`TerminalDirectToEmulator` version on any platform at this time) in addition
to the library's default handling, which is to set a flag for the event loop
to inform you.
Remember, this is called from a signal handler and/or from a separate thread,
so you are not allowed to do much with it and need care when setting TLS variables.
I suggest you only set a `__gshared bool` flag as many other operations will risk
undefined behavior.
$(WARNING
This function is never called on the default Windows console
configuration in the current implementation. You can use
`-version=TerminalDirectToEmulator` to guarantee it is called there
too by causing the library to pop up a gui window for your application.
)
History:
Added March 30, 2020. Included in release v7.1.0.
+/
__gshared void delegate() nothrow @nogc sigIntExtension;
version(TerminalDirectToEmulator) {
version=WithEncapsulatedSignals;
}
version(Posix) {
enum SIGWINCH = 28;
__gshared bool windowSizeChanged = false;
__gshared bool interrupted = false; /// you might periodically check this in a long operation and abort if it is set. Remember it is volatile. It is also sent through the input event loop via RealTimeConsoleInput
__gshared bool hangedUp = false; /// similar to interrupted.
version=WithSignals;
version(with_eventloop)
struct SignalFired {}
extern(C)
void sizeSignalHandler(int sigNumber) nothrow {
windowSizeChanged = true;
version(with_eventloop) {
import arsd.eventloop;
try
send(SignalFired());
catch(Exception) {}
}
}
extern(C)
void interruptSignalHandler(int sigNumber) nothrow {
interrupted = true;
version(with_eventloop) {
import arsd.eventloop;
try
send(SignalFired());
catch(Exception) {}
}
if(sigIntExtension)
sigIntExtension();
}
extern(C)
void hangupSignalHandler(int sigNumber) nothrow {
hangedUp = true;
version(with_eventloop) {
import arsd.eventloop;
try
send(SignalFired());
catch(Exception) {}
}
}
}
// parts of this were taken from Robik's ConsoleD
// https://github.com/robik/ConsoleD/blob/master/consoled.d
// Uncomment this line to get a main() to demonstrate this module's
// capabilities.
//version = Demo
version(TerminalDirectToEmulator) {
version=VtEscapeCodes;
} else version(Windows) {
version(VtEscapeCodes) {} // cool
version=Win32Console;
}
version(Windows)
import core.sys.windows.windows;
version(Win32Console) {
private {
enum RED_BIT = 4;
enum GREEN_BIT = 2;
enum BLUE_BIT = 1;
}
pragma(lib, "user32");
}
version(Posix) {
version=VtEscapeCodes;
import core.sys.posix.termios;
import core.sys.posix.unistd;
import unix = core.sys.posix.unistd;
import core.sys.posix.sys.types;
import core.sys.posix.sys.time;
import core.stdc.stdio;
import core.sys.posix.sys.ioctl;
}
version(VtEscapeCodes) {
enum UseVtSequences = true;
version(TerminalDirectToEmulator) {
private {
enum RED_BIT = 1;
enum GREEN_BIT = 2;
enum BLUE_BIT = 4;
}
} else version(Windows) {} else
private {
enum RED_BIT = 1;
enum GREEN_BIT = 2;
enum BLUE_BIT = 4;
}
struct winsize {
ushort ws_row;
ushort ws_col;
ushort ws_xpixel;
ushort ws_ypixel;
}
// I'm taking this from the minimal termcap from my Slackware box (which I use as my /etc/termcap) and just taking the most commonly used ones (for me anyway).
// this way we'll have some definitions for 99% of typical PC cases even without any help from the local operating system
enum string builtinTermcap = `
# Generic VT entry.
vg|vt-generic|Generic VT entries:\
:bs:mi:ms:pt:xn:xo:it#8:\
:RA=\E[?7l:SA=\E?7h:\
:bl=^G:cr=^M:ta=^I:\
:cm=\E[%i%d;%dH:\
:le=^H:up=\E[A:do=\E[B:nd=\E[C:\
:LE=\E[%dD:RI=\E[%dC:UP=\E[%dA:DO=\E[%dB:\
:ho=\E[H:cl=\E[H\E[2J:ce=\E[K:cb=\E[1K:cd=\E[J:sf=\ED:sr=\EM:\
:ct=\E[3g:st=\EH:\
:cs=\E[%i%d;%dr:sc=\E7:rc=\E8:\
:ei=\E[4l:ic=\E[@:IC=\E[%d@:al=\E[L:AL=\E[%dL:\
:dc=\E[P:DC=\E[%dP:dl=\E[M:DL=\E[%dM:\
:so=\E[7m:se=\E[m:us=\E[4m:ue=\E[m:\
:mb=\E[5m:mh=\E[2m:md=\E[1m:mr=\E[7m:me=\E[m:\
:sc=\E7:rc=\E8:kb=\177:\
:ku=\E[A:kd=\E[B:kr=\E[C:kl=\E[D:
# Slackware 3.1 linux termcap entry (Sat Apr 27 23:03:58 CDT 1996):
lx|linux|console|con80x25|LINUX System Console:\
:do=^J:co#80:li#25:cl=\E[H\E[J:sf=\ED:sb=\EM:\
:le=^H:bs:am:cm=\E[%i%d;%dH:nd=\E[C:up=\E[A:\
:ce=\E[K:cd=\E[J:so=\E[7m:se=\E[27m:us=\E[36m:ue=\E[m:\
:md=\E[1m:mr=\E[7m:mb=\E[5m:me=\E[m:is=\E[1;25r\E[25;1H:\
:ll=\E[1;25r\E[25;1H:al=\E[L:dc=\E[P:dl=\E[M:\
:it#8:ku=\E[A:kd=\E[B:kr=\E[C:kl=\E[D:kb=^H:ti=\E[r\E[H:\
:ho=\E[H:kP=\E[5~:kN=\E[6~:kH=\E[4~:kh=\E[1~:kD=\E[3~:kI=\E[2~:\
:k1=\E[[A:k2=\E[[B:k3=\E[[C:k4=\E[[D:k5=\E[[E:k6=\E[17~:\
:F1=\E[23~:F2=\E[24~:\
:k7=\E[18~:k8=\E[19~:k9=\E[20~:k0=\E[21~:K1=\E[1~:K2=\E[5~:\
:K4=\E[4~:K5=\E[6~:\
:pt:sr=\EM:vt#3:xn:km:bl=^G:vi=\E[?25l:ve=\E[?25h:vs=\E[?25h:\
:sc=\E7:rc=\E8:cs=\E[%i%d;%dr:\
:r1=\Ec:r2=\Ec:r3=\Ec:
# Some other, commonly used linux console entries.
lx|con80x28:co#80:li#28:tc=linux:
lx|con80x43:co#80:li#43:tc=linux:
lx|con80x50:co#80:li#50:tc=linux:
lx|con100x37:co#100:li#37:tc=linux:
lx|con100x40:co#100:li#40:tc=linux:
lx|con132x43:co#132:li#43:tc=linux:
# vt102 - vt100 + insert line etc. VT102 does not have insert character.
v2|vt102|DEC vt102 compatible:\
:co#80:li#24:\
:ic@:IC@:\
:is=\E[m\E[?1l\E>:\
:rs=\E[m\E[?1l\E>:\
:eA=\E)0:as=^N:ae=^O:ac=aaffggjjkkllmmnnooqqssttuuvvwwxx:\
:ks=:ke=:\
:k1=\EOP:k2=\EOQ:k3=\EOR:k4=\EOS:\
:tc=vt-generic:
# vt100 - really vt102 without insert line, insert char etc.
vt|vt100|DEC vt100 compatible:\
:im@:mi@:al@:dl@:ic@:dc@:AL@:DL@:IC@:DC@:\
:tc=vt102:
# Entry for an xterm. Insert mode has been disabled.
vs|xterm|tmux|tmux-256color|xterm-kitty|screen|screen.xterm|screen-256color|screen.xterm-256color|xterm-color|xterm-256color|vs100|xterm terminal emulator (X Window System):\
:am:bs:mi@:km:co#80:li#55:\
:im@:ei@:\
:cl=\E[H\E[J:\
:ct=\E[3k:ue=\E[m:\
:is=\E[m\E[?1l\E>:\
:rs=\E[m\E[?1l\E>:\
:vi=\E[?25l:ve=\E[?25h:\
:eA=\E)0:as=^N:ae=^O:ac=aaffggjjkkllmmnnooqqssttuuvvwwxx:\
:kI=\E[2~:kD=\E[3~:kP=\E[5~:kN=\E[6~:\
:k1=\EOP:k2=\EOQ:k3=\EOR:k4=\EOS:k5=\E[15~:\
:k6=\E[17~:k7=\E[18~:k8=\E[19~:k9=\E[20~:k0=\E[21~:\
:F1=\E[23~:F2=\E[24~:\
:kh=\E[H:kH=\E[F:\
:ks=:ke=:\
:te=\E[2J\E[?47l\E8:ti=\E7\E[?47h:\
:tc=vt-generic:
#rxvt, added by me
rxvt|rxvt-unicode|rxvt-unicode-256color:\
:am:bs:mi@:km:co#80:li#55:\
:im@:ei@:\
:ct=\E[3k:ue=\E[m:\
:is=\E[m\E[?1l\E>:\
:rs=\E[m\E[?1l\E>:\
:vi=\E[?25l:\
:ve=\E[?25h:\
:eA=\E)0:as=^N:ae=^O:ac=aaffggjjkkllmmnnooqqssttuuvvwwxx:\
:kI=\E[2~:kD=\E[3~:kP=\E[5~:kN=\E[6~:\
:k1=\E[11~:k2=\E[12~:k3=\E[13~:k4=\E[14~:k5=\E[15~:\
:k6=\E[17~:k7=\E[18~:k8=\E[19~:k9=\E[20~:k0=\E[21~:\
:F1=\E[23~:F2=\E[24~:\
:kh=\E[7~:kH=\E[8~:\
:ks=:ke=:\
:te=\E[2J\E[?47l\E8:ti=\E7\E[?47h:\
:tc=vt-generic:
# Some other entries for the same xterm.
v2|xterms|vs100s|xterm small window:\
:co#80:li#24:tc=xterm:
vb|xterm-bold|xterm with bold instead of underline:\
:us=\E[1m:tc=xterm:
vi|xterm-ins|xterm with insert mode:\
:mi:im=\E[4h:ei=\E[4l:tc=xterm:
Eterm|Eterm Terminal Emulator (X11 Window System):\
:am:bw:eo:km:mi:ms:xn:xo:\
:co#80:it#8:li#24:lm#0:pa#64:Co#8:AF=\E[3%dm:AB=\E[4%dm:op=\E[39m\E[49m:\
:AL=\E[%dL:DC=\E[%dP:DL=\E[%dM:DO=\E[%dB:IC=\E[%d@:\
:K1=\E[7~:K2=\EOu:K3=\E[5~:K4=\E[8~:K5=\E[6~:LE=\E[%dD:\
:RI=\E[%dC:UP=\E[%dA:ae=^O:al=\E[L:as=^N:bl=^G:cd=\E[J:\
:ce=\E[K:cl=\E[H\E[2J:cm=\E[%i%d;%dH:cr=^M:\
:cs=\E[%i%d;%dr:ct=\E[3g:dc=\E[P:dl=\E[M:do=\E[B:\
:ec=\E[%dX:ei=\E[4l:ho=\E[H:i1=\E[?47l\E>\E[?1l:ic=\E[@:\
:im=\E[4h:is=\E[r\E[m\E[2J\E[H\E[?7h\E[?1;3;4;6l\E[4l:\
:k1=\E[11~:k2=\E[12~:k3=\E[13~:k4=\E[14~:k5=\E[15~:\
:k6=\E[17~:k7=\E[18~:k8=\E[19~:k9=\E[20~:kD=\E[3~:\
:kI=\E[2~:kN=\E[6~:kP=\E[5~:kb=^H:kd=\E[B:ke=:kh=\E[7~:\
:kl=\E[D:kr=\E[C:ks=:ku=\E[A:le=^H:mb=\E[5m:md=\E[1m:\
:me=\E[m\017:mr=\E[7m:nd=\E[C:rc=\E8:\
:sc=\E7:se=\E[27m:sf=^J:so=\E[7m:sr=\EM:st=\EH:ta=^I:\
:te=\E[2J\E[?47l\E8:ti=\E7\E[?47h:ue=\E[24m:up=\E[A:\
:us=\E[4m:vb=\E[?5h\E[?5l:ve=\E[?25h:vi=\E[?25l:\
:ac=aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~:
# DOS terminal emulator such as Telix or TeleMate.
# This probably also works for the SCO console, though it's incomplete.
an|ansi|ansi-bbs|ANSI terminals (emulators):\
:co#80:li#24:am:\
:is=:rs=\Ec:kb=^H:\
:as=\E[m:ae=:eA=:\
:ac=0\333+\257,\256.\031-\030a\261f\370g\361j\331k\277l\332m\300n\305q\304t\264u\303v\301w\302x\263~\025:\
:kD=\177:kH=\E[Y:kN=\E[U:kP=\E[V:kh=\E[H:\
:k1=\EOP:k2=\EOQ:k3=\EOR:k4=\EOS:k5=\EOT:\
:k6=\EOU:k7=\EOV:k8=\EOW:k9=\EOX:k0=\EOY:\
:tc=vt-generic:
`;
} else {
enum UseVtSequences = false;
}
/// A modifier for [Color]
enum Bright = 0x08;
/// Defines the list of standard colors understood by Terminal.
/// See also: [Bright]
enum Color : ushort {
black = 0, /// .
red = RED_BIT, /// .
green = GREEN_BIT, /// .
yellow = red | green, /// .
blue = BLUE_BIT, /// .
magenta = red | blue, /// .
cyan = blue | green, /// .
white = red | green | blue, /// .
DEFAULT = 256,
}
/// When capturing input, what events are you interested in?
///
/// Note: these flags can be OR'd together to select more than one option at a time.
///
/// Ctrl+C and other keyboard input is always captured, though it may be line buffered if you don't use raw.
/// The rationale for that is to ensure the Terminal destructor has a chance to run, since the terminal is a shared resource and should be put back before the program terminates.
enum ConsoleInputFlags {
raw = 0, /// raw input returns keystrokes immediately, without line buffering
echo = 1, /// do you want to automatically echo input back to the user?
mouse = 2, /// capture mouse events
paste = 4, /// capture paste events (note: without this, paste can come through as keystrokes)
size = 8, /// window resize events
releasedKeys = 64, /// key release events. Not reliable on Posix.
allInputEvents = 8|4|2, /// subscribe to all input events. Note: in previous versions, this also returned release events. It no longer does, use allInputEventsWithRelease if you want them.
allInputEventsWithRelease = allInputEvents|releasedKeys, /// subscribe to all input events, including (unreliable on Posix) key release events.
noEolWrap = 128,
}
/// Defines how terminal output should be handled.
enum ConsoleOutputType {
linear = 0, /// do you want output to work one line at a time?
cellular = 1, /// or do you want access to the terminal screen as a grid of characters?
//truncatedCellular = 3, /// cellular, but instead of wrapping output to the next line automatically, it will truncate at the edges
minimalProcessing = 255, /// do the least possible work, skips most construction and desturction tasks. Only use if you know what you're doing here
}
alias ConsoleOutputMode = ConsoleOutputType;
/// Some methods will try not to send unnecessary commands to the screen. You can override their judgement using a ForceOption parameter, if present
enum ForceOption {
automatic = 0, /// automatically decide what to do (best, unless you know for sure it isn't right)
neverSend = -1, /// never send the data. This will only update Terminal's internal state. Use with caution.
alwaysSend = 1, /// always send the data, even if it doesn't seem necessary
}
///
enum TerminalCursor {
DEFAULT = 0, ///
insert = 1, ///
block = 2 ///
}
// we could do it with termcap too, getenv("TERMCAP") then split on : and replace \E with \033 and get the pieces
/// Encapsulates the I/O capabilities of a terminal.
///
/// Warning: do not write out escape sequences to the terminal. This won't work
/// on Windows and will confuse Terminal's internal state on Posix.
struct Terminal {
///
@disable this();
@disable this(this);
private ConsoleOutputType type;
version(TerminalDirectToEmulator) {
private bool windowSizeChanged = false;
private bool interrupted = false; /// you might periodically check this in a long operation and abort if it is set. Remember it is volatile. It is also sent through the input event loop via RealTimeConsoleInput
private bool hangedUp = false; /// similar to interrupted.
}
private TerminalCursor currentCursor_;
version(Windows) private CONSOLE_CURSOR_INFO originalCursorInfo;
/++
Changes the current cursor.
+/
void cursor(TerminalCursor what, ForceOption force = ForceOption.automatic) {
if(force == ForceOption.neverSend) {
currentCursor_ = what;
return;
} else {
if(what != currentCursor_ || force == ForceOption.alwaysSend) {
currentCursor_ = what;
version(Win32Console) {
final switch(what) {
case TerminalCursor.DEFAULT:
SetConsoleCursorInfo(hConsole, &originalCursorInfo);
break;
case TerminalCursor.insert:
case TerminalCursor.block:
CONSOLE_CURSOR_INFO info;
GetConsoleCursorInfo(hConsole, &info);
info.dwSize = what == TerminalCursor.insert ? 1 : 100;
SetConsoleCursorInfo(hConsole, &info);
break;
}
} else {
final switch(what) {
case TerminalCursor.DEFAULT:
if(terminalInFamily("linux"))
writeStringRaw("\033[?0c");
else
writeStringRaw("\033[0 q");
break;
case TerminalCursor.insert:
if(terminalInFamily("linux"))
writeStringRaw("\033[?2c");
else if(terminalInFamily("xterm"))
writeStringRaw("\033[6 q");
else
writeStringRaw("\033[4 q");
break;
case TerminalCursor.block:
if(terminalInFamily("linux"))
writeStringRaw("\033[?6c");
else
writeStringRaw("\033[2 q");
break;
}
}
}
}
}
/++
Terminal is only valid to use on an actual console device or terminal
handle. You should not attempt to construct a Terminal instance if this
returns false. Real time input is similarly impossible if `!stdinIsTerminal`.
+/
static bool stdoutIsTerminal() {
version(TerminalDirectToEmulator) {
version(Windows) {
// if it is null, it was a gui subsystem exe. But otherwise, it
// might be explicitly redirected and we should respect that for
// compatibility with normal console expectations (even though like
// we COULD pop up a gui and do both, really that isn't the normal
// use of this library so don't wanna go too nuts)
auto hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
return hConsole is null || GetFileType(hConsole) == FILE_TYPE_CHAR;
} else version(Posix) {
// same as normal here since thee is no gui subsystem really
import core.sys.posix.unistd;
return cast(bool) isatty(1);
} else static assert(0);
} else version(Posix) {
import core.sys.posix.unistd;
return cast(bool) isatty(1);
} else version(Win32Console) {
auto hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
return GetFileType(hConsole) == FILE_TYPE_CHAR;
/+
auto hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO originalSbi;
if(GetConsoleScreenBufferInfo(hConsole, &originalSbi) == 0)
return false;
else
return true;
+/
} else static assert(0);
}
///
static bool stdinIsTerminal() {
version(TerminalDirectToEmulator) {
version(Windows) {
auto hConsole = GetStdHandle(STD_INPUT_HANDLE);
return hConsole is null || GetFileType(hConsole) == FILE_TYPE_CHAR;
} else version(Posix) {
// same as normal here since thee is no gui subsystem really
import core.sys.posix.unistd;
return cast(bool) isatty(0);
} else static assert(0);
} else version(Posix) {
import core.sys.posix.unistd;
return cast(bool) isatty(0);
} else version(Win32Console) {
auto hConsole = GetStdHandle(STD_INPUT_HANDLE);
return GetFileType(hConsole) == FILE_TYPE_CHAR;
} else static assert(0);
}
version(Posix) {
private int fdOut;
private int fdIn;
private int[] delegate() getSizeOverride;
void delegate(in void[]) _writeDelegate; // used to override the unix write() system call, set it magically
}
bool terminalInFamily(string[] terms...) {
import std.process;
import std.string;
version(TerminalDirectToEmulator)
auto term = "xterm";
else
auto term = environment.get("TERM");
foreach(t; terms)
if(indexOf(term, t) != -1)
return true;
return false;
}
version(Posix) {
// This is a filthy hack because Terminal.app and OS X are garbage who don't
// work the way they're advertised. I just have to best-guess hack and hope it
// doesn't break anything else. (If you know a better way, let me know!)
bool isMacTerminal() {
// it gives 1,2 in getTerminalCapabilities...
// FIXME
import std.process;
import std.string;
auto term = environment.get("TERM");
return term == "xterm-256color";
}
} else
bool isMacTerminal() { return false; }
static string[string] termcapDatabase;
static void readTermcapFile(bool useBuiltinTermcap = false) {
import std.file;
import std.stdio;
import std.string;
//if(!exists("/etc/termcap"))
useBuiltinTermcap = true;
string current;
void commitCurrentEntry() {
if(current is null)
return;
string names = current;
auto idx = indexOf(names, ":");
if(idx != -1)
names = names[0 .. idx];
foreach(name; split(names, "|"))
termcapDatabase[name] = current;
current = null;
}
void handleTermcapLine(in char[] line) {
if(line.length == 0) { // blank
commitCurrentEntry();
return; // continue
}
if(line[0] == '#') // comment
return; // continue
size_t termination = line.length;
if(line[$-1] == '\\')
termination--; // cut off the \\
current ~= strip(line[0 .. termination]);
// termcap entries must be on one logical line, so if it isn't continued, we know we're done
if(line[$-1] != '\\')
commitCurrentEntry();
}
if(useBuiltinTermcap) {
version(VtEscapeCodes)
foreach(line; splitLines(builtinTermcap)) {
handleTermcapLine(line);
}
} else {
foreach(line; File("/etc/termcap").byLine()) {
handleTermcapLine(line);
}
}
}
static string getTermcapDatabase(string terminal) {
import std.string;
if(termcapDatabase is null)
readTermcapFile();
auto data = terminal in termcapDatabase;
if(data is null)
return null;
auto tc = *data;
auto more = indexOf(tc, ":tc=");
if(more != -1) {
auto tcKey = tc[more + ":tc=".length .. $];
auto end = indexOf(tcKey, ":");
if(end != -1)
tcKey = tcKey[0 .. end];
tc = getTermcapDatabase(tcKey) ~ tc;
}
return tc;
}
string[string] termcap;
void readTermcap(string t = null) {
version(TerminalDirectToEmulator)
if(usingDirectEmulator)
t = "xterm";
import std.process;
import std.string;
import std.array;
string termcapData = environment.get("TERMCAP");
if(termcapData.length == 0) {
if(t is null) {
t = environment.get("TERM");
}
// loosen the check so any xterm variety gets
// the same termcap. odds are this is right
// almost always
if(t.indexOf("xterm") != -1)
t = "xterm";
if(t.indexOf("putty") != -1)
t = "xterm";
if(t.indexOf("tmux") != -1)
t = "tmux";
if(t.indexOf("screen") != -1)
t = "screen";
termcapData = getTermcapDatabase(t);
}
auto e = replace(termcapData, "\\\n", "\n");
termcap = null;
foreach(part; split(e, ":")) {
// FIXME: handle numeric things too
auto things = split(part, "=");
if(things.length)
termcap[things[0]] =
things.length > 1 ? things[1] : null;
}
}
string findSequenceInTermcap(in char[] sequenceIn) {
char[10] sequenceBuffer;
char[] sequence;
if(sequenceIn.length > 0 && sequenceIn[0] == '\033') {
if(!(sequenceIn.length < sequenceBuffer.length - 1))
return null;
sequenceBuffer[1 .. sequenceIn.length + 1] = sequenceIn[];
sequenceBuffer[0] = '\\';
sequenceBuffer[1] = 'E';
sequence = sequenceBuffer[0 .. sequenceIn.length + 1];
} else {
sequence = sequenceBuffer[1 .. sequenceIn.length + 1];
}
import std.array;
foreach(k, v; termcap)
if(v == sequence)
return k;
return null;
}
string getTermcap(string key) {
auto k = key in termcap;
if(k !is null) return *k;
return null;
}
// Looks up a termcap item and tries to execute it. Returns false on failure
bool doTermcap(T...)(string key, T t) {
import std.conv;
auto fs = getTermcap(key);
if(fs is null)
return false;
int swapNextTwo = 0;
R getArg(R)(int idx) {
if(swapNextTwo == 2) {
idx ++;
swapNextTwo--;
} else if(swapNextTwo == 1) {
idx --;
swapNextTwo--;
}
foreach(i, arg; t) {
if(i == idx)
return to!R(arg);
}
assert(0, to!string(idx) ~ " is out of bounds working " ~ fs);
}
char[256] buffer;
int bufferPos = 0;
void addChar(char c) {
import std.exception;
enforce(bufferPos < buffer.length);
buffer[bufferPos++] = c;
}
void addString(in char[] c) {
import std.exception;
enforce(bufferPos + c.length < buffer.length);
buffer[bufferPos .. bufferPos + c.length] = c[];
bufferPos += c.length;
}
void addInt(int c, int minSize) {
import std.string;
auto str = format("%0"~(minSize ? to!string(minSize) : "")~"d", c);
addString(str);
}
bool inPercent;
int argPosition = 0;
int incrementParams = 0;
bool skipNext;
bool nextIsChar;
bool inBackslash;
foreach(char c; fs) {
if(inBackslash) {
if(c == 'E')
addChar('\033');
else
addChar(c);
inBackslash = false;
} else if(nextIsChar) {
if(skipNext)
skipNext = false;
else
addChar(cast(char) (c + getArg!int(argPosition) + (incrementParams ? 1 : 0)));
if(incrementParams) incrementParams--;
argPosition++;
inPercent = false;
} else if(inPercent) {
switch(c) {
case '%':
addChar('%');
inPercent = false;
break;
case '2':
case '3':
case 'd':
if(skipNext)
skipNext = false;
else
addInt(getArg!int(argPosition) + (incrementParams ? 1 : 0),
c == 'd' ? 0 : (c - '0')
);
if(incrementParams) incrementParams--;
argPosition++;
inPercent = false;
break;
case '.':
if(skipNext)
skipNext = false;
else
addChar(cast(char) (getArg!int(argPosition) + (incrementParams ? 1 : 0)));
if(incrementParams) incrementParams--;
argPosition++;
break;
case '+':
nextIsChar = true;
inPercent = false;
break;
case 'i':
incrementParams = 2;
inPercent = false;
break;
case 's':
skipNext = true;
inPercent = false;
break;
case 'b':
argPosition--;
inPercent = false;
break;
case 'r':
swapNextTwo = 2;
inPercent = false;
break;
// FIXME: there's more
// http://www.gnu.org/software/termutils/manual/termcap-1.3/html_mono/termcap.html
default:
assert(0, "not supported " ~ c);
}
} else {
if(c == '%')
inPercent = true;
else if(c == '\\')
inBackslash = true;
else
addChar(c);
}
}
writeStringRaw(buffer[0 .. bufferPos]);
return true;
}
uint tcaps;
bool inlineImagesSupported() {
return (tcaps & TerminalCapabilities.arsdImage) ? true : false;
}
bool clipboardSupported() {
version(Win32Console) return true;
else return (tcaps & TerminalCapabilities.arsdImage) ? true : false;
}
// only supported on my custom terminal emulator. guarded behind if(inlineImagesSupported)
// though that isn't even 100% accurate but meh
void changeWindowIcon()(string filename) {
if(inlineImagesSupported()) {
import arsd.png;
auto image = readPng(filename);
auto ii = cast(IndexedImage) image;
assert(ii !is null);
// copy/pasted from my terminalemulator.d
string encodeSmallTextImage(IndexedImage ii) {
char encodeNumeric(int c) {
if(c < 10)
return cast(char)(c + '0');
if(c < 10 + 26)
return cast(char)(c - 10 + 'a');
assert(0);
}
string s;
s ~= encodeNumeric(ii.width);
s ~= encodeNumeric(ii.height);
foreach(entry; ii.palette)
s ~= entry.toRgbaHexString();
s ~= "Z";
ubyte rleByte;
int rleCount;
void rleCommit() {
if(rleByte >= 26)
assert(0); // too many colors for us to handle
if(rleCount == 0)
goto finish;
if(rleCount == 1) {
s ~= rleByte + 'a';
goto finish;
}
import std.conv;
s ~= to!string(rleCount);
s ~= rleByte + 'a';
finish:
rleByte = 0;
rleCount = 0;
}
foreach(b; ii.data) {
if(b == rleByte)
rleCount++;
else {
rleCommit();
rleByte = b;
rleCount = 1;
}
}
rleCommit();
return s;
}
this.writeStringRaw("\033]5000;"~encodeSmallTextImage(ii)~"\007");
}
}
// dependent on tcaps...
void displayInlineImage()(ubyte[] imageData) {
if(inlineImagesSupported) {
import std.base64;
// I might change this protocol later!
enum extensionMagicIdentifier = "ARSD Terminal Emulator binary extension data follows:";
this.writeStringRaw("\000");
this.writeStringRaw(extensionMagicIdentifier);
this.writeStringRaw(Base64.encode(imageData));
this.writeStringRaw("\000");
}
}
void demandUserAttention() {
if(UseVtSequences) {
if(!terminalInFamily("linux"))
writeStringRaw("\033]5001;1\007");
}
}
void requestCopyToClipboard(string text) {
if(clipboardSupported) {
import std.base64;
writeStringRaw("\033]52;c;"~Base64.encode(cast(ubyte[])text)~"\007");
}
}
void requestCopyToPrimary(string text) {
if(clipboardSupported) {
import std.base64;
writeStringRaw("\033]52;p;"~Base64.encode(cast(ubyte[])text)~"\007");
}
}
bool hasDefaultDarkBackground() {
version(Win32Console) {
return !(defaultBackgroundColor & 0xf);
} else {
version(TerminalDirectToEmulator)
if(usingDirectEmulator)
return integratedTerminalEmulatorConfiguration.defaultBackground.g < 100;
// FIXME: there is probably a better way to do this
// but like idk how reliable it is.
if(terminalInFamily("linux"))
return true;
else
return false;
}
}
version(TerminalDirectToEmulator) {
TerminalEmulatorWidget tew;
private __gshared Window mainWindow;
import core.thread;
version(Posix)
ThreadID threadId;
else version(Windows)
HANDLE threadId;
private __gshared Thread guiThread;
private static class NewTerminalEvent {
Terminal* t;
this(Terminal* t) {
this.t = t;
}
}
bool usingDirectEmulator;
}
version(TerminalDirectToEmulator)
/++
+/
this(ConsoleOutputType type) {
this.type = type;
if(type == ConsoleOutputType.minimalProcessing) {
readTermcap("xterm");
_suppressDestruction = true;
return;
}
import arsd.simpledisplay;
static if(UsingSimpledisplayX11) {
try {
if(arsd.simpledisplay.librariesSuccessfullyLoaded) {
XDisplayConnection.get();
this.usingDirectEmulator = true;
} else if(!integratedTerminalEmulatorConfiguration.fallbackToDegradedTerminal) {
throw new Exception("Unable to load X libraries to create custom terminal.");
}
} catch(Exception e) {
if(!integratedTerminalEmulatorConfiguration.fallbackToDegradedTerminal)
throw e;
}
} else {
this.usingDirectEmulator = true;
}
if(!usingDirectEmulator) {
version(Posix) {
posixInitialize(type, 0, 1, null);
return;
} else {
throw new Exception("Total wtf - are you on a windows system without a gui?!?");
}
assert(0);
}
tcaps = uint.max; // all capabilities
import core.thread;
version(Posix)
threadId = Thread.getThis.id;
else version(Windows)
threadId = GetCurrentThread();
if(guiThread is null) {
guiThread = new Thread( {
auto window = new TerminalEmulatorWindow(&this, null);
mainWindow = window;
mainWindow.win.addEventListener((NewTerminalEvent t) {
auto nw = new TerminalEmulatorWindow(t.t, null);
t.t.tew = nw.tew;
t.t = null;
nw.show();
});
tew = window.tew;
//try
window.loop();
/*
catch(Throwable t) {
import std.stdio;
stdout.writeln(t);
stdout.flush();
}
*/
});
guiThread.start();
guiThread.priority = Thread.PRIORITY_MAX; // gui thread needs responsiveness
} else {
// FIXME: 64 bit builds on linux segfault with multiple terminals
// so that isn't really supported as of yet.
while(cast(shared) mainWindow is null) {
import core.thread;
Thread.sleep(5.msecs);
}
mainWindow.win.postEvent(new NewTerminalEvent(&this));
}
// need to wait until it is properly initialized
while(cast(shared) tew is null) {
import core.thread;
Thread.sleep(5.msecs);
}
initializeVt();
}
else
version(Posix)
/**
* Constructs an instance of Terminal representing the capabilities of
* the current terminal.
*
* While it is possible to override the stdin+stdout file descriptors, remember
* that is not portable across platforms and be sure you know what you're doing.
*
* ditto on getSizeOverride. That's there so you can do something instead of ioctl.
*/
this(ConsoleOutputType type, int fdIn = 0, int fdOut = 1, int[] delegate() getSizeOverride = null) {
posixInitialize(type, fdIn, fdOut, getSizeOverride);
}
version(Posix)
private void posixInitialize(ConsoleOutputType type, int fdIn = 0, int fdOut = 1, int[] delegate() getSizeOverride = null) {
this.fdIn = fdIn;
this.fdOut = fdOut;
this.getSizeOverride = getSizeOverride;
this.type = type;
if(type == ConsoleOutputType.minimalProcessing) {
readTermcap();
_suppressDestruction = true;
return;
}
tcaps = getTerminalCapabilities(fdIn, fdOut);
//writeln(tcaps);
initializeVt();
}
void initializeVt() {
readTermcap();
if(type == ConsoleOutputType.cellular) {
doTermcap("ti");
clear();
moveTo(0, 0, ForceOption.alwaysSend); // we need to know where the cursor is for some features to work, and moving it is easier than querying it
}
if(terminalInFamily("xterm", "rxvt", "screen", "tmux")) {
writeStringRaw("\033[22;0t"); // save window title on a stack (support seems spotty, but it doesn't hurt to have it)
}
}
// EXPERIMENTAL do not use yet
Terminal alternateScreen() {
assert(this.type != ConsoleOutputType.cellular);
this.flush();
return Terminal(ConsoleOutputType.cellular);
}
version(Windows) {
HANDLE hConsole;
CONSOLE_SCREEN_BUFFER_INFO originalSbi;
}
version(Win32Console)
/// ditto
this(ConsoleOutputType type) {
if(UseVtSequences) {
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
initializeVt();
} else {
if(type == ConsoleOutputType.cellular) {
hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, null, CONSOLE_TEXTMODE_BUFFER, null);
if(hConsole == INVALID_HANDLE_VALUE) {
import std.conv;
throw new Exception(to!string(GetLastError()));
}
SetConsoleActiveScreenBuffer(hConsole);
/*
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686125%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683193%28v=vs.85%29.aspx
*/
COORD size;
/*
CONSOLE_SCREEN_BUFFER_INFO sbi;
GetConsoleScreenBufferInfo(hConsole, &sbi);
size.X = cast(short) GetSystemMetrics(SM_CXMIN);
size.Y = cast(short) GetSystemMetrics(SM_CYMIN);
*/
// FIXME: this sucks, maybe i should just revert it. but there shouldn't be scrollbars in cellular mode
//size.X = 80;
//size.Y = 24;
//SetConsoleScreenBufferSize(hConsole, size);
GetConsoleCursorInfo(hConsole, &originalCursorInfo);
clear();
} else {
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
}
if(GetConsoleScreenBufferInfo(hConsole, &originalSbi) == 0)
throw new Exception("not a user-interactive terminal");
defaultForegroundColor = cast(Color) (originalSbi.wAttributes & 0x0f);
defaultBackgroundColor = cast(Color) ((originalSbi.wAttributes >> 4) & 0x0f);
// this is unnecessary since I use the W versions of other functions
// and can cause weird font bugs, so I'm commenting unless some other
// need comes up.
/*
oldCp = GetConsoleOutputCP();
SetConsoleOutputCP(65001); // UTF-8
oldCpIn = GetConsoleCP();
SetConsoleCP(65001); // UTF-8
*/
}
}
version(Win32Console) {
private Color defaultBackgroundColor = Color.black;
private Color defaultForegroundColor = Color.white;
UINT oldCp;
UINT oldCpIn;
}
// only use this if you are sure you know what you want, since the terminal is a shared resource you generally really want to reset it to normal when you leave...
bool _suppressDestruction;
~this() {
if(_suppressDestruction) {
flush();
return;
}
if(UseVtSequences) {
if(type == ConsoleOutputType.cellular) {
doTermcap("te");
}
version(TerminalDirectToEmulator) {
if(usingDirectEmulator) {
writeln("\n\n<exited>");
setTitle(tew.terminalEmulator.currentTitle ~ " <exited>");
tew.term = null;
if(integratedTerminalEmulatorConfiguration.closeOnExit)
tew.parentWindow.close();
} else {
if(terminalInFamily("xterm", "rxvt", "screen", "tmux")) {
writeStringRaw("\033[23;0t"); // restore window title from the stack
}
}
} else
if(terminalInFamily("xterm", "rxvt", "screen", "tmux")) {
writeStringRaw("\033[23;0t"); // restore window title from the stack
}
cursor = TerminalCursor.DEFAULT;
showCursor();
reset();
flush();
if(lineGetter !is null)
lineGetter.dispose();
} else version(Win32Console) {
flush(); // make sure user data is all flushed before resetting
reset();
showCursor();
if(lineGetter !is null)
lineGetter.dispose();
SetConsoleOutputCP(oldCp);
SetConsoleCP(oldCpIn);
auto stdo = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleActiveScreenBuffer(stdo);
if(hConsole !is stdo)
CloseHandle(hConsole);
}
}
// lazily initialized and preserved between calls to getline for a bit of efficiency (only a bit)
// and some history storage.
LineGetter lineGetter;
int _currentForeground = Color.DEFAULT;
int _currentBackground = Color.DEFAULT;
RGB _currentForegroundRGB;
RGB _currentBackgroundRGB;
bool reverseVideo = false;
/++
Attempts to set color according to a 24 bit value (r, g, b, each >= 0 and < 256).
This is not supported on all terminals. It will attempt to fall back to a 256-color
or 8-color palette in those cases automatically.
Returns: true if it believes it was successful (note that it cannot be completely sure),
false if it had to use a fallback.
+/
bool setTrueColor(RGB foreground, RGB background, ForceOption force = ForceOption.automatic) {
if(force == ForceOption.neverSend) {
_currentForeground = -1;
_currentBackground = -1;
_currentForegroundRGB = foreground;
_currentBackgroundRGB = background;
return true;
}
if(force == ForceOption.automatic && _currentForeground == -1 && _currentBackground == -1 && (_currentForegroundRGB == foreground && _currentBackgroundRGB == background))
return true;
_currentForeground = -1;
_currentBackground = -1;
_currentForegroundRGB = foreground;
_currentBackgroundRGB = background;
version(Win32Console) {
flush();
ushort setTob = cast(ushort) approximate16Color(background);
ushort setTof = cast(ushort) approximate16Color(foreground);
SetConsoleTextAttribute(
hConsole,
cast(ushort)((setTob << 4) | setTof));
return false;
} else {
// FIXME: if the terminal reliably does support 24 bit color, use it
// instead of the round off. But idk how to detect that yet...
// fallback to 16 color for term that i know don't take it well
import std.process;
import std.string;
version(TerminalDirectToEmulator)
if(usingDirectEmulator)
goto skip_approximation;
if(environment.get("TERM") == "rxvt" || environment.get("TERM") == "linux") {
// not likely supported, use 16 color fallback
auto setTof = approximate16Color(foreground);
auto setTob = approximate16Color(background);
writeStringRaw(format("\033[%dm\033[3%dm\033[4%dm",
(setTof & Bright) ? 1 : 0,
cast(int) (setTof & ~Bright),
cast(int) (setTob & ~Bright)
));
return false;
}
skip_approximation:
// otherwise, assume it is probably supported and give it a try
writeStringRaw(format("\033[38;5;%dm\033[48;5;%dm",
colorToXTermPaletteIndex(foreground),
colorToXTermPaletteIndex(background)
));
/+ // this is the full 24 bit color sequence
writeStringRaw(format("\033[38;2;%d;%d;%dm", foreground.r, foreground.g, foreground.b));
writeStringRaw(format("\033[48;2;%d;%d;%dm", background.r, background.g, background.b));
+/
return true;
}
}
/// Changes the current color. See enum Color for the values.
void color(int foreground, int background, ForceOption force = ForceOption.automatic, bool reverseVideo = false) {
if(force != ForceOption.neverSend) {
version(Win32Console) {
// assuming a dark background on windows, so LowContrast == dark which means the bit is NOT set on hardware
/*
foreground ^= LowContrast;
background ^= LowContrast;
*/
ushort setTof = cast(ushort) foreground;
ushort setTob = cast(ushort) background;
// this isn't necessarily right but meh
if(background == Color.DEFAULT)
setTob = defaultBackgroundColor;
if(foreground == Color.DEFAULT)
setTof = defaultForegroundColor;
if(force == ForceOption.alwaysSend || reverseVideo != this.reverseVideo || foreground != _currentForeground || background != _currentBackground) {
flush(); // if we don't do this now, the buffering can screw up the colors...
if(reverseVideo) {
if(background == Color.DEFAULT)
setTof = defaultBackgroundColor;
else
setTof = cast(ushort) background | (foreground & Bright);
if(background == Color.DEFAULT)
setTob = defaultForegroundColor;
else
setTob = cast(ushort) (foreground & ~Bright);
}
SetConsoleTextAttribute(
hConsole,
cast(ushort)((setTob << 4) | setTof));
}
} else {
import std.process;
// I started using this envvar for my text editor, but now use it elsewhere too
// if we aren't set to dark, assume light
/*
if(getenv("ELVISBG") == "dark") {
// LowContrast on dark bg menas
} else {
foreground ^= LowContrast;
background ^= LowContrast;
}
*/
ushort setTof = cast(ushort) foreground & ~Bright;
ushort setTob = cast(ushort) background & ~Bright;
if(foreground & Color.DEFAULT)
setTof = 9; // ansi sequence for reset
if(background == Color.DEFAULT)
setTob = 9;
import std.string;
if(force == ForceOption.alwaysSend || reverseVideo != this.reverseVideo || foreground != _currentForeground || background != _currentBackground) {
writeStringRaw(format("\033[%dm\033[3%dm\033[4%dm\033[%dm",
(foreground != Color.DEFAULT && (foreground & Bright)) ? 1 : 0,
cast(int) setTof,
cast(int) setTob,
reverseVideo ? 7 : 27
));
}
}
}
_currentForeground = foreground;
_currentBackground = background;
this.reverseVideo = reverseVideo;
}
private bool _underlined = false;
/++
Outputs a hyperlink to my custom terminal (v0.0.7 or later) or to version
`TerminalDirectToEmulator`. The way it works is a bit strange...
If using a terminal that supports it, it outputs the given text with the
given identifier attached (one bit of identifier per grapheme of text!). When
the user clicks on it, it will send a [LinkEvent] with the text and the identifier
for you to respond, if in real-time input mode, or a simple paste event with the
text if not (you will not be able to distinguish this from a user pasting the
same text).
If the user's terminal does not support my feature, it writes plain text instead.
It is important that you make sure your program still works even if the hyperlinks
never work - ideally, make them out of text the user can type manually or copy/paste
into your command line somehow too.
Hyperlinks may not work correctly after your program exits or if you are capturing
mouse input (the user will have to hold shift in that case). It is really designed
for linear mode with direct to emulator mode. If you are using cellular mode with
full input capturing, you should manage the clicks yourself.
Similarly, if it horizontally scrolls off the screen, it can be corrupted since it
packs your text and identifier into free bits in the screen buffer itself. I may be
able to fix that later.
Params:
text = text displayed in the terminal
identifier = an additional number attached to the text and returned to you in a [LinkEvent]
autoStyle = set to `false` to suppress the automatic color and underlining of the text.
Bugs:
there's no keyboard interaction with it at all right now. i might make the terminal
emulator offer the ids or something through a hold ctrl or something interface. idk.
or tap ctrl twice to turn that on.
History:
Added March 18, 2020
+/
void hyperlink(string text, ushort identifier = 0, bool autoStyle = true) {
if((tcaps & TerminalCapabilities.arsdHyperlinks)) {
bool previouslyUnderlined = _underlined;
int fg = _currentForeground, bg = _currentBackground;
if(autoStyle) {
color(Color.blue, Color.white);
underline = true;
}
import std.conv;
writeStringRaw("\033[?" ~ to!string(65536 + identifier) ~ "h");
write(text);
writeStringRaw("\033[?65536l");
if(autoStyle) {
underline = previouslyUnderlined;
color(fg, bg);
}
} else {
write(text); // graceful degrade
}
}
/// Note: the Windows console does not support underlining
void underline(bool set, ForceOption force = ForceOption.automatic) {
if(set == _underlined && force != ForceOption.alwaysSend)
return;
if(UseVtSequences) {
if(set)
writeStringRaw("\033[4m");
else
writeStringRaw("\033[24m");
}
_underlined = set;
}
// FIXME: do I want to do bold and italic?
/// Returns the terminal to normal output colors
void reset() {
version(Win32Console)
SetConsoleTextAttribute(
hConsole,
originalSbi.wAttributes);
else
writeStringRaw("\033[0m");
_underlined = false;
_currentForeground = Color.DEFAULT;
_currentBackground = Color.DEFAULT;
reverseVideo = false;
}
// FIXME: add moveRelative
/// The current x position of the output cursor. 0 == leftmost column
@property int cursorX() {
return _cursorX;
}
/// The current y position of the output cursor. 0 == topmost row
@property int cursorY() {
return _cursorY;
}
private int _cursorX;
private int _cursorY;
/// Moves the output cursor to the given position. (0, 0) is the upper left corner of the screen. The force parameter can be used to force an update, even if Terminal doesn't think it is necessary
void moveTo(int x, int y, ForceOption force = ForceOption.automatic) {
if(force != ForceOption.neverSend && (force == ForceOption.alwaysSend || x != _cursorX || y != _cursorY)) {
executeAutoHideCursor();
if(UseVtSequences) {
doTermcap("cm", y, x);
} else version(Win32Console) {
flush(); // if we don't do this now, the buffering can screw up the position
COORD coord = {cast(short) x, cast(short) y};
SetConsoleCursorPosition(hConsole, coord);
}
}
_cursorX = x;
_cursorY = y;
}
/// shows the cursor
void showCursor() {
if(UseVtSequences)
doTermcap("ve");
else version(Win32Console) {
CONSOLE_CURSOR_INFO info;
GetConsoleCursorInfo(hConsole, &info);
info.bVisible = true;
SetConsoleCursorInfo(hConsole, &info);
}
}
/// hides the cursor
void hideCursor() {
if(UseVtSequences) {
doTermcap("vi");
} else version(Win32Console) {
CONSOLE_CURSOR_INFO info;
GetConsoleCursorInfo(hConsole, &info);
info.bVisible = false;
SetConsoleCursorInfo(hConsole, &info);
}
}
private bool autoHidingCursor;
private bool autoHiddenCursor;
// explicitly not publicly documented
// Sets the cursor to automatically insert a hide command at the front of the output buffer iff it is moved.
// Call autoShowCursor when you are done with the batch update.
void autoHideCursor() {
autoHidingCursor = true;
}
private void executeAutoHideCursor() {
if(autoHidingCursor) {
version(Win32Console)
hideCursor();
else if(UseVtSequences) {
// prepend the hide cursor command so it is the first thing flushed
writeBuffer = "\033[?25l" ~ writeBuffer;
}
autoHiddenCursor = true;
autoHidingCursor = false; // already been done, don't insert the command again
}
}
// explicitly not publicly documented
// Shows the cursor if it was automatically hidden by autoHideCursor and resets the internal auto hide state.
void autoShowCursor() {
if(autoHiddenCursor)
showCursor();
autoHidingCursor = false;
autoHiddenCursor = false;
}
/*
// alas this doesn't work due to a bunch of delegate context pointer and postblit problems
// instead of using: auto input = terminal.captureInput(flags)
// use: auto input = RealTimeConsoleInput(&terminal, flags);
/// Gets real time input, disabling line buffering
RealTimeConsoleInput captureInput(ConsoleInputFlags flags) {
return RealTimeConsoleInput(&this, flags);
}
*/
/// Changes the terminal's title
void setTitle(string t) {
version(Win32Console) {
wchar[256] buffer;
size_t bufferLength;
foreach(wchar ch; t)
if(bufferLength < buffer.length)
buffer[bufferLength++] = ch;
if(bufferLength < buffer.length)
buffer[bufferLength++] = 0;
else
buffer[$-1] = 0;
SetConsoleTitleW(buffer.ptr);
} else {
import std.string;
if(terminalInFamily("xterm", "rxvt", "screen", "tmux"))
writeStringRaw(format("\033]0;%s\007", t));
}
}
/// Flushes your updates to the terminal.
/// It is important to call this when you are finished writing for now if you are using the version=with_eventloop
void flush() {
if(writeBuffer.length == 0)
return;
version(TerminalDirectToEmulator) {
if(usingDirectEmulator) {
tew.sendRawInput(cast(ubyte[]) writeBuffer);
writeBuffer = null;
} else {
interiorFlush();
}
} else {
interiorFlush();
}
}
private void interiorFlush() {
version(Posix) {
if(_writeDelegate !is null) {
_writeDelegate(writeBuffer);
} else {
ssize_t written;
while(writeBuffer.length) {
written = unix.write(this.fdOut, writeBuffer.ptr, writeBuffer.length);
if(written < 0)
throw new Exception("write failed for some reason");
writeBuffer = writeBuffer[written .. $];
}
}
} else version(Win32Console) {
import std.conv;
// FIXME: I'm not sure I'm actually happy with this allocation but
// it probably isn't a big deal. At least it has unicode support now.
wstring writeBufferw = to!wstring(writeBuffer);
while(writeBufferw.length) {
DWORD written;
WriteConsoleW(hConsole, writeBufferw.ptr, cast(DWORD)writeBufferw.length, &written, null);
writeBufferw = writeBufferw[written .. $];
}
writeBuffer = null;
}
}
int[] getSize() {
version(TerminalDirectToEmulator) {
if(usingDirectEmulator)
return [tew.terminalEmulator.width, tew.terminalEmulator.height];
else
return getSizeInternal();
} else {
return getSizeInternal();
}
}
private int[] getSizeInternal() {
version(Windows) {
CONSOLE_SCREEN_BUFFER_INFO info;
GetConsoleScreenBufferInfo( hConsole, &info );
int cols, rows;
cols = (info.srWindow.Right - info.srWindow.Left + 1);
rows = (info.srWindow.Bottom - info.srWindow.Top + 1);
return [cols, rows];
} else {
if(getSizeOverride is null) {
winsize w;
ioctl(0, TIOCGWINSZ, &w);
return [w.ws_col, w.ws_row];
} else return getSizeOverride();
}
}
void updateSize() {
auto size = getSize();
_width = size[0];
_height = size[1];
}
private int _width;
private int _height;
/// The current width of the terminal (the number of columns)
@property int width() {
if(_width == 0 || _height == 0)
updateSize();
return _width;
}
/// The current height of the terminal (the number of rows)
@property int height() {
if(_width == 0 || _height == 0)
updateSize();
return _height;
}
/*
void write(T...)(T t) {
foreach(arg; t) {
writeStringRaw(to!string(arg));
}
}
*/
/// Writes to the terminal at the current cursor position.
void writef(T...)(string f, T t) {
import std.string;
writePrintableString(format(f, t));
}
/// ditto
void writefln(T...)(string f, T t) {
writef(f ~ "\n", t);
}
/// ditto
void write(T...)(T t) {
import std.conv;
string data;
foreach(arg; t) {
data ~= to!string(arg);
}
writePrintableString(data);
}
/// ditto
void writeln(T...)(T t) {
write(t, "\n");
}
/+
/// A combined moveTo and writef that puts the cursor back where it was before when it finishes the write.
/// Only works in cellular mode.
/// Might give better performance than moveTo/writef because if the data to write matches the internal buffer, it skips sending anything (to override the buffer check, you can use moveTo and writePrintableString with ForceOption.alwaysSend)
void writefAt(T...)(int x, int y, string f, T t) {
import std.string;
auto toWrite = format(f, t);
auto oldX = _cursorX;
auto oldY = _cursorY;
writeAtWithoutReturn(x, y, toWrite);
moveTo(oldX, oldY);
}
void writeAtWithoutReturn(int x, int y, in char[] data) {
moveTo(x, y);
writeStringRaw(toWrite, ForceOption.alwaysSend);
}
+/
void writePrintableString(const(char)[] s, ForceOption force = ForceOption.automatic) {
// an escape character is going to mess things up. Actually any non-printable character could, but meh
// assert(s.indexOf("\033") == -1);
if(s.length == 0)
return;
// tracking cursor position
// FIXME: by grapheme?
foreach(dchar ch; s) {
switch(ch) {
case '\n':
_cursorX = 0;
_cursorY++;
break;
case '\r':
_cursorX = 0;
break;
case '\t':
_cursorX ++;
_cursorX += _cursorX % 8; // FIXME: get the actual tabstop, if possible
break;
default:
_cursorX++;
}
if(_wrapAround && _cursorX > width) {
_cursorX = 0;
_cursorY++;
}
if(_cursorY == height)
_cursorY--;
/+
auto index = getIndex(_cursorX, _cursorY);
if(data[index] != ch) {
data[index] = ch;
}
+/
}
version(TerminalDirectToEmulator) {
// this breaks up extremely long output a little as an aid to the
// gui thread; by breaking it up, it helps to avoid monopolizing the
// event loop. Easier to do here than in the thread itself because
// this one doesn't have escape sequences to break up so it avoids work.
while(s.length) {
auto len = s.length;
if(len > 1024 * 32) {
len = 1024 * 32;
// get to the start of a utf-8 sequence. kidna sorta.
while(len && (s[len] & 0x1000_0000))
len--;
}
auto next = s[0 .. len];
s = s[len .. $];
writeStringRaw(next);
}
} else {
writeStringRaw(s);
}
}
/* private */ bool _wrapAround = true;
deprecated alias writePrintableString writeString; /// use write() or writePrintableString instead
private string writeBuffer;
// you really, really shouldn't use this unless you know what you are doing
/*private*/ void writeStringRaw(in char[] s) {
writeBuffer ~= s; // buffer it to do everything at once in flush() calls
if(writeBuffer.length > 1024 * 32)
flush();
}
/// Clears the screen.
void clear() {
if(UseVtSequences) {
doTermcap("cl");
} else version(Win32Console) {
// http://support.microsoft.com/kb/99261
flush();
DWORD c;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD conSize;
GetConsoleScreenBufferInfo(hConsole, &csbi);
conSize = csbi.dwSize.X * csbi.dwSize.Y;
COORD coordScreen;
FillConsoleOutputCharacterA(hConsole, ' ', conSize, coordScreen, &c);
FillConsoleOutputAttribute(hConsole, csbi.wAttributes, conSize, coordScreen, &c);
moveTo(0, 0, ForceOption.alwaysSend);
}
_cursorX = 0;
_cursorY = 0;
}
/// gets a line, including user editing. Convenience method around the LineGetter class and RealTimeConsoleInput facilities - use them if you need more control.
/// You really shouldn't call this if stdin isn't actually a user-interactive terminal! So if you expect people to pipe data to your app, check for that or use something else.
// FIXME: add a method to make it easy to check if stdin is actually a tty and use other methods there.
string getline(string prompt = null) {
if(lineGetter is null)
lineGetter = new LineGetter(&this);
// since the struct might move (it shouldn't, this should be unmovable!) but since
// it technically might, I'm updating the pointer before using it just in case.
lineGetter.terminal = &this;
if(prompt !is null)
lineGetter.prompt = prompt;
auto input = RealTimeConsoleInput(&this, ConsoleInputFlags.raw);
auto line = lineGetter.getline(&input);
// lineGetter leaves us exactly where it was when the user hit enter, giving best
// flexibility to real-time input and cellular programs. The convenience function,
// however, wants to do what is right in most the simple cases, which is to actually
// print the line (echo would be enabled without RealTimeConsoleInput anyway and they
// did hit enter), so we'll do that here too.
writePrintableString("\n");
return line;
}
}
/++
Removes terminal color, bold, etc. sequences from a string,
making it plain text suitable for output to a normal .txt
file.
+/
inout(char)[] removeTerminalGraphicsSequences(inout(char)[] s) {
import std.string;
auto at = s.indexOf("\033[");
if(at == -1)
return s;
inout(char)[] ret;
do {
ret ~= s[0 .. at];
s = s[at + 2 .. $];
while(s.length && !((s[0] >= 'a' && s[0] <= 'z') || s[0] >= 'A' && s[0] <= 'Z')) {
s = s[1 .. $];
}
if(s.length)
s = s[1 .. $]; // skip the terminator
at = s.indexOf("\033[");
} while(at != -1);
ret ~= s;
return ret;
}
unittest {
assert("foo".removeTerminalGraphicsSequences == "foo");
assert("\033[34mfoo".removeTerminalGraphicsSequences == "foo");
assert("\033[34mfoo\033[39m".removeTerminalGraphicsSequences == "foo");
assert("\033[34m\033[45mfoo\033[39mbar\033[49m".removeTerminalGraphicsSequences == "foobar");
}
/+
struct ConsoleBuffer {
int cursorX;
int cursorY;
int width;
int height;
dchar[] data;
void actualize(Terminal* t) {
auto writer = t.getBufferedWriter();
this.copyTo(&(t.onScreen));
}
void copyTo(ConsoleBuffer* buffer) {
buffer.cursorX = this.cursorX;
buffer.cursorY = this.cursorY;
buffer.width = this.width;
buffer.height = this.height;
buffer.data[] = this.data[];
}
}
+/
/**
* Encapsulates the stream of input events received from the terminal input.
*/
struct RealTimeConsoleInput {
@disable this();
@disable this(this);
/++
Requests the system to send paste data as a [PasteEvent] to this stream, if possible.
See_Also:
[Terminal.requestCopyToPrimary]
[Terminal.requestCopyToClipboard]
[Terminal.clipboardSupported]
History:
Added February 17, 2020.
It was in Terminal briefly during an undocumented period, but it had to be moved here to have the context needed to send the real time paste event.
+/
void requestPasteFromClipboard() {
version(Win32Console) {
HWND hwndOwner = null;
if(OpenClipboard(hwndOwner) == 0)
throw new Exception("OpenClipboard");
scope(exit)
CloseClipboard();
if(auto dataHandle = GetClipboardData(CF_UNICODETEXT)) {
if(auto data = cast(wchar*) GlobalLock(dataHandle)) {
scope(exit)
GlobalUnlock(dataHandle);
int len = 0;
auto d = data;
while(*d) {
d++;
len++;
}
string s;
s.reserve(len);
foreach(idx, dchar ch; data[0 .. len]) {
// CR/LF -> LF
if(ch == '\r' && idx + 1 < len && data[idx + 1] == '\n')
continue;
s ~= ch;
}
injectEvent(InputEvent(PasteEvent(s), terminal), InjectionPosition.tail);
}
}
} else
if(terminal.clipboardSupported) {
if(UseVtSequences)
terminal.writeStringRaw("\033]52;c;?\007");
}
}
/// ditto
void requestPasteFromPrimary() {
if(terminal.clipboardSupported) {
if(UseVtSequences)
terminal.writeStringRaw("\033]52;p;?\007");
}
}
version(Posix) {
private int fdOut;
private int fdIn;
private sigaction_t oldSigWinch;
private sigaction_t oldSigIntr;
private sigaction_t oldHupIntr;
private termios old;
ubyte[128] hack;
// apparently termios isn't the size druntime thinks it is (at least on 32 bit, sometimes)....
// tcgetattr smashed other variables in here too that could create random problems
// so this hack is just to give some room for that to happen without destroying the rest of the world
}
version(Windows) {
private DWORD oldInput;
private DWORD oldOutput;
HANDLE inputHandle;
}
private ConsoleInputFlags flags;
private Terminal* terminal;
private void delegate()[] destructor;
/// To capture input, you need to provide a terminal and some flags.
public this(Terminal* terminal, ConsoleInputFlags flags) {
this.flags = flags;
this.terminal = terminal;
version(Windows) {
inputHandle = GetStdHandle(STD_INPUT_HANDLE);
}
version(Win32Console) {
GetConsoleMode(inputHandle, &oldInput);
DWORD mode = 0;
//mode |= ENABLE_PROCESSED_INPUT /* 0x01 */; // this gives Ctrl+C and automatic paste... which we probably want to be similar to linux
//if(flags & ConsoleInputFlags.size)
mode |= ENABLE_WINDOW_INPUT /* 0208 */; // gives size etc
if(flags & ConsoleInputFlags.echo)
mode |= ENABLE_ECHO_INPUT; // 0x4
if(flags & ConsoleInputFlags.mouse)
mode |= ENABLE_MOUSE_INPUT; // 0x10
// if(flags & ConsoleInputFlags.raw) // FIXME: maybe that should be a separate flag for ENABLE_LINE_INPUT
SetConsoleMode(inputHandle, mode);
destructor ~= { SetConsoleMode(inputHandle, oldInput); };
GetConsoleMode(terminal.hConsole, &oldOutput);
mode = 0;
// we want this to match linux too
mode |= ENABLE_PROCESSED_OUTPUT; /* 0x01 */
if(!(flags & ConsoleInputFlags.noEolWrap))
mode |= ENABLE_WRAP_AT_EOL_OUTPUT; /* 0x02 */
SetConsoleMode(terminal.hConsole, mode);
destructor ~= { SetConsoleMode(terminal.hConsole, oldOutput); };
}
version(TerminalDirectToEmulator) {
if(terminal.usingDirectEmulator)
terminal.tew.terminalEmulator.echo = (flags & ConsoleInputFlags.echo) ? true : false;
else version(Posix)
posixInit();
} else version(Posix) {
posixInit();
}
if(UseVtSequences) {
if(flags & ConsoleInputFlags.mouse) {
// basic button press+release notification
// FIXME: try to get maximum capabilities from all terminals
// right now this works well on xterm but rxvt isn't sending movements...
terminal.writeStringRaw("\033[?1000h");
destructor ~= { terminal.writeStringRaw("\033[?1000l"); };
// the MOUSE_HACK env var is for the case where I run screen
// but set TERM=xterm (which I do from putty). The 1003 mouse mode
// doesn't work there, breaking mouse support entirely. So by setting
// MOUSE_HACK=1002 it tells us to use the other mode for a fallback.
import std.process : environment;
if(terminal.terminalInFamily("xterm") && environment.get("MOUSE_HACK") != "1002") {
// this is vt200 mouse with full motion tracking, supported by xterm
terminal.writeStringRaw("\033[?1003h");
destructor ~= { terminal.writeStringRaw("\033[?1003l"); };
} else if(terminal.terminalInFamily("rxvt", "screen", "tmux") || environment.get("MOUSE_HACK") == "1002") {
terminal.writeStringRaw("\033[?1002h"); // this is vt200 mouse with press/release and motion notification iff buttons are pressed
destructor ~= { terminal.writeStringRaw("\033[?1002l"); };
}
}
if(flags & ConsoleInputFlags.paste) {
if(terminal.terminalInFamily("xterm", "rxvt", "screen", "tmux")) {
terminal.writeStringRaw("\033[?2004h"); // bracketed paste mode
destructor ~= { terminal.writeStringRaw("\033[?2004l"); };
}
}
if(terminal.tcaps & TerminalCapabilities.arsdHyperlinks) {
terminal.writeStringRaw("\033[?3004h"); // bracketed link mode
destructor ~= { terminal.writeStringRaw("\033[?3004l"); };
}
// try to ensure the terminal is in UTF-8 mode
if(terminal.terminalInFamily("xterm", "screen", "linux", "tmux") && !terminal.isMacTerminal()) {
terminal.writeStringRaw("\033%G");
}
terminal.flush();
}
version(with_eventloop) {
import arsd.eventloop;
version(Win32Console)
auto listenTo = inputHandle;
else version(Posix)
auto listenTo = this.fdIn;
else static assert(0, "idk about this OS");
version(Posix)
addListener(&signalFired);
if(listenTo != -1) {
addFileEventListeners(listenTo, &eventListener, null, null);
destructor ~= { removeFileEventListeners(listenTo); };
}
addOnIdle(&terminal.flush);
destructor ~= { removeOnIdle(&terminal.flush); };
}
}
version(Posix)
private void posixInit() {
this.fdIn = terminal.fdIn;
this.fdOut = terminal.fdOut;
if(fdIn != -1) {
tcgetattr(fdIn, &old);
auto n = old;
auto f = ICANON;
if(!(flags & ConsoleInputFlags.echo))
f |= ECHO;
// \033Z or \033[c
n.c_lflag &= ~f;
tcsetattr(fdIn, TCSANOW, &n);
}
// some weird bug breaks this, https://github.com/robik/ConsoleD/issues/3
//destructor ~= { tcsetattr(fdIn, TCSANOW, &old); };
if(flags & ConsoleInputFlags.size) {
import core.sys.posix.signal;
sigaction_t n;
n.sa_handler = &sizeSignalHandler;
n.sa_mask = cast(sigset_t) 0;
n.sa_flags = 0;
sigaction(SIGWINCH, &n, &oldSigWinch);
}
{
import core.sys.posix.signal;
sigaction_t n;
n.sa_handler = &interruptSignalHandler;
n.sa_mask = cast(sigset_t) 0;
n.sa_flags = 0;
sigaction(SIGINT, &n, &oldSigIntr);
}
{
import core.sys.posix.signal;
sigaction_t n;
n.sa_handler = &hangupSignalHandler;
n.sa_mask = cast(sigset_t) 0;
n.sa_flags = 0;
sigaction(SIGHUP, &n, &oldHupIntr);
}
}
void fdReadyReader() {
auto queue = readNextEvents();
foreach(event; queue)
userEventHandler(event);
}
void delegate(InputEvent) userEventHandler;
/++
If you are using [arsd.simpledisplay] and want terminal interop too, you can call
this function to add it to the sdpy event loop and get the callback called on new
input.
Note that you will probably need to call `terminal.flush()` when you are doing doing
output, as the sdpy event loop doesn't know to do that (yet). I will probably change
that in a future version, but it doesn't hurt to call it twice anyway, so I recommend
calling flush yourself in any code you write using this.
+/
void integrateWithSimpleDisplayEventLoop()(void delegate(InputEvent) userEventHandler) {
this.userEventHandler = userEventHandler;
import arsd.simpledisplay;
version(Win32Console)
auto listener = new WindowsHandleReader(&fdReadyReader, terminal.hConsole);
else version(linux)
auto listener = new PosixFdReader(&fdReadyReader, fdIn);
else static assert(0, "sdpy event loop integration not implemented on this platform");
}
version(with_eventloop) {
version(Posix)
void signalFired(SignalFired) {
if(interrupted) {
interrupted = false;
send(InputEvent(UserInterruptionEvent(), terminal));
}
if(windowSizeChanged)
send(checkWindowSizeChanged());
if(hangedUp) {
hangedUp = false;
send(InputEvent(HangupEvent(), terminal));
}
}
import arsd.eventloop;
void eventListener(OsFileHandle fd) {
auto queue = readNextEvents();
foreach(event; queue)
send(event);
}
}
bool _suppressDestruction;
~this() {
if(_suppressDestruction)
return;
// the delegate thing doesn't actually work for this... for some reason
version(TerminalDirectToEmulator) {
if(terminal && terminal.usingDirectEmulator)
goto skip_extra;
}
version(Posix) {
if(fdIn != -1)
tcsetattr(fdIn, TCSANOW, &old);
if(flags & ConsoleInputFlags.size) {
// restoration
sigaction(SIGWINCH, &oldSigWinch, null);
}
sigaction(SIGINT, &oldSigIntr, null);
sigaction(SIGHUP, &oldHupIntr, null);
}
skip_extra:
// we're just undoing everything the constructor did, in reverse order, same criteria
foreach_reverse(d; destructor)
d();
}
/**
Returns true if there iff getch() would not block.
WARNING: kbhit might consume input that would be ignored by getch. This
function is really only meant to be used in conjunction with getch. Typically,
you should use a full-fledged event loop if you want all kinds of input. kbhit+getch
are just for simple keyboard driven applications.
*/
bool kbhit() {
auto got = getch(true);
if(got == dchar.init)
return false;
getchBuffer = got;
return true;
}
/// Check for input, waiting no longer than the number of milliseconds
bool timedCheckForInput(int milliseconds) {
if(inputQueue.length || timedCheckForInput_bypassingBuffer(milliseconds))
return true;
version(WithEncapsulatedSignals)
if(terminal.interrupted || terminal.windowSizeChanged || terminal.hangedUp)
return true;
version(WithSignals)
if(interrupted || windowSizeChanged || hangedUp)
return true;
return false;
}
/* private */ bool anyInput_internal(int timeout = 0) {
return timedCheckForInput(timeout);
}
bool timedCheckForInput_bypassingBuffer(int milliseconds) {
version(TerminalDirectToEmulator) {
if(!terminal.usingDirectEmulator)
return timedCheckForInput_bypassingBuffer_impl(milliseconds);
import core.time;
if(terminal.tew.terminalEmulator.pendingForApplication.length)
return true;
if(terminal.tew.terminalEmulator.outgoingSignal.wait(milliseconds.msecs))
// it was notified, but it could be left over from stuff we
// already processed... so gonna check the blocking conditions here too
// (FIXME: this sucks and is surely a race condition of pain)
return terminal.tew.terminalEmulator.pendingForApplication.length || terminal.interrupted || terminal.windowSizeChanged || terminal.hangedUp;
else
return false;
} else
return timedCheckForInput_bypassingBuffer_impl(milliseconds);
}
private bool timedCheckForInput_bypassingBuffer_impl(int milliseconds) {
version(Windows) {
auto response = WaitForSingleObject(inputHandle, milliseconds);
if(response == 0)
return true; // the object is ready
return false;
} else version(Posix) {
if(fdIn == -1)
return false;
timeval tv;
tv.tv_sec = 0;
tv.tv_usec = milliseconds * 1000;
fd_set fs;
FD_ZERO(&fs);
FD_SET(fdIn, &fs);
int tries = 0;
try_again:
auto ret = select(fdIn + 1, &fs, null, null, &tv);
if(ret == -1) {
import core.stdc.errno;
if(errno == EINTR) {
tries++;
if(tries < 3)
goto try_again;
}
return false;
}
if(ret == 0)
return false;
return FD_ISSET(fdIn, &fs);
}
}
private dchar getchBuffer;
/// Get one key press from the terminal, discarding other
/// events in the process. Returns dchar.init upon receiving end-of-file.
///
/// Be aware that this may return non-character key events, like F1, F2, arrow keys, etc., as private use Unicode characters. Check them against KeyboardEvent.Key if you like.
dchar getch(bool nonblocking = false) {
if(getchBuffer != dchar.init) {
auto a = getchBuffer;
getchBuffer = dchar.init;
return a;
}
if(nonblocking && !anyInput_internal())
return dchar.init;
auto event = nextEvent();
while(event.type != InputEvent.Type.KeyboardEvent || event.keyboardEvent.pressed == false) {
if(event.type == InputEvent.Type.UserInterruptionEvent)
throw new UserInterruptionException();
if(event.type == InputEvent.Type.HangupEvent)
throw new HangupException();
if(event.type == InputEvent.Type.EndOfFileEvent)
return dchar.init;
if(nonblocking && !anyInput_internal())
return dchar.init;
event = nextEvent();
}
return event.keyboardEvent.which;
}
//char[128] inputBuffer;
//int inputBufferPosition;
int nextRaw(bool interruptable = false) {
version(TerminalDirectToEmulator) {
if(!terminal.usingDirectEmulator)
return nextRaw_impl(interruptable);
moar:
//if(interruptable && inputQueue.length)
//return -1;
if(terminal.tew.terminalEmulator.pendingForApplication.length == 0)
terminal.tew.terminalEmulator.outgoingSignal.wait();
synchronized(terminal.tew.terminalEmulator) {
if(terminal.tew.terminalEmulator.pendingForApplication.length == 0) {
if(interruptable)
return -1;
else
goto moar;
}
auto a = terminal.tew.terminalEmulator.pendingForApplication[0];
terminal.tew.terminalEmulator.pendingForApplication = terminal.tew.terminalEmulator.pendingForApplication[1 .. $];
return a;
}
} else
return nextRaw_impl(interruptable);
}
private int nextRaw_impl(bool interruptable = false) {
version(Posix) {
if(fdIn == -1)
return 0;
char[1] buf;
try_again:
auto ret = read(fdIn, buf.ptr, buf.length);
if(ret == 0)
return 0; // input closed
if(ret == -1) {
import core.stdc.errno;
if(errno == EINTR)
// interrupted by signal call, quite possibly resize or ctrl+c which we want to check for in the event loop
if(interruptable)
return -1;
else
goto try_again;
else
throw new Exception("read failed");
}
//terminal.writef("RAW READ: %d\n", buf[0]);
if(ret == 1)
return inputPrefilter ? inputPrefilter(buf[0]) : buf[0];
else
assert(0); // read too much, should be impossible
} else version(Windows) {
char[1] buf;
DWORD d;
import std.conv;
if(!ReadFile(inputHandle, buf.ptr, cast(int) buf.length, &d, null))
throw new Exception("ReadFile " ~ to!string(GetLastError()));
return buf[0];
}
}
version(Posix)
int delegate(char) inputPrefilter;
// for VT
dchar nextChar(int starting) {
if(starting <= 127)
return cast(dchar) starting;
char[6] buffer;
int pos = 0;
buffer[pos++] = cast(char) starting;
// see the utf-8 encoding for details
int remaining = 0;
ubyte magic = starting & 0xff;
while(magic & 0b1000_000) {
remaining++;
magic <<= 1;
}
while(remaining && pos < buffer.length) {
buffer[pos++] = cast(char) nextRaw();
remaining--;
}
import std.utf;
size_t throwAway; // it insists on the index but we don't care
return decode(buffer[], throwAway);
}
InputEvent checkWindowSizeChanged() {
auto oldWidth = terminal.width;
auto oldHeight = terminal.height;
terminal.updateSize();
version(WithSignals)
windowSizeChanged = false;
version(WithEncapsulatedSignals)
terminal.windowSizeChanged = false;
return InputEvent(SizeChangedEvent(oldWidth, oldHeight, terminal.width, terminal.height), terminal);
}
// character event
// non-character key event
// paste event
// mouse event
// size event maybe, and if appropriate focus events
/// Returns the next event.
///
/// Experimental: It is also possible to integrate this into
/// a generic event loop, currently under -version=with_eventloop and it will
/// require the module arsd.eventloop (Linux only at this point)
InputEvent nextEvent() {
terminal.flush();
wait_for_more:
version(WithSignals) {
if(interrupted) {
interrupted = false;
return InputEvent(UserInterruptionEvent(), terminal);
}
if(hangedUp) {
hangedUp = false;
return InputEvent(HangupEvent(), terminal);
}
if(windowSizeChanged) {
return checkWindowSizeChanged();
}
}
version(WithEncapsulatedSignals) {
if(terminal.interrupted) {
terminal.interrupted = false;
return InputEvent(UserInterruptionEvent(), terminal);
}
if(terminal.hangedUp) {
terminal.hangedUp = false;
return InputEvent(HangupEvent(), terminal);
}
if(terminal.windowSizeChanged) {
return checkWindowSizeChanged();
}
}
if(inputQueue.length) {
auto e = inputQueue[0];
inputQueue = inputQueue[1 .. $];
return e;
}
auto more = readNextEvents();
if(!more.length)
goto wait_for_more; // i used to do a loop (readNextEvents can read something, but it might be discarded by the input filter) but now it goto's above because readNextEvents might be interrupted by a SIGWINCH aka size event so we want to check that at least
assert(more.length);
auto e = more[0];
inputQueue = more[1 .. $];
return e;
}
InputEvent* peekNextEvent() {
if(inputQueue.length)
return &(inputQueue[0]);
return null;
}
enum InjectionPosition { head, tail }
void injectEvent(InputEvent ev, InjectionPosition where) {
final switch(where) {
case InjectionPosition.head:
inputQueue = ev ~ inputQueue;
break;
case InjectionPosition.tail:
inputQueue ~= ev;
break;
}
}
InputEvent[] inputQueue;
InputEvent[] readNextEvents() {
if(UseVtSequences)
return readNextEventsVt();
else version(Win32Console)
return readNextEventsWin32();
else
assert(0);
}
version(Win32Console)
InputEvent[] readNextEventsWin32() {
terminal.flush(); // make sure all output is sent out before waiting for anything
INPUT_RECORD[32] buffer;
DWORD actuallyRead;
// FIXME: ReadConsoleInputW
auto success = ReadConsoleInputW(inputHandle, buffer.ptr, buffer.length, &actuallyRead);
if(success == 0)
throw new Exception("ReadConsoleInput");
InputEvent[] newEvents;
input_loop: foreach(record; buffer[0 .. actuallyRead]) {
switch(record.EventType) {
case KEY_EVENT:
auto ev = record.KeyEvent;
KeyboardEvent ke;
CharacterEvent e;
NonCharacterKeyEvent ne;
ke.pressed = ev.bKeyDown ? true : false;
// only send released events when specifically requested
// terminal.writefln("got %s %s", ev.UnicodeChar, ev.bKeyDown);
if(ev.UnicodeChar && ev.wVirtualKeyCode == VK_MENU && ev.bKeyDown == 0) {
// this indicates Windows is actually sending us
// an alt+xxx key sequence, may also be a unicode paste.
// either way, it cool.
ke.pressed = true;
} else {
if(!(flags & ConsoleInputFlags.releasedKeys) && !ev.bKeyDown)
break;
}
e.eventType = ke.pressed ? CharacterEvent.Type.Pressed : CharacterEvent.Type.Released;
ne.eventType = ke.pressed ? NonCharacterKeyEvent.Type.Pressed : NonCharacterKeyEvent.Type.Released;
e.modifierState = ev.dwControlKeyState;
ne.modifierState = ev.dwControlKeyState;
ke.modifierState = ev.dwControlKeyState;
if(ev.UnicodeChar) {
// new style event goes first
if(ev.UnicodeChar == 3) {
// handling this internally for linux compat too
newEvents ~= InputEvent(UserInterruptionEvent(), terminal);
} else if(ev.UnicodeChar == '\r') {
// translating \r to \n for same result as linux...
ke.which = cast(dchar) cast(wchar) '\n';
newEvents ~= InputEvent(ke, terminal);
// old style event then follows as the fallback
e.character = cast(dchar) cast(wchar) '\n';
newEvents ~= InputEvent(e, terminal);
} else if(ev.wVirtualKeyCode == 0x1b) {
ke.which = cast(KeyboardEvent.Key) (ev.wVirtualKeyCode + 0xF0000);
newEvents ~= InputEvent(ke, terminal);
ne.key = cast(NonCharacterKeyEvent.Key) ev.wVirtualKeyCode;
newEvents ~= InputEvent(ne, terminal);
} else {
ke.which = cast(dchar) cast(wchar) ev.UnicodeChar;
newEvents ~= InputEvent(ke, terminal);
// old style event then follows as the fallback
e.character = cast(dchar) cast(wchar) ev.UnicodeChar;
newEvents ~= InputEvent(e, terminal);
}
} else {
// old style event
ne.key = cast(NonCharacterKeyEvent.Key) ev.wVirtualKeyCode;
// new style event. See comment on KeyboardEvent.Key
ke.which = cast(KeyboardEvent.Key) (ev.wVirtualKeyCode + 0xF0000);
// FIXME: make this better. the goal is to make sure the key code is a valid enum member
// Windows sends more keys than Unix and we're doing lowest common denominator here
foreach(member; __traits(allMembers, NonCharacterKeyEvent.Key))
if(__traits(getMember, NonCharacterKeyEvent.Key, member) == ne.key) {
newEvents ~= InputEvent(ke, terminal);
newEvents ~= InputEvent(ne, terminal);
break;
}
}
break;
case MOUSE_EVENT:
auto ev = record.MouseEvent;
MouseEvent e;
e.modifierState = ev.dwControlKeyState;
e.x = ev.dwMousePosition.X;
e.y = ev.dwMousePosition.Y;
switch(ev.dwEventFlags) {
case 0:
//press or release
e.eventType = MouseEvent.Type.Pressed;
static DWORD lastButtonState;
auto lastButtonState2 = lastButtonState;
e.buttons = ev.dwButtonState;
lastButtonState = e.buttons;
// this is sent on state change. if fewer buttons are pressed, it must mean released
if(cast(DWORD) e.buttons < lastButtonState2) {
e.eventType = MouseEvent.Type.Released;
// if last was 101 and now it is 100, then button far right was released
// so we flip the bits, ~100 == 011, then and them: 101 & 011 == 001, the
// button that was released
e.buttons = lastButtonState2 & ~e.buttons;
}
break;
case MOUSE_MOVED:
e.eventType = MouseEvent.Type.Moved;
e.buttons = ev.dwButtonState;
break;
case 0x0004/*MOUSE_WHEELED*/:
e.eventType = MouseEvent.Type.Pressed;
if(ev.dwButtonState > 0)
e.buttons = MouseEvent.Button.ScrollDown;
else
e.buttons = MouseEvent.Button.ScrollUp;
break;
default:
continue input_loop;
}
newEvents ~= InputEvent(e, terminal);
break;
case WINDOW_BUFFER_SIZE_EVENT:
auto ev = record.WindowBufferSizeEvent;
auto oldWidth = terminal.width;
auto oldHeight = terminal.height;
terminal._width = ev.dwSize.X;
terminal._height = ev.dwSize.Y;
newEvents ~= InputEvent(SizeChangedEvent(oldWidth, oldHeight, terminal.width, terminal.height), terminal);
break;
// FIXME: can we catch ctrl+c here too?
default:
// ignore
}
}
return newEvents;
}
// for UseVtSequences....
InputEvent[] readNextEventsVt() {
terminal.flush(); // make sure all output is sent out before we try to get input
// we want to starve the read, especially if we're called from an edge-triggered
// epoll (which might happen in version=with_eventloop.. impl detail there subject
// to change).
auto initial = readNextEventsHelper();
// lol this calls select() inside a function prolly called from epoll but meh,
// it is the simplest thing that can possibly work. The alternative would be
// doing non-blocking reads and buffering in the nextRaw function (not a bad idea
// btw, just a bit more of a hassle).
while(timedCheckForInput_bypassingBuffer(0)) {
auto ne = readNextEventsHelper();
initial ~= ne;
foreach(n; ne)
if(n.type == InputEvent.Type.EndOfFileEvent)
return initial; // hit end of file, get out of here lest we infinite loop
// (select still returns info available even after we read end of file)
}
return initial;
}
// The helper reads just one actual event from the pipe...
// for UseVtSequences....
InputEvent[] readNextEventsHelper(int remainingFromLastTime = int.max) {
InputEvent[] charPressAndRelease(dchar character) {
if((flags & ConsoleInputFlags.releasedKeys))
return [
// new style event
InputEvent(KeyboardEvent(true, character, 0), terminal),
InputEvent(KeyboardEvent(false, character, 0), terminal),
// old style event
InputEvent(CharacterEvent(CharacterEvent.Type.Pressed, character, 0), terminal),
InputEvent(CharacterEvent(CharacterEvent.Type.Released, character, 0), terminal),
];
else return [
// new style event
InputEvent(KeyboardEvent(true, character, 0), terminal),
// old style event
InputEvent(CharacterEvent(CharacterEvent.Type.Pressed, character, 0), terminal)
];
}
InputEvent[] keyPressAndRelease(NonCharacterKeyEvent.Key key, uint modifiers = 0) {
if((flags & ConsoleInputFlags.releasedKeys))
return [
// new style event FIXME: when the old events are removed, kill the +0xF0000 from here!
InputEvent(KeyboardEvent(true, cast(dchar)(key) + 0xF0000, modifiers), terminal),
InputEvent(KeyboardEvent(false, cast(dchar)(key) + 0xF0000, modifiers), terminal),
// old style event
InputEvent(NonCharacterKeyEvent(NonCharacterKeyEvent.Type.Pressed, key, modifiers), terminal),
InputEvent(NonCharacterKeyEvent(NonCharacterKeyEvent.Type.Released, key, modifiers), terminal),
];
else return [
// new style event FIXME: when the old events are removed, kill the +0xF0000 from here!
InputEvent(KeyboardEvent(true, cast(dchar)(key) + 0xF0000, modifiers), terminal),
// old style event
InputEvent(NonCharacterKeyEvent(NonCharacterKeyEvent.Type.Pressed, key, modifiers), terminal)
];
}
InputEvent[] keyPressAndRelease2(dchar c, uint modifiers = 0) {
if((flags & ConsoleInputFlags.releasedKeys))
return [
InputEvent(KeyboardEvent(true, c, modifiers), terminal),
InputEvent(KeyboardEvent(false, c, modifiers), terminal),
// old style event
InputEvent(CharacterEvent(CharacterEvent.Type.Pressed, c, modifiers), terminal),
InputEvent(CharacterEvent(CharacterEvent.Type.Released, c, modifiers), terminal),
];
else return [
InputEvent(KeyboardEvent(true, c, modifiers), terminal),
// old style event
InputEvent(CharacterEvent(CharacterEvent.Type.Pressed, c, modifiers), terminal)
];
}
char[30] sequenceBuffer;
// this assumes you just read "\033["
char[] readEscapeSequence(char[] sequence) {
int sequenceLength = 2;
sequence[0] = '\033';
sequence[1] = '[';
while(sequenceLength < sequence.length) {
auto n = nextRaw();
sequence[sequenceLength++] = cast(char) n;
// I think a [ is supposed to termiate a CSI sequence
// but the Linux console sends CSI[A for F1, so I'm
// hacking it to accept that too
if(n >= 0x40 && !(sequenceLength == 3 && n == '['))
break;
}
return sequence[0 .. sequenceLength];
}
InputEvent[] translateTermcapName(string cap) {
switch(cap) {
//case "k0":
//return keyPressAndRelease(NonCharacterKeyEvent.Key.F1);
case "k1":
return keyPressAndRelease(NonCharacterKeyEvent.Key.F1);
case "k2":
return keyPressAndRelease(NonCharacterKeyEvent.Key.F2);
case "k3":
return keyPressAndRelease(NonCharacterKeyEvent.Key.F3);
case "k4":
return keyPressAndRelease(NonCharacterKeyEvent.Key.F4);
case "k5":
return keyPressAndRelease(NonCharacterKeyEvent.Key.F5);
case "k6":
return keyPressAndRelease(NonCharacterKeyEvent.Key.F6);
case "k7":
return keyPressAndRelease(NonCharacterKeyEvent.Key.F7);
case "k8":
return keyPressAndRelease(NonCharacterKeyEvent.Key.F8);
case "k9":
return keyPressAndRelease(NonCharacterKeyEvent.Key.F9);
case "k;":
case "k0":
return keyPressAndRelease(NonCharacterKeyEvent.Key.F10);
case "F1":
return keyPressAndRelease(NonCharacterKeyEvent.Key.F11);
case "F2":
return keyPressAndRelease(NonCharacterKeyEvent.Key.F12);
case "kb":
return charPressAndRelease('\b');
case "kD":
return keyPressAndRelease(NonCharacterKeyEvent.Key.Delete);
case "kd":
case "do":
return keyPressAndRelease(NonCharacterKeyEvent.Key.DownArrow);
case "ku":
case "up":
return keyPressAndRelease(NonCharacterKeyEvent.Key.UpArrow);
case "kl":
return keyPressAndRelease(NonCharacterKeyEvent.Key.LeftArrow);
case "kr":
case "nd":
return keyPressAndRelease(NonCharacterKeyEvent.Key.RightArrow);
case "kN":
case "K5":
return keyPressAndRelease(NonCharacterKeyEvent.Key.PageDown);
case "kP":
case "K2":
return keyPressAndRelease(NonCharacterKeyEvent.Key.PageUp);
case "ho": // this might not be a key but my thing sometimes returns it... weird...
case "kh":
case "K1":
return keyPressAndRelease(NonCharacterKeyEvent.Key.Home);
case "kH":
return keyPressAndRelease(NonCharacterKeyEvent.Key.End);
case "kI":
return keyPressAndRelease(NonCharacterKeyEvent.Key.Insert);
default:
// don't know it, just ignore
//import std.stdio;
//terminal.writeln(cap);
}
return null;
}
InputEvent[] doEscapeSequence(in char[] sequence) {
switch(sequence) {
case "\033[200~":
// bracketed paste begin
// we want to keep reading until
// "\033[201~":
// and build a paste event out of it
string data;
for(;;) {
auto n = nextRaw();
if(n == '\033') {
n = nextRaw();
if(n == '[') {
auto esc = readEscapeSequence(sequenceBuffer);
if(esc == "\033[201~") {
// complete!
break;
} else {
// was something else apparently, but it is pasted, so keep it
data ~= esc;
}
} else {
data ~= '\033';
data ~= cast(char) n;
}
} else {
data ~= cast(char) n;
}
}
return [InputEvent(PasteEvent(data), terminal)];
case "\033[220~":
// bracketed hyperlink begin (arsd extension)
string data;
for(;;) {
auto n = nextRaw();
if(n == '\033') {
n = nextRaw();
if(n == '[') {
auto esc = readEscapeSequence(sequenceBuffer);
if(esc == "\033[221~") {
// complete!
break;
} else {
// was something else apparently, but it is pasted, so keep it
data ~= esc;
}
} else {
data ~= '\033';
data ~= cast(char) n;
}
} else {
data ~= cast(char) n;
}
}
import std.string, std.conv;
auto idx = data.indexOf(";");
auto id = data[0 .. idx].to!ushort;
data = data[idx + 1 .. $];
idx = data.indexOf(";");
auto cmd = data[0 .. idx].to!ushort;
data = data[idx + 1 .. $];
return [InputEvent(LinkEvent(data, id, cmd), terminal)];
case "\033[M":
// mouse event
auto buttonCode = nextRaw() - 32;
// nextChar is commented because i'm not using UTF-8 mouse mode
// cuz i don't think it is as widely supported
auto x = cast(int) (/*nextChar*/(nextRaw())) - 33; /* they encode value + 32, but make upper left 1,1. I want it to be 0,0 */
auto y = cast(int) (/*nextChar*/(nextRaw())) - 33; /* ditto */
bool isRelease = (buttonCode & 0b11) == 3;
int buttonNumber;
if(!isRelease) {
buttonNumber = (buttonCode & 0b11);
if(buttonCode & 64)
buttonNumber += 3; // button 4 and 5 are sent as like button 1 and 2, but code | 64
// so button 1 == button 4 here
// note: buttonNumber == 0 means button 1 at this point
buttonNumber++; // hence this
// apparently this considers middle to be button 2. but i want middle to be button 3.
if(buttonNumber == 2)
buttonNumber = 3;
else if(buttonNumber == 3)
buttonNumber = 2;
}
auto modifiers = buttonCode & (0b0001_1100);
// 4 == shift
// 8 == meta
// 16 == control
MouseEvent m;
if(buttonCode & 32)
m.eventType = MouseEvent.Type.Moved;
else
m.eventType = isRelease ? MouseEvent.Type.Released : MouseEvent.Type.Pressed;
// ugh, if no buttons are pressed, released and moved are indistinguishable...
// so we'll count the buttons down, and if we get a release
static int buttonsDown = 0;
if(!isRelease && buttonNumber <= 3) // exclude wheel "presses"...
buttonsDown++;
if(isRelease && m.eventType != MouseEvent.Type.Moved) {
if(buttonsDown)
buttonsDown--;
else // no buttons down, so this should be a motion instead..
m.eventType = MouseEvent.Type.Moved;
}
if(buttonNumber == 0)
m.buttons = 0; // we don't actually know :(
else
m.buttons = 1 << (buttonNumber - 1); // I prefer flags so that's how we do it
m.x = x;
m.y = y;
m.modifierState = modifiers;
return [InputEvent(m, terminal)];
default:
// screen doesn't actually do the modifiers, but
// it uses the same format so this branch still works fine.
if(terminal.terminalInFamily("xterm", "screen", "tmux")) {
import std.conv, std.string;
auto terminator = sequence[$ - 1];
auto parts = sequence[2 .. $ - 1].split(";");
// parts[0] and terminator tells us the key
// parts[1] tells us the modifierState
uint modifierState;
int modGot;
if(parts.length > 1)
modGot = to!int(parts[1]);
mod_switch: switch(modGot) {
case 2: modifierState |= ModifierState.shift; break;
case 3: modifierState |= ModifierState.alt; break;
case 4: modifierState |= ModifierState.shift | ModifierState.alt; break;
case 5: modifierState |= ModifierState.control; break;
case 6: modifierState |= ModifierState.shift | ModifierState.control; break;
case 7: modifierState |= ModifierState.alt | ModifierState.control; break;
case 8: modifierState |= ModifierState.shift | ModifierState.alt | ModifierState.control; break;
case 9:
..
case 16:
modifierState |= ModifierState.meta;
if(modGot != 9) {
modGot -= 8;
goto mod_switch;
}
break;
// this is an extension in my own terminal emulator
case 20:
..
case 36:
modifierState |= ModifierState.windows;
modGot -= 20;
goto mod_switch;
default:
}
switch(terminator) {
case 'A': return keyPressAndRelease(NonCharacterKeyEvent.Key.UpArrow, modifierState);
case 'B': return keyPressAndRelease(NonCharacterKeyEvent.Key.DownArrow, modifierState);
case 'C': return keyPressAndRelease(NonCharacterKeyEvent.Key.RightArrow, modifierState);
case 'D': return keyPressAndRelease(NonCharacterKeyEvent.Key.LeftArrow, modifierState);
case 'H': return keyPressAndRelease(NonCharacterKeyEvent.Key.Home, modifierState);
case 'F': return keyPressAndRelease(NonCharacterKeyEvent.Key.End, modifierState);
case 'P': return keyPressAndRelease(NonCharacterKeyEvent.Key.F1, modifierState);
case 'Q': return keyPressAndRelease(NonCharacterKeyEvent.Key.F2, modifierState);
case 'R': return keyPressAndRelease(NonCharacterKeyEvent.Key.F3, modifierState);
case 'S': return keyPressAndRelease(NonCharacterKeyEvent.Key.F4, modifierState);
case '~': // others
switch(parts[0]) {
case "1": return keyPressAndRelease(NonCharacterKeyEvent.Key.Home, modifierState);
case "4": return keyPressAndRelease(NonCharacterKeyEvent.Key.End, modifierState);
case "5": return keyPressAndRelease(NonCharacterKeyEvent.Key.PageUp, modifierState);
case "6": return keyPressAndRelease(NonCharacterKeyEvent.Key.PageDown, modifierState);
case "2": return keyPressAndRelease(NonCharacterKeyEvent.Key.Insert, modifierState);
case "3": return keyPressAndRelease(NonCharacterKeyEvent.Key.Delete, modifierState);
case "15": return keyPressAndRelease(NonCharacterKeyEvent.Key.F5, modifierState);
case "17": return keyPressAndRelease(NonCharacterKeyEvent.Key.F6, modifierState);
case "18": return keyPressAndRelease(NonCharacterKeyEvent.Key.F7, modifierState);
case "19": return keyPressAndRelease(NonCharacterKeyEvent.Key.F8, modifierState);
case "20": return keyPressAndRelease(NonCharacterKeyEvent.Key.F9, modifierState);
case "21": return keyPressAndRelease(NonCharacterKeyEvent.Key.F10, modifierState);
case "23": return keyPressAndRelease(NonCharacterKeyEvent.Key.F11, modifierState);
case "24": return keyPressAndRelease(NonCharacterKeyEvent.Key.F12, modifierState);
// starting at 70 i do some magic for like shift+enter etc.
// this only happens on my own terminal emulator.
case "70": return keyPressAndRelease(NonCharacterKeyEvent.Key.ScrollLock, modifierState);
case "78": return keyPressAndRelease2('\b', modifierState);
case "79": return keyPressAndRelease2('\t', modifierState);
case "83": return keyPressAndRelease2('\n', modifierState);
default:
}
break;
default:
}
} else if(terminal.terminalInFamily("rxvt")) {
// look it up in the termcap key database
string cap = terminal.findSequenceInTermcap(sequence);
if(cap !is null) {
//terminal.writeln("found in termcap " ~ cap);
return translateTermcapName(cap);
}
// FIXME: figure these out. rxvt seems to just change the terminator while keeping the rest the same
// though it isn't consistent. ugh.
} else {
// maybe we could do more terminals, but linux doesn't even send it and screen just seems to pass through, so i don't think so; xterm prolly covers most them anyway
// so this space is semi-intentionally left blank
//terminal.writeln("wtf ", sequence[1..$]);
// look it up in the termcap key database
string cap = terminal.findSequenceInTermcap(sequence);
if(cap !is null) {
//terminal.writeln("found in termcap " ~ cap);
return translateTermcapName(cap);
}
}
}
return null;
}
auto c = remainingFromLastTime == int.max ? nextRaw(true) : remainingFromLastTime;
if(c == -1)
return null; // interrupted; give back nothing so the other level can recheck signal flags
if(c == 0)
return [InputEvent(EndOfFileEvent(), terminal)];
if(c == '\033') {
if(timedCheckForInput_bypassingBuffer(50)) {
// escape sequence
c = nextRaw();
if(c == '[') { // CSI, ends on anything >= 'A'
return doEscapeSequence(readEscapeSequence(sequenceBuffer));
} else if(c == 'O') {
// could be xterm function key
auto n = nextRaw();
char[3] thing;
thing[0] = '\033';
thing[1] = 'O';
thing[2] = cast(char) n;
auto cap = terminal.findSequenceInTermcap(thing);
if(cap is null) {
return keyPressAndRelease(NonCharacterKeyEvent.Key.escape) ~
charPressAndRelease('O') ~
charPressAndRelease(thing[2]);
} else {
return translateTermcapName(cap);
}
} else if(c == '\033') {
// could be escape followed by an escape sequence!
return keyPressAndRelease(NonCharacterKeyEvent.Key.escape) ~ readNextEventsHelper(c);
} else {
// I don't know, probably unsupported terminal or just quick user input or something
return keyPressAndRelease(NonCharacterKeyEvent.Key.escape) ~ charPressAndRelease(nextChar(c));
}
} else {
// user hit escape (or super slow escape sequence, but meh)
return keyPressAndRelease(NonCharacterKeyEvent.Key.escape);
}
} else {
// FIXME: what if it is neither? we should check the termcap
auto next = nextChar(c);
if(next == 127) // some terminals send 127 on the backspace. Let's normalize that.
next = '\b';
return charPressAndRelease(next);
}
}
}
/// The new style of keyboard event
struct KeyboardEvent {
bool pressed; ///
dchar which; ///
alias key = which; /// I often use this when porting old to new so i took it
alias character = which; /// I often use this when porting old to new so i took it
uint modifierState; ///
///
bool isCharacter() {
return !(which >= Key.min && which <= Key.max);
}
// these match Windows virtual key codes numerically for simplicity of translation there
// but are plus a unicode private use area offset so i can cram them in the dchar
// http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731%28v=vs.85%29.aspx
/// .
enum Key : dchar {
escape = 0x1b + 0xF0000, /// .
F1 = 0x70 + 0xF0000, /// .
F2 = 0x71 + 0xF0000, /// .
F3 = 0x72 + 0xF0000, /// .
F4 = 0x73 + 0xF0000, /// .
F5 = 0x74 + 0xF0000, /// .
F6 = 0x75 + 0xF0000, /// .
F7 = 0x76 + 0xF0000, /// .
F8 = 0x77 + 0xF0000, /// .
F9 = 0x78 + 0xF0000, /// .
F10 = 0x79 + 0xF0000, /// .
F11 = 0x7A + 0xF0000, /// .
F12 = 0x7B + 0xF0000, /// .
LeftArrow = 0x25 + 0xF0000, /// .
RightArrow = 0x27 + 0xF0000, /// .
UpArrow = 0x26 + 0xF0000, /// .
DownArrow = 0x28 + 0xF0000, /// .
Insert = 0x2d + 0xF0000, /// .
Delete = 0x2e + 0xF0000, /// .
Home = 0x24 + 0xF0000, /// .
End = 0x23 + 0xF0000, /// .
PageUp = 0x21 + 0xF0000, /// .
PageDown = 0x22 + 0xF0000, /// .
ScrollLock = 0x91 + 0xF0000, /// unlikely to work outside my custom terminal emulator
}
}
/// Deprecated: use KeyboardEvent instead in new programs
/// Input event for characters
struct CharacterEvent {
/// .
enum Type {
Released, /// .
Pressed /// .
}
Type eventType; /// .
dchar character; /// .
uint modifierState; /// Don't depend on this to be available for character events
}
/// Deprecated: use KeyboardEvent instead in new programs
struct NonCharacterKeyEvent {
/// .
enum Type {
Released, /// .
Pressed /// .
}
Type eventType; /// .
// these match Windows virtual key codes numerically for simplicity of translation there
//http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731%28v=vs.85%29.aspx
/// .
enum Key : int {
escape = 0x1b, /// .
F1 = 0x70, /// .
F2 = 0x71, /// .
F3 = 0x72, /// .
F4 = 0x73, /// .
F5 = 0x74, /// .
F6 = 0x75, /// .
F7 = 0x76, /// .
F8 = 0x77, /// .
F9 = 0x78, /// .
F10 = 0x79, /// .
F11 = 0x7A, /// .
F12 = 0x7B, /// .
LeftArrow = 0x25, /// .
RightArrow = 0x27, /// .
UpArrow = 0x26, /// .
DownArrow = 0x28, /// .
Insert = 0x2d, /// .
Delete = 0x2e, /// .
Home = 0x24, /// .
End = 0x23, /// .
PageUp = 0x21, /// .
PageDown = 0x22, /// .
ScrollLock = 0x91, /// unlikely to work outside my terminal emulator
}
Key key; /// .
uint modifierState; /// A mask of ModifierState. Always use by checking modifierState & ModifierState.something, the actual value differs across platforms
}
/// .
struct PasteEvent {
string pastedText; /// .
}
/++
Indicates a hyperlink was clicked in my custom terminal emulator
or with version `TerminalDirectToEmulator`.
You can simply ignore this event in a `final switch` if you aren't
using the feature.
History:
Added March 18, 2020
+/
struct LinkEvent {
string text; ///
ushort identifier; ///
ushort command; /// set by the terminal to indicate how it was clicked. values tbd
}
/// .
struct MouseEvent {
// these match simpledisplay.d numerically as well
/// .
enum Type {
Moved = 0, /// .
Pressed = 1, /// .
Released = 2, /// .
Clicked, /// .
}
Type eventType; /// .
// note: these should numerically match simpledisplay.d for maximum beauty in my other code
/// .
enum Button : uint {
None = 0, /// .
Left = 1, /// .
Middle = 4, /// .
Right = 2, /// .
ScrollUp = 8, /// .
ScrollDown = 16 /// .
}
uint buttons; /// A mask of Button
int x; /// 0 == left side
int y; /// 0 == top
uint modifierState; /// shift, ctrl, alt, meta, altgr. Not always available. Always check by using modifierState & ModifierState.something
}
/// When you get this, check terminal.width and terminal.height to see the new size and react accordingly.
struct SizeChangedEvent {
int oldWidth;
int oldHeight;
int newWidth;
int newHeight;
}
/// the user hitting ctrl+c will send this
/// You should drop what you're doing and perhaps exit when this happens.
struct UserInterruptionEvent {}
/// If the user hangs up (for example, closes the terminal emulator without exiting the app), this is sent.
/// If you receive it, you should generally cleanly exit.
struct HangupEvent {}
/// Sent upon receiving end-of-file from stdin.
struct EndOfFileEvent {}
interface CustomEvent {}
version(Win32Console)
enum ModifierState : uint {
shift = 0x10,
control = 0x8 | 0x4, // 8 == left ctrl, 4 == right ctrl
// i'm not sure if the next two are available
alt = 2 | 1, //2 ==left alt, 1 == right alt
// FIXME: I don't think these are actually available
windows = 512,
meta = 4096, // FIXME sanity
// I don't think this is available on Linux....
scrollLock = 0x40,
}
else
enum ModifierState : uint {
shift = 4,
alt = 2,
control = 16,
meta = 8,
windows = 512 // only available if you are using my terminal emulator; it isn't actually offered on standard linux ones
}
version(DDoc)
///
enum ModifierState : uint {
///
shift = 4,
///
alt = 2,
///
control = 16,
}
/++
[RealTimeConsoleInput.nextEvent] returns one of these. Check the type, then use the [InputEvent.get|get] method to get the more detailed information about the event.
++/
struct InputEvent {
/// .
enum Type {
KeyboardEvent, /// Keyboard key pressed (or released, where supported)
CharacterEvent, /// Do not use this in new programs, use KeyboardEvent instead
NonCharacterKeyEvent, /// Do not use this in new programs, use KeyboardEvent instead
PasteEvent, /// The user pasted some text. Not always available, the pasted text might come as a series of character events instead.
LinkEvent, /// User clicked a hyperlink you created. Simply ignore if you are not using that feature.
MouseEvent, /// only sent if you subscribed to mouse events
SizeChangedEvent, /// only sent if you subscribed to size events
UserInterruptionEvent, /// the user hit ctrl+c
EndOfFileEvent, /// stdin has received an end of file
HangupEvent, /// the terminal hanged up - for example, if the user closed a terminal emulator
CustomEvent /// .
}
/// If this event is deprecated, you should filter it out in new programs
bool isDeprecated() {
return type == Type.CharacterEvent || type == Type.NonCharacterKeyEvent;
}
/// .
@property Type type() { return t; }
/// Returns a pointer to the terminal associated with this event.
/// (You can usually just ignore this as there's only one terminal typically.)
///
/// It may be null in the case of program-generated events;
@property Terminal* terminal() { return term; }
/++
Gets the specific event instance. First, check the type (such as in a `switch` statement), then extract the correct one from here. Note that the template argument is a $(B value type of the enum above), not a type argument. So to use it, do $(D event.get!(InputEvent.Type.KeyboardEvent)), for example.
See_Also:
The event types:
[KeyboardEvent], [MouseEvent], [SizeChangedEvent],
[PasteEvent], [UserInterruptionEvent],
[EndOfFileEvent], [HangupEvent], [CustomEvent]
And associated functions:
[RealTimeConsoleInput], [ConsoleInputFlags]
++/
@property auto get(Type T)() {
if(type != T)
throw new Exception("Wrong event type");
static if(T == Type.CharacterEvent)
return characterEvent;
else static if(T == Type.KeyboardEvent)
return keyboardEvent;
else static if(T == Type.NonCharacterKeyEvent)
return nonCharacterKeyEvent;
else static if(T == Type.PasteEvent)
return pasteEvent;
else static if(T == Type.LinkEvent)
return linkEvent;
else static if(T == Type.MouseEvent)
return mouseEvent;
else static if(T == Type.SizeChangedEvent)
return sizeChangedEvent;
else static if(T == Type.UserInterruptionEvent)
return userInterruptionEvent;
else static if(T == Type.EndOfFileEvent)
return endOfFileEvent;
else static if(T == Type.HangupEvent)
return hangupEvent;
else static if(T == Type.CustomEvent)
return customEvent;
else static assert(0, "Type " ~ T.stringof ~ " not added to the get function");
}
/// custom event is public because otherwise there's no point at all
this(CustomEvent c, Terminal* p = null) {
t = Type.CustomEvent;
customEvent = c;
}
private {
this(CharacterEvent c, Terminal* p) {
t = Type.CharacterEvent;
characterEvent = c;
}
this(KeyboardEvent c, Terminal* p) {
t = Type.KeyboardEvent;
keyboardEvent = c;
}
this(NonCharacterKeyEvent c, Terminal* p) {
t = Type.NonCharacterKeyEvent;
nonCharacterKeyEvent = c;
}
this(PasteEvent c, Terminal* p) {
t = Type.PasteEvent;
pasteEvent = c;
}
this(LinkEvent c, Terminal* p) {
t = Type.LinkEvent;
linkEvent = c;
}
this(MouseEvent c, Terminal* p) {
t = Type.MouseEvent;
mouseEvent = c;
}
this(SizeChangedEvent c, Terminal* p) {
t = Type.SizeChangedEvent;
sizeChangedEvent = c;
}
this(UserInterruptionEvent c, Terminal* p) {
t = Type.UserInterruptionEvent;
userInterruptionEvent = c;
}
this(HangupEvent c, Terminal* p) {
t = Type.HangupEvent;
hangupEvent = c;
}
this(EndOfFileEvent c, Terminal* p) {
t = Type.EndOfFileEvent;
endOfFileEvent = c;
}
Type t;
Terminal* term;
union {
KeyboardEvent keyboardEvent;
CharacterEvent characterEvent;
NonCharacterKeyEvent nonCharacterKeyEvent;
PasteEvent pasteEvent;
MouseEvent mouseEvent;
SizeChangedEvent sizeChangedEvent;
UserInterruptionEvent userInterruptionEvent;
HangupEvent hangupEvent;
EndOfFileEvent endOfFileEvent;
LinkEvent linkEvent;
CustomEvent customEvent;
}
}
}
version(Demo)
/// View the source of this!
void main() {
auto terminal = Terminal(ConsoleOutputType.cellular);
//terminal.color(Color.DEFAULT, Color.DEFAULT);
//
///*
auto getter = new FileLineGetter(&terminal, "test");
getter.prompt = "> ";
getter.history = ["abcdefghijklmnopqrstuvwzyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"];
terminal.writeln("\n" ~ getter.getline());
terminal.writeln("\n" ~ getter.getline());
terminal.writeln("\n" ~ getter.getline());
getter.dispose();
//*/
terminal.writeln(terminal.getline());
terminal.writeln(terminal.getline());
terminal.writeln(terminal.getline());
//input.getch();
// return;
//
terminal.setTitle("Basic I/O");
auto input = RealTimeConsoleInput(&terminal, ConsoleInputFlags.raw | ConsoleInputFlags.allInputEventsWithRelease);
terminal.color(Color.green | Bright, Color.black);
terminal.write("test some long string to see if it wraps or what because i dont really know what it is going to do so i just want to test i think it will wrap but gotta be sure lolololololololol");
terminal.writefln("%d %d", terminal.cursorX, terminal.cursorY);
terminal.color(Color.DEFAULT, Color.DEFAULT);
int centerX = terminal.width / 2;
int centerY = terminal.height / 2;
bool timeToBreak = false;
terminal.hyperlink("test", 4);
terminal.hyperlink("another", 7);
void handleEvent(InputEvent event) {
//terminal.writef("%s\n", event.type);
final switch(event.type) {
case InputEvent.Type.LinkEvent:
auto ev = event.get!(InputEvent.Type.LinkEvent);
terminal.writeln(ev);
break;
case InputEvent.Type.UserInterruptionEvent:
case InputEvent.Type.HangupEvent:
case InputEvent.Type.EndOfFileEvent:
timeToBreak = true;
version(with_eventloop) {
import arsd.eventloop;
exit();
}
break;
case InputEvent.Type.SizeChangedEvent:
auto ev = event.get!(InputEvent.Type.SizeChangedEvent);
terminal.writeln(ev);
break;
case InputEvent.Type.KeyboardEvent:
auto ev = event.get!(InputEvent.Type.KeyboardEvent);
terminal.writef("\t%s", ev);
terminal.writef(" (%s)", cast(KeyboardEvent.Key) ev.which);
terminal.writeln();
if(ev.which == 'Q') {
timeToBreak = true;
version(with_eventloop) {
import arsd.eventloop;
exit();
}
}
if(ev.which == 'C')
terminal.clear();
break;
case InputEvent.Type.CharacterEvent: // obsolete
auto ev = event.get!(InputEvent.Type.CharacterEvent);
terminal.writef("\t%s\n", ev);
break;
case InputEvent.Type.NonCharacterKeyEvent: // obsolete
terminal.writef("\t%s\n", event.get!(InputEvent.Type.NonCharacterKeyEvent));
break;
case InputEvent.Type.PasteEvent:
terminal.writef("\t%s\n", event.get!(InputEvent.Type.PasteEvent));
break;
case InputEvent.Type.MouseEvent:
//terminal.writef("\t%s\n", event.get!(InputEvent.Type.MouseEvent));
break;
case InputEvent.Type.CustomEvent:
break;
}
//terminal.writefln("%d %d", terminal.cursorX, terminal.cursorY);
/*
if(input.kbhit()) {
auto c = input.getch();
if(c == 'q' || c == 'Q')
break;
terminal.moveTo(centerX, centerY);
terminal.writef("%c", c);
terminal.flush();
}
usleep(10000);
*/
}
version(with_eventloop) {
import arsd.eventloop;
addListener(&handleEvent);
loop();
} else {
loop: while(true) {
auto event = input.nextEvent();
handleEvent(event);
if(timeToBreak)
break loop;
}
}
}
enum TerminalCapabilities : uint {
minimal = 0,
vt100 = 1 << 0,
// my special terminal emulator extensions
arsdClipboard = 1 << 15, // 90 in caps
arsdImage = 1 << 16, // 91 in caps
arsdHyperlinks = 1 << 17, // 92 in caps
}
version(Posix)
private uint /* TerminalCapabilities bitmask */ getTerminalCapabilities(int fdIn, int fdOut) {
if(fdIn == -1 || fdOut == -1)
return TerminalCapabilities.minimal;
import std.conv;
import core.stdc.errno;
import core.sys.posix.unistd;
ubyte[128] hack2;
termios old;
ubyte[128] hack;
tcgetattr(fdIn, &old);
auto n = old;
n.c_lflag &= ~(ICANON | ECHO);
tcsetattr(fdIn, TCSANOW, &n);
scope(exit)
tcsetattr(fdIn, TCSANOW, &old);
// drain the buffer? meh
string cmd = "\033[c";
auto err = write(fdOut, cmd.ptr, cmd.length);
if(err != cmd.length) {
throw new Exception("couldn't ask terminal for ID");
}
// reading directly to bypass any buffering
int retries = 16;
int len;
ubyte[96] buffer;
try_again:
timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 250 * 1000; // 250 ms
fd_set fs;
FD_ZERO(&fs);
FD_SET(fdIn, &fs);
if(select(fdIn + 1, &fs, null, null, &tv) == -1) {
goto try_again;
}
if(FD_ISSET(fdIn, &fs)) {
auto len2 = read(fdIn, &buffer[len], buffer.length - len);
if(len2 <= 0) {
retries--;
if(retries > 0)
goto try_again;
throw new Exception("can't get terminal id");
} else {
len += len2;
}
} else {
// no data... assume terminal doesn't support giving an answer
return TerminalCapabilities.minimal;
}
ubyte[] answer;
bool hasAnswer(ubyte[] data) {
if(data.length < 4)
return false;
answer = null;
size_t start;
int position = 0;
foreach(idx, ch; data) {
switch(position) {
case 0:
if(ch == '\033') {
start = idx;
position++;
}
break;
case 1:
if(ch == '[')
position++;
else
position = 0;
break;
case 2:
if(ch == '?')
position++;
else
position = 0;
break;
case 3:
// body
if(ch == 'c') {
answer = data[start .. idx + 1];
return true;
} else if(ch == ';' || (ch >= '0' && ch <= '9')) {
// good, keep going
} else {
// invalid, drop it
position = 0;
}
break;
default: assert(0);
}
}
return false;
}
auto got = buffer[0 .. len];
if(!hasAnswer(got)) {
goto try_again;
}
auto gots = cast(char[]) answer[3 .. $-1];
import std.string;
auto pieces = split(gots, ";");
uint ret = TerminalCapabilities.vt100;
foreach(p; pieces)
switch(p) {
case "90":
ret |= TerminalCapabilities.arsdClipboard;
break;
case "91":
ret |= TerminalCapabilities.arsdImage;
break;
case "92":
ret |= TerminalCapabilities.arsdHyperlinks;
break;
default:
}
return ret;
}
private extern(C) int mkstemp(char *templ);
/**
FIXME: support lines that wrap
FIXME: better controls maybe
FIXME: support multi-line "lines" and some form of line continuation, both
from the user (if permitted) and from the application, so like the user
hits "class foo { \n" and the app says "that line needs continuation" automatically.
FIXME: fix lengths on prompt and suggestion
A note on history:
To save history, you must call LineGetter.dispose() when you're done with it.
History will not be automatically saved without that call!
The history saving and loading as a trivially encountered race condition: if you
open two programs that use the same one at the same time, the one that closes second
will overwrite any history changes the first closer saved.
GNU Getline does this too... and it actually kinda drives me nuts. But I don't know
what a good fix is except for doing a transactional commit straight to the file every
time and that seems like hitting the disk way too often.
We could also do like a history server like a database daemon that keeps the order
correct but I don't actually like that either because I kinda like different bashes
to have different history, I just don't like it all to get lost.
Regardless though, this isn't even used in bash anyway, so I don't think I care enough
to put that much effort into it. Just using separate files for separate tasks is good
enough I think.
*/
class LineGetter {
/* A note on the assumeSafeAppends in here: since these buffers are private, we can be
pretty sure that stomping isn't an issue, so I'm using this liberally to keep the
append/realloc code simple and hopefully reasonably fast. */
// saved to file
string[] history;
// not saved
Terminal* terminal;
string historyFilename;
/// Make sure that the parent terminal struct remains in scope for the duration
/// of LineGetter's lifetime, as it does hold on to and use the passed pointer
/// throughout.
///
/// historyFilename will load and save an input history log to a particular folder.
/// Leaving it null will mean no file will be used and history will not be saved across sessions.
this(Terminal* tty, string historyFilename = null) {
this.terminal = tty;
this.historyFilename = historyFilename;
line.reserve(128);
if(historyFilename.length)
loadSettingsAndHistoryFromFile();
regularForeground = cast(Color) terminal._currentForeground;
background = cast(Color) terminal._currentBackground;
suggestionForeground = Color.blue;
}
/// Call this before letting LineGetter die so it can do any necessary
/// cleanup and save the updated history to a file.
void dispose() {
if(historyFilename.length)
saveSettingsAndHistoryToFile();
}
/// Override this to change the directory where history files are stored
///
/// Default is $HOME/.arsd-getline on linux and %APPDATA%/arsd-getline/ on Windows.
/* virtual */ string historyFileDirectory() {
version(Windows) {
char[1024] path;
// FIXME: this doesn't link because the crappy dmd lib doesn't have it
if(0) { // SHGetFolderPathA(null, CSIDL_APPDATA, null, 0, path.ptr) >= 0) {
import core.stdc.string;
return cast(string) path[0 .. strlen(path.ptr)] ~ "\\arsd-getline";
} else {
import std.process;
return environment["APPDATA"] ~ "\\arsd-getline";
}
} else version(Posix) {
import std.process;
return environment["HOME"] ~ "/.arsd-getline";
}
}
/// You can customize the colors here. You should set these after construction, but before
/// calling startGettingLine or getline.
Color suggestionForeground = Color.blue;
Color regularForeground = Color.DEFAULT; /// ditto
Color background = Color.DEFAULT; /// ditto
Color promptColor = Color.DEFAULT; /// ditto
Color specialCharBackground = Color.green; /// ditto
//bool reverseVideo;
/// Set this if you want a prompt to be drawn with the line. It does NOT support color in string.
@property void prompt(string p) {
this.prompt_ = p;
promptLength = 0;
foreach(dchar c; p)
promptLength++;
}
/// ditto
@property string prompt() {
return this.prompt_;
}
private string prompt_;
private int promptLength;
/++
Turn on auto suggest if you want a greyed thing of what tab
would be able to fill in as you type.
You might want to turn it off if generating a completion list is slow.
Or if you know you want it, be sure to turn it on explicitly in your
code because I reserve the right to change the default without advance notice.
History:
On March 4, 2020, I changed the default to `false` because it
is kinda slow and not useful in all cases.
+/
bool autoSuggest = false;
/++
Returns true if there was any input in the buffer. Can be
checked in the case of a [UserInterruptionException].
+/
bool hadInput() {
return line.length > 0;
}
/// Override this if you don't want all lines added to the history.
/// You can return null to not add it at all, or you can transform it.
/* virtual */ string historyFilter(string candidate) {
return candidate;
}
/// You may override this to do nothing
/* virtual */ void saveSettingsAndHistoryToFile() {
import std.file;
if(!exists(historyFileDirectory))
mkdir(historyFileDirectory);
auto fn = historyPath();
import std.stdio;
auto file = File(fn, "wt");
foreach(item; history)
file.writeln(item);
}
/++
History:
Introduced on January 31, 2020
+/
/* virtual */ string historyFileExtension() {
return ".history";
}
private string historyPath() {
import std.path;
auto filename = historyFileDirectory() ~ dirSeparator ~ historyFilename ~ historyFileExtension();
return filename;
}
/// You may override this to do nothing
/* virtual */ void loadSettingsAndHistoryFromFile() {
import std.file;
history = null;
auto fn = historyPath();
if(exists(fn)) {
import std.stdio;
foreach(line; File(fn, "rt").byLine)
history ~= line.idup;
}
}
/++
Override this to provide tab completion. You may use the candidate
argument to filter the list, but you don't have to (LineGetter will
do it for you on the values you return). This means you can ignore
the arguments if you like.
Ideally, you wouldn't return more than about ten items since the list
gets difficult to use if it is too long.
Tab complete cannot modify text before or after the cursor at this time.
I *might* change that later to allow tab complete to fuzzy search and spell
check fix before. But right now it ONLY inserts.
Default is to provide recent command history as autocomplete.
Returns:
This function should return the full string to replace
`candidate[tabCompleteStartPoint(args) .. $]`.
For example, if your user wrote `wri<tab>` and you want to complete
it to `write` or `writeln`, you should return `["write", "writeln"]`.
If you offer different tab complete in different places, you still
need to return the whole string. For example, a file competition of
a second argument, when the user writes `terminal.d term<tab>` and you
want it to complete to an additional `terminal.d`, you should return
`["terminal.d terminal.d"]`; in other words, `candidate ~ completion`
for each completion.
It does this so you can simply return an array of words without having
to rebuild that array for each combination.
To choose the word separator, override [tabCompleteStartPoint].
Params:
candidate = the text of the line up to the text cursor, after
which the completed text would be inserted
afterCursor = the remaining text after the cursor. You can inspect
this, but cannot change it - this will be appended to the line
after completion, keeping the cursor in the same relative location.
History:
Prior to January 30, 2020, this method took only one argument,
`candidate`. It now takes `afterCursor` as well, to allow you to
make more intelligent completions with full context.
+/
/* virtual */ protected string[] tabComplete(in dchar[] candidate, in dchar[] afterCursor) {
return history.length > 20 ? history[0 .. 20] : history;
}
/++
Override this to provide a different tab competition starting point. The default
is `0`, always completing the complete line, but you may return the index of another
character of `candidate` to provide a new split.
Returns:
The index of `candidate` where we should start the slice to keep in [tabComplete].
It must be `>= 0 && <= candidate.length`.
History:
Added on February 1, 2020. Initial default is to return 0 to maintain
old behavior.
+/
/* virtual */ protected size_t tabCompleteStartPoint(in dchar[] candidate, in dchar[] afterCursor) {
return 0;
}
/++
This gives extra information for an item when displaying tab competition details.
History:
Added January 31, 2020.
+/
/* virtual */ protected string tabCompleteHelp(string candidate) {
return null;
}
private string[] filterTabCompleteList(string[] list, size_t start) {
if(list.length == 0)
return list;
string[] f;
f.reserve(list.length);
foreach(item; list) {
import std.algorithm;
if(startsWith(item, line[start .. cursorPosition]))
f ~= item;
}
/+
// if it is excessively long, let's trim it down by trying to
// group common sub-sequences together.
if(f.length > terminal.height * 3 / 4) {
import std.algorithm;
f.sort();
// see how many can be saved by just keeping going until there is
// no more common prefix. then commit that and keep on down the list.
// since it is sorted, if there is a commonality, it should appear quickly
string[] n;
string commonality = f[0];
size_t idx = 1;
while(idx < f.length) {
auto c = commonPrefix(commonality, f[idx]);
if(c.length > cursorPosition - start) {
commonality = c;
} else {
n ~= commonality;
commonality = f[idx];
}
idx++;
}
if(commonality.length)
n ~= commonality;
if(n.length)
f = n;
}
+/
return f;
}
/++
Override this to provide a custom display of the tab completion list.
History:
Prior to January 31, 2020, it only displayed the list. After
that, it would call [tabCompleteHelp] for each candidate and display
that string (if present) as well.
+/
protected void showTabCompleteList(string[] list) {
if(list.length) {
// FIXME: allow mouse clicking of an item, that would be cool
auto start = tabCompleteStartPoint(line[0 .. cursorPosition], line[cursorPosition .. $]);
// FIXME: scroll
//if(terminal.type == ConsoleOutputType.linear) {
terminal.writeln();
foreach(item; list) {
terminal.color(suggestionForeground, background);
import std.utf;
auto idx = codeLength!char(line[start .. cursorPosition]);
terminal.write(" ", item[0 .. idx]);
terminal.color(regularForeground, background);
terminal.write(item[idx .. $]);
auto help = tabCompleteHelp(item);
if(help !is null) {
import std.string;
help = help.replace("\t", " ").replace("\n", " ").replace("\r", " ");
terminal.write("\t\t");
int remaining;
if(terminal.cursorX + 2 < terminal.width) {
remaining = terminal.width - terminal.cursorX - 2;
}
if(remaining > 8)
terminal.write(remaining < help.length ? help[0 .. remaining] : help);
}
terminal.writeln();
}
updateCursorPosition();
redraw();
//}
}
}
/++
Called by the default event loop when the user presses F1. Override
`showHelp` to change the UI, override [helpMessage] if you just want
to change the message.
History:
Introduced on January 30, 2020
+/
protected void showHelp() {
terminal.writeln();
terminal.writeln(helpMessage);
updateCursorPosition();
redraw();
}
/++
History:
Introduced on January 30, 2020
+/
protected string helpMessage() {
return "Press F2 to edit current line in your editor. F3 searches. F9 runs current line while maintaining current edit state.";
}
/++
History:
Introduced on January 30, 2020
+/
protected dchar[] editLineInEditor(in dchar[] line, in size_t cursorPosition) {
import std.conv;
import std.process;
import std.file;
char[] tmpName;
version(Windows) {
import core.stdc.string;
char[280] path;
auto l = GetTempPathA(cast(DWORD) path.length, path.ptr);
if(l == 0) throw new Exception("GetTempPathA");
path[l] = 0;
char[280] name;
auto r = GetTempFileNameA(path.ptr, "adr", 0, name.ptr);
if(r == 0) throw new Exception("GetTempFileNameA");
tmpName = name[0 .. strlen(name.ptr)];
scope(exit)
std.file.remove(tmpName);
std.file.write(tmpName, to!string(line));
string editor = environment.get("EDITOR", "notepad.exe");
} else {
import core.stdc.stdlib;
import core.sys.posix.unistd;
char[120] name;
string p = "/tmp/adrXXXXXX";
name[0 .. p.length] = p[];
name[p.length] = 0;
auto fd = mkstemp(name.ptr);
tmpName = name[0 .. p.length];
if(fd == -1) throw new Exception("mkstemp");
scope(exit)
close(fd);
scope(exit)
std.file.remove(tmpName);
string s = to!string(line);
while(s.length) {
auto x = write(fd, s.ptr, s.length);
if(x == -1) throw new Exception("write");
s = s[x .. $];
}
string editor = environment.get("EDITOR", "vi");
}
// FIXME the spawned process changes terminal state!
spawnProcess([editor, tmpName]).wait;
import std.string;
return to!(dchar[])(cast(char[]) std.file.read(tmpName)).chomp;
}
//private RealTimeConsoleInput* rtci;
/// One-call shop for the main workhorse
/// If you already have a RealTimeConsoleInput ready to go, you
/// should pass a pointer to yours here. Otherwise, LineGetter will
/// make its own.
public string getline(RealTimeConsoleInput* input = null) {
startGettingLine();
if(input is null) {
auto i = RealTimeConsoleInput(terminal, ConsoleInputFlags.raw | ConsoleInputFlags.allInputEvents | ConsoleInputFlags.noEolWrap);
//rtci = &i;
//scope(exit) rtci = null;
while(workOnLine(i.nextEvent(), &i)) {}
} else {
//rtci = input;
//scope(exit) rtci = null;
while(workOnLine(input.nextEvent(), input)) {}
}
return finishGettingLine();
}
private int currentHistoryViewPosition = 0;
private dchar[] uncommittedHistoryCandidate;
void loadFromHistory(int howFarBack) {
if(howFarBack < 0)
howFarBack = 0;
if(howFarBack > history.length) // lol signed/unsigned comparison here means if i did this first, before howFarBack < 0, it would totally cycle around.
howFarBack = cast(int) history.length;
if(howFarBack == currentHistoryViewPosition)
return;
if(currentHistoryViewPosition == 0) {
// save the current line so we can down arrow back to it later
if(uncommittedHistoryCandidate.length < line.length) {
uncommittedHistoryCandidate.length = line.length;
}
uncommittedHistoryCandidate[0 .. line.length] = line[];
uncommittedHistoryCandidate = uncommittedHistoryCandidate[0 .. line.length];
uncommittedHistoryCandidate.assumeSafeAppend();
}
currentHistoryViewPosition = howFarBack;
if(howFarBack == 0) {
line.length = uncommittedHistoryCandidate.length;
line.assumeSafeAppend();
line[] = uncommittedHistoryCandidate[];
} else {
line = line[0 .. 0];
line.assumeSafeAppend();
foreach(dchar ch; history[$ - howFarBack])
line ~= ch;
}
cursorPosition = cast(int) line.length;
scrollToEnd();
}
bool insertMode = true;
bool multiLineMode = false;
private dchar[] line;
private int cursorPosition = 0;
private int horizontalScrollPosition = 0;
private void scrollToEnd() {
horizontalScrollPosition = (cast(int) line.length);
horizontalScrollPosition -= availableLineLength();
if(horizontalScrollPosition < 0)
horizontalScrollPosition = 0;
}
// used for redrawing the line in the right place
// and detecting mouse events on our line.
private int startOfLineX;
private int startOfLineY;
// private string[] cachedCompletionList;
// FIXME
// /// Note that this assumes the tab complete list won't change between actual
// /// presses of tab by the user. If you pass it a list, it will use it, but
// /// otherwise it will keep track of the last one to avoid calls to tabComplete.
private string suggestion(string[] list = null) {
import std.algorithm, std.utf;
auto relevantLineSection = line[0 .. cursorPosition];
auto start = tabCompleteStartPoint(relevantLineSection, line[cursorPosition .. $]);
relevantLineSection = relevantLineSection[start .. $];
// FIXME: see about caching the list if we easily can
if(list is null)
list = filterTabCompleteList(tabComplete(relevantLineSection, line[cursorPosition .. $]), start);
if(list.length) {
string commonality = list[0];
foreach(item; list[1 .. $]) {
commonality = commonPrefix(commonality, item);
}
if(commonality.length) {
return commonality[codeLength!char(relevantLineSection) .. $];
}
}
return null;
}
/// Adds a character at the current position in the line. You can call this too if you hook events for hotkeys or something.
/// You'll probably want to call redraw() after adding chars.
void addChar(dchar ch) {
assert(cursorPosition >= 0 && cursorPosition <= line.length);
if(cursorPosition == line.length)
line ~= ch;
else {
assert(line.length);
if(insertMode) {
line ~= ' ';
for(int i = cast(int) line.length - 2; i >= cursorPosition; i --)
line[i + 1] = line[i];
}
line[cursorPosition] = ch;
}
cursorPosition++;
if(cursorPosition >= horizontalScrollPosition + availableLineLength())
horizontalScrollPosition++;
}
/// .
void addString(string s) {
// FIXME: this could be more efficient
// but does it matter? these lines aren't super long anyway. But then again a paste could be excessively long (prolly accidental, but still)
foreach(dchar ch; s)
addChar(ch);
}
/// Deletes the character at the current position in the line.
/// You'll probably want to call redraw() after deleting chars.
void deleteChar() {
if(cursorPosition == line.length)
return;
for(int i = cursorPosition; i < line.length - 1; i++)
line[i] = line[i + 1];
line = line[0 .. $-1];
line.assumeSafeAppend();
}
///
void deleteToEndOfLine() {
line = line[0 .. cursorPosition];
line.assumeSafeAppend();
//while(cursorPosition < line.length)
//deleteChar();
}
int availableLineLength() {
return terminal.width - startOfLineX - promptLength - 1;
}
private int lastDrawLength = 0;
void redraw() {
terminal.hideCursor();
scope(exit) {
version(Win32Console) {
// on Windows, we want to make sure all
// is displayed before the cursor jumps around
terminal.flush();
terminal.showCursor();
} else {
// but elsewhere, the showCursor is itself buffered,
// so we can do it all at once for a slight speed boost
terminal.showCursor();
//import std.string; import std.stdio; writeln(terminal.writeBuffer.replace("\033", "\\e"));
terminal.flush();
}
}
terminal.moveTo(startOfLineX, startOfLineY);
auto lineLength = availableLineLength();
if(lineLength < 0)
throw new Exception("too narrow terminal to draw");
terminal.color(promptColor, background);
terminal.write(prompt);
terminal.color(regularForeground, background);
auto towrite = line[horizontalScrollPosition .. $];
auto cursorPositionToDrawX = cursorPosition - horizontalScrollPosition;
auto cursorPositionToDrawY = 0;
int written = promptLength;
void specialChar(char c) {
terminal.color(regularForeground, specialCharBackground);
terminal.write(c);
terminal.color(regularForeground, background);
written++;
lineLength--;
}
void regularChar(dchar ch) {
import std.utf;
char[4] buffer;
auto l = encode(buffer, ch);
// note the Terminal buffers it so meh
terminal.write(buffer[0 .. l]);
written++;
lineLength--;
}
// FIXME: if there is a color at the end of the line it messes up as you scroll
// FIXME: need a way to go to multi-line editing
foreach(dchar ch; towrite) {
if(lineLength == 0)
break;
switch(ch) {
case '\n': specialChar('n'); break;
case '\r': specialChar('r'); break;
case '\a': specialChar('a'); break;
case '\t': specialChar('t'); break;
case '\b': specialChar('b'); break;
case '\033': specialChar('e'); break;
default:
regularChar(ch);
}
}
string suggestion;
if(lineLength >= 0) {
suggestion = ((cursorPosition == towrite.length) && autoSuggest) ? this.suggestion() : null;
if(suggestion.length) {
terminal.color(suggestionForeground, background);
foreach(dchar ch; suggestion) {
if(lineLength == 0)
break;
regularChar(ch);
}
terminal.color(regularForeground, background);
}
}
// FIXME: graphemes
if(written < lastDrawLength)
foreach(i; written .. lastDrawLength)
terminal.write(" ");
lastDrawLength = written;
terminal.moveTo(startOfLineX + cursorPositionToDrawX + promptLength, startOfLineY + cursorPositionToDrawY);
}
/// Starts getting a new line. Call workOnLine and finishGettingLine afterward.
///
/// Make sure that you've flushed your input and output before calling this
/// function or else you might lose events or get exceptions from this.
void startGettingLine() {
// reset from any previous call first
if(!maintainBuffer) {
cursorPosition = 0;
horizontalScrollPosition = 0;
justHitTab = false;
currentHistoryViewPosition = 0;
if(line.length) {
line = line[0 .. 0];
line.assumeSafeAppend();
}
}
maintainBuffer = false;
initializeWithSize(true);
terminal.cursor = TerminalCursor.insert;
terminal.showCursor();
}
private void positionCursor() {
if(cursorPosition == 0)
horizontalScrollPosition = 0;
else if(cursorPosition == line.length)
scrollToEnd();
else {
// otherwise just try to center it in the screen
horizontalScrollPosition = cursorPosition;
horizontalScrollPosition -= terminal.width / 2;
// align on a code point boundary
aligned(horizontalScrollPosition, -1);
if(horizontalScrollPosition < 0)
horizontalScrollPosition = 0;
}
}
private void aligned(ref int what, int direction) {
// whereas line is right now dchar[] no need for this
// at least until we go by grapheme...
/*
while(what > 0 && what < line.length && ((line[what] & 0b1100_0000) == 0b1000_0000))
what += direction;
*/
}
private void initializeWithSize(bool firstEver = false) {
auto x = startOfLineX;
updateCursorPosition();
if(!firstEver) {
startOfLineX = x;
positionCursor();
}
lastDrawLength = terminal.width - terminal.cursorX;
version(Win32Console)
lastDrawLength -= 1; // I don't like this but Windows resizing is different anyway and it is liable to scroll if i go over..
redraw();
}
private void updateCursorPosition() {
terminal.flush();
// then get the current cursor position to start fresh
version(TerminalDirectToEmulator) {
if(!terminal.usingDirectEmulator)
return updateCursorPosition_impl();
startOfLineX = terminal.tew.terminalEmulator.cursorX;
startOfLineY = terminal.tew.terminalEmulator.cursorY;
} else
updateCursorPosition_impl();
}
private void updateCursorPosition_impl() {
version(Win32Console) {
CONSOLE_SCREEN_BUFFER_INFO info;
GetConsoleScreenBufferInfo(terminal.hConsole, &info);
startOfLineX = info.dwCursorPosition.X;
startOfLineY = info.dwCursorPosition.Y;
} else version(Posix) {
// request current cursor position
// we have to turn off cooked mode to get this answer, otherwise it will all
// be messed up. (I hate unix terminals, the Windows way is so much easer.)
// We also can't use RealTimeConsoleInput here because it also does event loop stuff
// which would be broken by the child destructor :( (maybe that should be a FIXME)
/+
if(rtci !is null) {
while(rtci.timedCheckForInput_bypassingBuffer(1000))
rtci.inputQueue ~= rtci.readNextEvents();
}
+/
ubyte[128] hack2;
termios old;
ubyte[128] hack;
tcgetattr(terminal.fdIn, &old);
auto n = old;
n.c_lflag &= ~(ICANON | ECHO);
tcsetattr(terminal.fdIn, TCSANOW, &n);
scope(exit)
tcsetattr(terminal.fdIn, TCSANOW, &old);
terminal.writeStringRaw("\033[6n");
terminal.flush();
import std.conv;
import core.stdc.errno;
import core.sys.posix.unistd;
ubyte readOne() {
ubyte[1] buffer;
int tries = 0;
try_again:
if(tries > 30)
throw new Exception("terminal reply timed out");
auto len = read(terminal.fdIn, buffer.ptr, buffer.length);
if(len == -1) {
if(errno == EINTR)
goto try_again;
if(errno == EAGAIN || errno == EWOULDBLOCK) {
import core.thread;
Thread.sleep(10.msecs);
tries++;
goto try_again;
}
} else if(len == 0) {
throw new Exception("Couldn't get cursor position to initialize get line " ~ to!string(len) ~ " " ~ to!string(errno));
}
return buffer[0];
}
nextEscape:
while(readOne() != '\033') {}
if(readOne() != '[')
goto nextEscape;
int x, y;
// now we should have some numbers being like yyy;xxxR
// but there may be a ? in there too; DEC private mode format
// of the very same data.
x = 0;
y = 0;
auto b = readOne();
if(b == '?')
b = readOne(); // no big deal, just ignore and continue
nextNumberY:
if(b >= '0' && b <= '9') {
y *= 10;
y += b - '0';
} else goto nextEscape;
b = readOne();
if(b != ';')
goto nextNumberY;
b = readOne();
nextNumberX:
if(b >= '0' && b <= '9') {
x *= 10;
x += b - '0';
} else goto nextEscape;
b = readOne();
// another digit
if(b >= '0' && b <= '9')
goto nextNumberX;
if(b != 'R')
goto nextEscape; // it wasn't the right thing it after all
startOfLineX = x - 1;
startOfLineY = y - 1;
}
// updating these too because I can with the more accurate info from above
terminal._cursorX = startOfLineX;
terminal._cursorY = startOfLineY;
}
private bool justHitTab;
private bool eof;
///
string delegate(string s) pastePreprocessor;
string defaultPastePreprocessor(string s) {
return s;
}
void showIndividualHelp(string help) {
terminal.writeln();
terminal.writeln(help);
}
private bool maintainBuffer;
/++
for integrating into another event loop
you can pass individual events to this and
the line getter will work on it
returns false when there's nothing more to do
History:
On February 17, 2020, it was changed to take
a new argument which should be the input source
where the event came from.
+/
bool workOnLine(InputEvent e, RealTimeConsoleInput* rtti = null) {
switch(e.type) {
case InputEvent.Type.EndOfFileEvent:
justHitTab = false;
eof = true;
// FIXME: this should be distinct from an empty line when hit at the beginning
return false;
//break;
case InputEvent.Type.KeyboardEvent:
auto ev = e.keyboardEvent;
if(ev.pressed == false)
return true;
/* Insert the character (unless it is backspace, tab, or some other control char) */
auto ch = ev.which;
switch(ch) {
version(Windows) case 26: // and this is really for Windows
goto case;
case 4: // ctrl+d will also send a newline-equivalent
if(line.length == 0)
eof = true;
goto case;
case '\r':
case '\n':
justHitTab = false;
return false;
case '\t':
auto relevantLineSection = line[0 .. cursorPosition];
auto start = tabCompleteStartPoint(relevantLineSection, line[cursorPosition .. $]);
relevantLineSection = relevantLineSection[start .. $];
auto possibilities = filterTabCompleteList(tabComplete(relevantLineSection, line[cursorPosition .. $]), start);
import std.utf;
if(possibilities.length == 1) {
auto toFill = possibilities[0][codeLength!char(relevantLineSection) .. $];
if(toFill.length) {
addString(toFill);
redraw();
} else {
auto help = this.tabCompleteHelp(possibilities[0]);
if(help.length) {
showIndividualHelp(help);
updateCursorPosition();
redraw();
}
}
justHitTab = false;
} else {
if(justHitTab) {
justHitTab = false;
showTabCompleteList(possibilities);
} else {
justHitTab = true;
/* fill it in with as much commonality as there is amongst all the suggestions */
auto suggestion = this.suggestion(possibilities);
if(suggestion.length) {
addString(suggestion);
redraw();
}
}
}
break;
case '\b':
justHitTab = false;
if(cursorPosition) {
cursorPosition--;
for(int i = cursorPosition; i < line.length - 1; i++)
line[i] = line[i + 1];
line = line[0 .. $ - 1];
line.assumeSafeAppend();
if(!multiLineMode) {
if(horizontalScrollPosition > cursorPosition - 1)
horizontalScrollPosition = cursorPosition - 1 - availableLineLength();
if(horizontalScrollPosition < 0)
horizontalScrollPosition = 0;
}
redraw();
}
break;
case KeyboardEvent.Key.escape:
justHitTab = false;
cursorPosition = 0;
horizontalScrollPosition = 0;
line = line[0 .. 0];
line.assumeSafeAppend();
redraw();
break;
case KeyboardEvent.Key.F1:
justHitTab = false;
showHelp();
break;
case KeyboardEvent.Key.F2:
justHitTab = false;
line = editLineInEditor(line, cursorPosition);
if(cursorPosition > line.length)
cursorPosition = cast(int) line.length;
if(horizontalScrollPosition > line.length)
horizontalScrollPosition = cast(int) line.length;
positionCursor();
redraw();
break;
case KeyboardEvent.Key.F3:
// case 'r' - 'a' + 1: // ctrl+r
justHitTab = false;
// search in history
// FIXME: what about search in completion too?
break;
case KeyboardEvent.Key.F4:
justHitTab = false;
// FIXME: clear line
break;
case KeyboardEvent.Key.F9:
justHitTab = false;
// compile and run analog; return the current string
// but keep the buffer the same
maintainBuffer = true;
return false;
case 0x1d: // ctrl+5, because of vim % shortcut
justHitTab = false;
// FIXME: find matching delimiter
break;
case KeyboardEvent.Key.LeftArrow:
justHitTab = false;
if(cursorPosition)
cursorPosition--;
if(ev.modifierState & ModifierState.control) {
while(cursorPosition && line[cursorPosition - 1] != ' ')
cursorPosition--;
}
aligned(cursorPosition, -1);
if(cursorPosition < horizontalScrollPosition)
positionCursor();
redraw();
break;
case KeyboardEvent.Key.RightArrow:
justHitTab = false;
if(cursorPosition < line.length)
cursorPosition++;
if(ev.modifierState & ModifierState.control) {
while(cursorPosition + 1 < line.length && line[cursorPosition + 1] != ' ')
cursorPosition++;
cursorPosition += 2;
if(cursorPosition > line.length)
cursorPosition = cast(int) line.length;
}
aligned(cursorPosition, 1);
if(cursorPosition > horizontalScrollPosition + availableLineLength())
positionCursor();
redraw();
break;
case KeyboardEvent.Key.UpArrow:
justHitTab = false;
loadFromHistory(currentHistoryViewPosition + 1);
redraw();
break;
case KeyboardEvent.Key.DownArrow:
justHitTab = false;
loadFromHistory(currentHistoryViewPosition - 1);
redraw();
break;
case KeyboardEvent.Key.PageUp:
justHitTab = false;
loadFromHistory(cast(int) history.length);
redraw();
break;
case KeyboardEvent.Key.PageDown:
justHitTab = false;
loadFromHistory(0);
redraw();
break;
case 1: // ctrl+a does home too in the emacs keybindings
case KeyboardEvent.Key.Home:
justHitTab = false;
cursorPosition = 0;
horizontalScrollPosition = 0;
redraw();
break;
case 5: // ctrl+e from emacs
case KeyboardEvent.Key.End:
justHitTab = false;
cursorPosition = cast(int) line.length;
scrollToEnd();
redraw();
break;
case ('v' - 'a' + 1):
if(rtti)
rtti.requestPasteFromClipboard();
break;
case KeyboardEvent.Key.Insert:
justHitTab = false;
if(ev.modifierState & ModifierState.shift) {
// paste
// shift+insert = request paste
// ctrl+insert = request copy. but that needs a selection
// those work on Windows!!!! and many linux TEs too.
// but if it does make it here, we'll attempt it at this level
if(rtti)
rtti.requestPasteFromClipboard();
} else if(ev.modifierState & ModifierState.control) {
// copy
// FIXME
} else {
insertMode = !insertMode;
if(insertMode)
terminal.cursor = TerminalCursor.insert;
else
terminal.cursor = TerminalCursor.block;
}
break;
case KeyboardEvent.Key.Delete:
justHitTab = false;
if(ev.modifierState & ModifierState.control)
deleteToEndOfLine();
else
deleteChar();
redraw();
break;
case 11: // ctrl+k is delete to end of line from emacs
justHitTab = false;
deleteToEndOfLine();
redraw();
break;
default:
justHitTab = false;
if(e.keyboardEvent.isCharacter)
addChar(ch);
redraw();
}
break;
case InputEvent.Type.PasteEvent:
justHitTab = false;
if(pastePreprocessor)
addString(pastePreprocessor(e.pasteEvent.pastedText));
else
addString(defaultPastePreprocessor(e.pasteEvent.pastedText));
redraw();
break;
case InputEvent.Type.MouseEvent:
/* Clicking with the mouse to move the cursor is so much easier than arrowing
or even emacs/vi style movements much of the time, so I'ma support it. */
auto me = e.mouseEvent;
if(me.eventType == MouseEvent.Type.Pressed) {
if(me.buttons & MouseEvent.Button.Left) {
if(me.y == startOfLineY) {
int p = me.x - startOfLineX - promptLength + horizontalScrollPosition;
if(p >= 0 && p < line.length) {
justHitTab = false;
cursorPosition = p;
redraw();
}
}
}
if(me.buttons & MouseEvent.Button.Middle) {
if(rtti)
rtti.requestPasteFromPrimary();
}
}
break;
case InputEvent.Type.SizeChangedEvent:
/* We'll adjust the bounding box. If you don't like this, handle SizeChangedEvent
yourself and then don't pass it to this function. */
// FIXME
initializeWithSize();
break;
case InputEvent.Type.UserInterruptionEvent:
/* I'll take this as canceling the line. */
throw new UserInterruptionException();
//break;
case InputEvent.Type.HangupEvent:
/* I'll take this as canceling the line. */
throw new HangupException();
//break;
default:
/* ignore. ideally it wouldn't be passed to us anyway! */
}
return true;
}
string finishGettingLine() {
import std.conv;
auto f = to!string(line);
auto history = historyFilter(f);
if(history !is null)
this.history ~= history;
// FIXME: we should hide the cursor if it was hidden in the call to startGettingLine
return eof ? null : f.length ? f : "";
}
}
/// Adds default constructors that just forward to the superclass
mixin template LineGetterConstructors() {
this(Terminal* tty, string historyFilename = null) {
super(tty, historyFilename);
}
}
/// This is a line getter that customizes the tab completion to
/// fill in file names separated by spaces, like a command line thing.
class FileLineGetter : LineGetter {
mixin LineGetterConstructors;
/// You can set this property to tell it where to search for the files
/// to complete.
string searchDirectory = ".";
override size_t tabCompleteStartPoint(in dchar[] candidate, in dchar[] afterCursor) {
import std.string;
return candidate.lastIndexOf(" ") + 1;
}
override protected string[] tabComplete(in dchar[] candidate, in dchar[] afterCursor) {
import std.file, std.conv, std.algorithm, std.string;
string[] list;
foreach(string name; dirEntries(searchDirectory, SpanMode.breadth)) {
// both with and without the (searchDirectory ~ "/")
list ~= name[searchDirectory.length + 1 .. $];
list ~= name[0 .. $];
}
return list;
}
}
version(Windows) {
// to get the directory for saving history in the line things
enum CSIDL_APPDATA = 26;
extern(Windows) HRESULT SHGetFolderPathA(HWND, int, HANDLE, DWORD, LPSTR);
}
/* Like getting a line, printing a lot of lines is kinda important too, so I'm including
that widget here too. */
struct ScrollbackBuffer {
bool demandsAttention;
this(string name) {
this.name = name;
}
void write(T...)(T t) {
import std.conv : text;
addComponent(text(t), foreground_, background_, null);
}
void writeln(T...)(T t) {
write(t, "\n");
}
void writef(T...)(string fmt, T t) {
import std.format: format;
write(format(fmt, t));
}
void writefln(T...)(string fmt, T t) {
writef(fmt, t, "\n");
}
void clear() {
lines.clear();
clickRegions = null;
scrollbackPosition = 0;
}
int foreground_ = Color.DEFAULT, background_ = Color.DEFAULT;
void color(int foreground, int background) {
this.foreground_ = foreground;
this.background_ = background;
}
void addComponent(string text, int foreground, int background, bool delegate() onclick) {
if(lines.length == 0) {
addLine();
}
bool first = true;
import std.algorithm;
foreach(t; splitter(text, "\n")) {
if(!first) addLine();
first = false;
lines[$-1].components ~= LineComponent(t, foreground, background, onclick);
}
}
void addLine() {
lines ~= Line();
if(scrollbackPosition) // if the user is scrolling back, we want to keep them basically centered where they are
scrollbackPosition++;
}
void addLine(string line) {
lines ~= Line([LineComponent(line)]);
if(scrollbackPosition) // if the user is scrolling back, we want to keep them basically centered where they are
scrollbackPosition++;
}
void scrollUp(int lines = 1) {
scrollbackPosition += lines;
//if(scrollbackPosition >= this.lines.length)
// scrollbackPosition = cast(int) this.lines.length - 1;
}
void scrollDown(int lines = 1) {
scrollbackPosition -= lines;
if(scrollbackPosition < 0)
scrollbackPosition = 0;
}
void scrollToBottom() {
scrollbackPosition = 0;
}
// this needs width and height to know how to word wrap it
void scrollToTop(int width, int height) {
scrollbackPosition = scrollTopPosition(width, height);
}
struct LineComponent {
string text;
bool isRgb;
union {
int color;
RGB colorRgb;
}
union {
int background;
RGB backgroundRgb;
}
bool delegate() onclick; // return true if you need to redraw
// 16 color ctor
this(string text, int color = Color.DEFAULT, int background = Color.DEFAULT, bool delegate() onclick = null) {
this.text = text;
this.color = color;
this.background = background;
this.onclick = onclick;
this.isRgb = false;
}
// true color ctor
this(string text, RGB colorRgb, RGB backgroundRgb = RGB(0, 0, 0), bool delegate() onclick = null) {
this.text = text;
this.colorRgb = colorRgb;
this.backgroundRgb = backgroundRgb;
this.onclick = onclick;
this.isRgb = true;
}
}
struct Line {
LineComponent[] components;
int length() {
int l = 0;
foreach(c; components)
l += c.text.length;
return l;
}
}
static struct CircularBuffer(T) {
T[] backing;
enum maxScrollback = 8192; // as a power of 2, i hope the compiler optimizes the % below to a simple bit mask...
int start;
int length_;
void clear() {
backing = null;
start = 0;
length_ = 0;
}
size_t length() {
return length_;
}
void opOpAssign(string op : "~")(T line) {
if(length_ < maxScrollback) {
backing.assumeSafeAppend();
backing ~= line;
length_++;
} else {
backing[start] = line;
start++;
if(start == maxScrollback)
start = 0;
}
}
ref T opIndex(int idx) {
return backing[(start + idx) % maxScrollback];
}
ref T opIndex(Dollar idx) {
return backing[(start + (length + idx.offsetFromEnd)) % maxScrollback];
}
CircularBufferRange opSlice(int startOfIteration, Dollar end) {
return CircularBufferRange(&this, startOfIteration, cast(int) length - startOfIteration + end.offsetFromEnd);
}
CircularBufferRange opSlice(int startOfIteration, int end) {
return CircularBufferRange(&this, startOfIteration, end - startOfIteration);
}
CircularBufferRange opSlice() {
return CircularBufferRange(&this, 0, cast(int) length);
}
static struct CircularBufferRange {
CircularBuffer* item;
int position;
int remaining;
this(CircularBuffer* item, int startOfIteration, int count) {
this.item = item;
position = startOfIteration;
remaining = count;
}
ref T front() { return (*item)[position]; }
bool empty() { return remaining <= 0; }
void popFront() {
position++;
remaining--;
}
ref T back() { return (*item)[remaining - 1 - position]; }
void popBack() {
remaining--;
}
}
static struct Dollar {
int offsetFromEnd;
Dollar opBinary(string op : "-")(int rhs) {
return Dollar(offsetFromEnd - rhs);
}
}
Dollar opDollar() { return Dollar(0); }
}
CircularBuffer!Line lines;
string name;
int x, y, width, height;
int scrollbackPosition;
int scrollTopPosition(int width, int height) {
int lineCount;
foreach_reverse(line; lines) {
int written = 0;
comp_loop: foreach(cidx, component; line.components) {
auto towrite = component.text;
foreach(idx, dchar ch; towrite) {
if(written >= width) {
lineCount++;
written = 0;
}
if(ch == '\t')
written += 8; // FIXME
else
written++;
}
}
lineCount++;
}
//if(lineCount > height)
return lineCount - height;
//return 0;
}
void drawInto(Terminal* terminal, in int x = 0, in int y = 0, int width = 0, int height = 0) {
if(lines.length == 0)
return;
if(width == 0)
width = terminal.width;
if(height == 0)
height = terminal.height;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
/* We need to figure out how much is going to fit
in a first pass, so we can figure out where to
start drawing */
int remaining = height + scrollbackPosition;
int start = cast(int) lines.length;
int howMany = 0;
bool firstPartial = false;
static struct Idx {
size_t cidx;
size_t idx;
}
Idx firstPartialStartIndex;
// this is private so I know we can safe append
clickRegions.length = 0;
clickRegions.assumeSafeAppend();
// FIXME: should prolly handle \n and \r in here too.
// we'll work backwards to figure out how much will fit...
// this will give accurate per-line things even with changing width and wrapping
// while being generally efficient - we usually want to show the end of the list
// anyway; actually using the scrollback is a bit of an exceptional case.
// It could probably do this instead of on each redraw, on each resize or insertion.
// or at least cache between redraws until one of those invalidates it.
foreach_reverse(line; lines) {
int written = 0;
int brokenLineCount;
Idx[16] lineBreaksBuffer;
Idx[] lineBreaks = lineBreaksBuffer[];
comp_loop: foreach(cidx, component; line.components) {
auto towrite = component.text;
foreach(idx, dchar ch; towrite) {
if(written >= width) {
if(brokenLineCount == lineBreaks.length)
lineBreaks ~= Idx(cidx, idx);
else
lineBreaks[brokenLineCount] = Idx(cidx, idx);
brokenLineCount++;
written = 0;
}
if(ch == '\t')
written += 8; // FIXME
else
written++;
}
}
lineBreaks = lineBreaks[0 .. brokenLineCount];
foreach_reverse(lineBreak; lineBreaks) {
if(remaining == 1) {
firstPartial = true;
firstPartialStartIndex = lineBreak;
break;
} else {
remaining--;
}
if(remaining <= 0)
break;
}
remaining--;
start--;
howMany++;
if(remaining <= 0)
break;
}
// second pass: actually draw it
int linePos = remaining;
foreach(line; lines[start .. start + howMany]) {
int written = 0;
if(linePos < 0) {
linePos++;
continue;
}
terminal.moveTo(x, y + ((linePos >= 0) ? linePos : 0));
auto todo = line.components;
if(firstPartial) {
todo = todo[firstPartialStartIndex.cidx .. $];
}
foreach(ref component; todo) {
if(component.isRgb)
terminal.setTrueColor(component.colorRgb, component.backgroundRgb);
else
terminal.color(component.color, component.background);
auto towrite = component.text;
again:
if(linePos >= height)
break;
if(firstPartial) {
towrite = towrite[firstPartialStartIndex.idx .. $];
firstPartial = false;
}
foreach(idx, dchar ch; towrite) {
if(written >= width) {
clickRegions ~= ClickRegion(&component, terminal.cursorX, terminal.cursorY, written);
terminal.write(towrite[0 .. idx]);
towrite = towrite[idx .. $];
linePos++;
written = 0;
terminal.moveTo(x, y + linePos);
goto again;
}
if(ch == '\t')
written += 8; // FIXME
else
written++;
}
if(towrite.length) {
clickRegions ~= ClickRegion(&component, terminal.cursorX, terminal.cursorY, written);
terminal.write(towrite);
}
}
if(written < width) {
terminal.color(Color.DEFAULT, Color.DEFAULT);
foreach(i; written .. width)
terminal.write(" ");
}
linePos++;
if(linePos >= height)
break;
}
if(linePos < height) {
terminal.color(Color.DEFAULT, Color.DEFAULT);
foreach(i; linePos .. height) {
if(i >= 0 && i < height) {
terminal.moveTo(x, y + i);
foreach(w; 0 .. width)
terminal.write(" ");
}
}
}
}
private struct ClickRegion {
LineComponent* component;
int xStart;
int yStart;
int length;
}
private ClickRegion[] clickRegions;
/// Default event handling for this widget. Call this only after drawing it into a rectangle
/// and only if the event ought to be dispatched to it (which you determine however you want;
/// you could dispatch all events to it, or perhaps filter some out too)
///
/// Returns true if it should be redrawn
bool handleEvent(InputEvent e) {
final switch(e.type) {
case InputEvent.Type.LinkEvent:
// meh
break;
case InputEvent.Type.KeyboardEvent:
auto ev = e.keyboardEvent;
demandsAttention = false;
switch(ev.which) {
case KeyboardEvent.Key.UpArrow:
scrollUp();
return true;
case KeyboardEvent.Key.DownArrow:
scrollDown();
return true;
case KeyboardEvent.Key.PageUp:
scrollUp(height);
return true;
case KeyboardEvent.Key.PageDown:
scrollDown(height);
return true;
default:
// ignore
}
break;
case InputEvent.Type.MouseEvent:
auto ev = e.mouseEvent;
if(ev.x >= x && ev.x < x + width && ev.y >= y && ev.y < y + height) {
demandsAttention = false;
// it is inside our box, so do something with it
auto mx = ev.x - x;
auto my = ev.y - y;
if(ev.eventType == MouseEvent.Type.Pressed) {
if(ev.buttons & MouseEvent.Button.Left) {
foreach(region; clickRegions)
if(ev.x >= region.xStart && ev.x < region.xStart + region.length && ev.y == region.yStart)
if(region.component.onclick !is null)
return region.component.onclick();
}
if(ev.buttons & MouseEvent.Button.ScrollUp) {
scrollUp();
return true;
}
if(ev.buttons & MouseEvent.Button.ScrollDown) {
scrollDown();
return true;
}
}
} else {
// outside our area, free to ignore
}
break;
case InputEvent.Type.SizeChangedEvent:
// (size changed might be but it needs to be handled at a higher level really anyway)
// though it will return true because it probably needs redrawing anyway.
return true;
case InputEvent.Type.UserInterruptionEvent:
throw new UserInterruptionException();
case InputEvent.Type.HangupEvent:
throw new HangupException();
case InputEvent.Type.EndOfFileEvent:
// ignore, not relevant to this
break;
case InputEvent.Type.CharacterEvent:
case InputEvent.Type.NonCharacterKeyEvent:
// obsolete, ignore them until they are removed
break;
case InputEvent.Type.CustomEvent:
case InputEvent.Type.PasteEvent:
// ignored, not relevant to us
break;
}
return false;
}
}
class UserInterruptionException : Exception {
this() { super("Ctrl+C"); }
}
class HangupException : Exception {
this() { super("Hup"); }
}
/*
// more efficient scrolling
http://msdn.microsoft.com/en-us/library/windows/desktop/ms685113%28v=vs.85%29.aspx
// and the unix sequences
rxvt documentation:
use this to finish the input magic for that
For the keypad, use Shift to temporarily override Application-Keypad
setting use Num_Lock to toggle Application-Keypad setting if Num_Lock
is off, toggle Application-Keypad setting. Also note that values of
Home, End, Delete may have been compiled differently on your system.
Normal Shift Control Ctrl+Shift
Tab ^I ESC [ Z ^I ESC [ Z
BackSpace ^H ^? ^? ^?
Find ESC [ 1 ~ ESC [ 1 $ ESC [ 1 ^ ESC [ 1 @
Insert ESC [ 2 ~ paste ESC [ 2 ^ ESC [ 2 @
Execute ESC [ 3 ~ ESC [ 3 $ ESC [ 3 ^ ESC [ 3 @
Select ESC [ 4 ~ ESC [ 4 $ ESC [ 4 ^ ESC [ 4 @
Prior ESC [ 5 ~ scroll-up ESC [ 5 ^ ESC [ 5 @
Next ESC [ 6 ~ scroll-down ESC [ 6 ^ ESC [ 6 @
Home ESC [ 7 ~ ESC [ 7 $ ESC [ 7 ^ ESC [ 7 @
End ESC [ 8 ~ ESC [ 8 $ ESC [ 8 ^ ESC [ 8 @
Delete ESC [ 3 ~ ESC [ 3 $ ESC [ 3 ^ ESC [ 3 @
F1 ESC [ 11 ~ ESC [ 23 ~ ESC [ 11 ^ ESC [ 23 ^
F2 ESC [ 12 ~ ESC [ 24 ~ ESC [ 12 ^ ESC [ 24 ^
F3 ESC [ 13 ~ ESC [ 25 ~ ESC [ 13 ^ ESC [ 25 ^
F4 ESC [ 14 ~ ESC [ 26 ~ ESC [ 14 ^ ESC [ 26 ^
F5 ESC [ 15 ~ ESC [ 28 ~ ESC [ 15 ^ ESC [ 28 ^
F6 ESC [ 17 ~ ESC [ 29 ~ ESC [ 17 ^ ESC [ 29 ^
F7 ESC [ 18 ~ ESC [ 31 ~ ESC [ 18 ^ ESC [ 31 ^
F8 ESC [ 19 ~ ESC [ 32 ~ ESC [ 19 ^ ESC [ 32 ^
F9 ESC [ 20 ~ ESC [ 33 ~ ESC [ 20 ^ ESC [ 33 ^
F10 ESC [ 21 ~ ESC [ 34 ~ ESC [ 21 ^ ESC [ 34 ^
F11 ESC [ 23 ~ ESC [ 23 $ ESC [ 23 ^ ESC [ 23 @
F12 ESC [ 24 ~ ESC [ 24 $ ESC [ 24 ^ ESC [ 24 @
F13 ESC [ 25 ~ ESC [ 25 $ ESC [ 25 ^ ESC [ 25 @
F14 ESC [ 26 ~ ESC [ 26 $ ESC [ 26 ^ ESC [ 26 @
F15 (Help) ESC [ 28 ~ ESC [ 28 $ ESC [ 28 ^ ESC [ 28 @
F16 (Menu) ESC [ 29 ~ ESC [ 29 $ ESC [ 29 ^ ESC [ 29 @
F17 ESC [ 31 ~ ESC [ 31 $ ESC [ 31 ^ ESC [ 31 @
F18 ESC [ 32 ~ ESC [ 32 $ ESC [ 32 ^ ESC [ 32 @
F19 ESC [ 33 ~ ESC [ 33 $ ESC [ 33 ^ ESC [ 33 @
F20 ESC [ 34 ~ ESC [ 34 $ ESC [ 34 ^ ESC [ 34 @
Application
Up ESC [ A ESC [ a ESC O a ESC O A
Down ESC [ B ESC [ b ESC O b ESC O B
Right ESC [ C ESC [ c ESC O c ESC O C
Left ESC [ D ESC [ d ESC O d ESC O D
KP_Enter ^M ESC O M
KP_F1 ESC O P ESC O P
KP_F2 ESC O Q ESC O Q
KP_F3 ESC O R ESC O R
KP_F4 ESC O S ESC O S
XK_KP_Multiply * ESC O j
XK_KP_Add + ESC O k
XK_KP_Separator , ESC O l
XK_KP_Subtract - ESC O m
XK_KP_Decimal . ESC O n
XK_KP_Divide / ESC O o
XK_KP_0 0 ESC O p
XK_KP_1 1 ESC O q
XK_KP_2 2 ESC O r
XK_KP_3 3 ESC O s
XK_KP_4 4 ESC O t
XK_KP_5 5 ESC O u
XK_KP_6 6 ESC O v
XK_KP_7 7 ESC O w
XK_KP_8 8 ESC O x
XK_KP_9 9 ESC O y
*/
version(Demo_kbhit)
void main() {
auto terminal = Terminal(ConsoleOutputType.linear);
auto input = RealTimeConsoleInput(&terminal, ConsoleInputFlags.raw);
int a;
char ch = '.';
while(a < 1000) {
a++;
if(a % terminal.width == 0) {
terminal.write("\r");
if(ch == '.')
ch = ' ';
else
ch = '.';
}
if(input.kbhit())
terminal.write(input.getch());
else
terminal.write(ch);
terminal.flush();
import core.thread;
Thread.sleep(50.msecs);
}
}
/*
The Xterm palette progression is:
[0, 95, 135, 175, 215, 255]
So if I take the color and subtract 55, then div 40, I get
it into one of these areas. If I add 20, I get a reasonable
rounding.
*/
ubyte colorToXTermPaletteIndex(RGB color) {
/*
Here, I will round off to the color ramp or the
greyscale. I will NOT use the bottom 16 colors because
there's duplicates (or very close enough) to them in here
*/
if(color.r == color.g && color.g == color.b) {
// grey - find one of them:
if(color.r == 0) return 0;
// meh don't need those two, let's simplify branche
//if(color.r == 0xc0) return 7;
//if(color.r == 0x80) return 8;
// it isn't == 255 because it wants to catch anything
// that would wrap the simple algorithm below back to 0.
if(color.r >= 248) return 15;
// there's greys in the color ramp too, but these
// are all close enough as-is, no need to complicate
// algorithm for approximation anyway
return cast(ubyte) (232 + ((color.r - 8) / 10));
}
// if it isn't grey, it is color
// the ramp goes blue, green, red, with 6 of each,
// so just multiplying will give something good enough
// will give something between 0 and 5, with some rounding
auto r = (cast(int) color.r - 35) / 40;
auto g = (cast(int) color.g - 35) / 40;
auto b = (cast(int) color.b - 35) / 40;
return cast(ubyte) (16 + b + g*6 + r*36);
}
/++
Represents a 24-bit color.
$(TIP You can convert these to and from [arsd.color.Color] using
`.tupleof`:
---
RGB rgb;
Color c = Color(rgb.tupleof);
---
)
+/
struct RGB {
ubyte r; ///
ubyte g; ///
ubyte b; ///
// terminal can't actually use this but I want the value
// there for assignment to an arsd.color.Color
private ubyte a = 255;
}
// This is an approximation too for a few entries, but a very close one.
RGB xtermPaletteIndexToColor(int paletteIdx) {
RGB color;
if(paletteIdx < 16) {
if(paletteIdx == 7)
return RGB(0xc0, 0xc0, 0xc0);
else if(paletteIdx == 8)
return RGB(0x80, 0x80, 0x80);
color.r = (paletteIdx & 0b001) ? ((paletteIdx & 0b1000) ? 0xff : 0x80) : 0x00;
color.g = (paletteIdx & 0b010) ? ((paletteIdx & 0b1000) ? 0xff : 0x80) : 0x00;
color.b = (paletteIdx & 0b100) ? ((paletteIdx & 0b1000) ? 0xff : 0x80) : 0x00;
} else if(paletteIdx < 232) {
// color ramp, 6x6x6 cube
color.r = cast(ubyte) ((paletteIdx - 16) / 36 * 40 + 55);
color.g = cast(ubyte) (((paletteIdx - 16) % 36) / 6 * 40 + 55);
color.b = cast(ubyte) ((paletteIdx - 16) % 6 * 40 + 55);
if(color.r == 55) color.r = 0;
if(color.g == 55) color.g = 0;
if(color.b == 55) color.b = 0;
} else {
// greyscale ramp, from 0x8 to 0xee
color.r = cast(ubyte) (8 + (paletteIdx - 232) * 10);
color.g = color.r;
color.b = color.g;
}
return color;
}
int approximate16Color(RGB color) {
int c;
c |= color.r > 64 ? RED_BIT : 0;
c |= color.g > 64 ? GREEN_BIT : 0;
c |= color.b > 64 ? BLUE_BIT : 0;
c |= (((color.r + color.g + color.b) / 3) > 80) ? Bright : 0;
return c;
}
version(TerminalDirectToEmulator) {
/++
Indicates the TerminalDirectToEmulator features
are present. You can check this with `static if`.
$(WARNING
This will cause the [Terminal] constructor to spawn a GUI thread with [arsd.minigui]/[arsd.simpledisplay].
This means you can NOT use those libraries in your
own thing without using the [arsd.simpledisplay.runInGuiThread] helper since otherwise the main thread is inaccessible, since having two different threads creating event loops or windows is undefined behavior with those libraries.
)
+/
enum IntegratedEmulator = true;
/++
Allows customization of the integrated emulator window.
You may change the default colors, font, and other aspects
of GUI integration.
Test for its presence before using with `static if(arsd.terminal.IntegratedEmulator)`.
All settings here must be set BEFORE you construct any [Terminal] instances.
History:
Added March 7, 2020.
+/
struct IntegratedTerminalEmulatorConfiguration {
/// Note that all Colors in here are 24 bit colors.
alias Color = arsd.color.Color;
/// Default foreground color of the terminal.
Color defaultForeground = Color.black;
/// Default background color of the terminal.
Color defaultBackground = Color.white;
/++
Font to use in the window. It should be a monospace font,
and your selection may not actually be used if not available on
the user's system, in which case it will fallback to one.
History:
Implemented March 26, 2020
+/
string fontName;
/// ditto
int fontSize = 14;
/++
Requested initial terminal size in character cells. You may not actually get exactly this.
+/
int initialWidth = 80;
/// ditto
int initialHeight = 40;
/++
If `true`, the window will close automatically when the main thread exits.
Otherwise, the window will remain open so the user can work with output before
it disappears.
History:
Added April 10, 2020 (v7.2.0)
+/
bool closeOnExit = false;
/++
Gives you a chance to modify the window as it is constructed. Intended
to let you add custom menu options.
---
import arsd.terminal;
integratedTerminalEmulatorConfiguration.menuExtensionsConstructor = (TerminalEmulatorWindow window) {
import arsd.minigui; // for the menu related UDAs
class Commands {
@menu("Help") {
void Topics() {
auto window = new Window(); // make a help window of some sort
window.show();
}
@separator
void About() {
messageBox("My Application v 1.0");
}
}
}
window.setMenuAndToolbarFromAnnotatedCode(new Commands());
};
---
History:
Added March 29, 2020. Included in release v7.1.0.
+/
void delegate(TerminalEmulatorWindow) menuExtensionsConstructor;
/++
Set this to true if you want [Terminal] to fallback to the user's
existing native terminal in the event that creating the custom terminal
is impossible for whatever reason.
If your application must have all advanced features, set this to `false`.
Otherwise, be sure you handle the absence of advanced features in your
application by checking methods like [Terminal.inlineImagesSupported],
etc., and only use things you can gracefully degrade without.
If this is set to false, `Terminal`'s constructor will throw if the gui fails
instead of carrying on with the stdout terminal (if possible).
History:
Added June 28, 2020. Included in release v8.1.0.
+/
bool fallbackToDegradedTerminal = true;
}
/+
status bar should probably tell
if scroll lock is on...
+/
/// You can set this in a static module constructor. (`shared static this() {}`)
__gshared IntegratedTerminalEmulatorConfiguration integratedTerminalEmulatorConfiguration;
import arsd.terminalemulator;
import arsd.minigui;
/++
Represents the window that the library pops up for you.
+/
final class TerminalEmulatorWindow : MainWindow {
/++
Gives access to the underlying terminal emulation object.
+/
TerminalEmulator terminalEmulator() {
return tew.terminalEmulator;
}
private TerminalEmulatorWindow parent;
private TerminalEmulatorWindow[] children;
private void childClosing(TerminalEmulatorWindow t) {
foreach(idx, c; children)
if(c is t)
children = children[0 .. idx] ~ children[idx + 1 .. $];
}
private void registerChild(TerminalEmulatorWindow t) {
children ~= t;
}
private this(Terminal* term, TerminalEmulatorWindow parent) {
this.parent = parent;
scope(success) if(parent) parent.registerChild(this);
super("Terminal Application", integratedTerminalEmulatorConfiguration.initialWidth * integratedTerminalEmulatorConfiguration.fontSize / 2, integratedTerminalEmulatorConfiguration.initialHeight * integratedTerminalEmulatorConfiguration.fontSize);
smw = new ScrollMessageWidget(this);
tew = new TerminalEmulatorWidget(term, smw);
smw.addEventListener("scroll", () {
tew.terminalEmulator.scrollbackTo(smw.position.x, smw.position.y + tew.terminalEmulator.height);
redraw();
});
smw.setTotalArea(1, 1);
setMenuAndToolbarFromAnnotatedCode(this);
if(integratedTerminalEmulatorConfiguration.menuExtensionsConstructor)
integratedTerminalEmulatorConfiguration.menuExtensionsConstructor(this);
}
TerminalEmulator.TerminalCell[] delegate(TerminalEmulator.TerminalCell[] i) parentFilter;
private void addScrollbackLineFromParent(TerminalEmulator.TerminalCell[] lineIn) {
if(parentFilter is null)
return;
auto line = parentFilter(lineIn);
if(line is null) return;
if(tew && tew.terminalEmulator) {
bool atBottom = smw.verticalScrollBar.atEnd && smw.horizontalScrollBar.atStart;
tew.terminalEmulator.addScrollbackLine(line);
tew.terminalEmulator.notifyScrollbackAdded();
if(atBottom) {
tew.terminalEmulator.notifyScrollbarPosition(0, int.max);
tew.terminalEmulator.scrollbackTo(0, int.max);
tew.redraw();
}
}
}
private TerminalEmulatorWidget tew;
private ScrollMessageWidget smw;
@menu("&History") {
@tip("Saves the currently visible content to a file")
void Save() {
getSaveFileName((string name) {
if(name.length) {
try
tew.terminalEmulator.writeScrollbackToFile(name);
catch(Exception e)
messageBox("Save failed: " ~ e.msg);
}
});
}
// FIXME
version(FIXME)
void Save_HTML() {
}
@separator
/*
void Find() {
// FIXME
// jump to the previous instance in the scrollback
}
*/
void Filter() {
// open a new window that just shows items that pass the filter
static struct FilterParams {
string searchTerm;
bool caseSensitive;
}
dialog((FilterParams p) {
auto nw = new TerminalEmulatorWindow(null, this);
nw.parentFilter = (TerminalEmulator.TerminalCell[] line) {
import std.algorithm;
import std.uni;
// omg autodecoding being kinda useful for once LOL
if(line.map!(c => c.hasNonCharacterData ? dchar(0) : (p.caseSensitive ? c.ch : c.ch.toLower)).
canFind(p.searchTerm))
{
// I might highlight the match too, but meh for now
return line;
}
return null;
};
foreach(line; tew.terminalEmulator.sbb[0 .. $]) {
if(auto l = nw.parentFilter(line))
nw.tew.terminalEmulator.addScrollbackLine(l);
}
nw.tew.terminalEmulator.toggleScrollLock();
nw.tew.terminalEmulator.drawScrollback();
nw.title = "Filter Display";
nw.show();
});
}
@separator
void Clear() {
tew.terminalEmulator.clearScrollbackHistory();
tew.terminalEmulator.cls();
tew.terminalEmulator.moveCursor(0, 0);
if(tew.term) {
tew.term.windowSizeChanged = true;
tew.terminalEmulator.outgoingSignal.notify();
}
tew.redraw();
}
@separator
void Exit() @accelerator("Alt+F4") @hotkey('x') {
this.close();
}
}
@menu("&Edit") {
void Copy() {
tew.terminalEmulator.copyToClipboard(tew.terminalEmulator.getSelectedText());
}
void Paste() {
tew.terminalEmulator.pasteFromClipboard(&tew.terminalEmulator.sendPasteData);
}
}
}
private class InputEventInternal {
const(ubyte)[] data;
this(in ubyte[] data) {
this.data = data;
}
}
private class TerminalEmulatorWidget : Widget {
Menu ctx;
override Menu contextMenu(int x, int y) {
if(ctx is null) {
ctx = new Menu("");
ctx.addItem(new MenuItem(new Action("Copy", 0, {
terminalEmulator.copyToClipboard(terminalEmulator.getSelectedText());
})));
ctx.addItem(new MenuItem(new Action("Paste", 0, {
terminalEmulator.pasteFromClipboard(&terminalEmulator.sendPasteData);
})));
ctx.addItem(new MenuItem(new Action("Toggle Scroll Lock", 0, {
terminalEmulator.toggleScrollLock();
})));
}
return ctx;
}
this(Terminal* term, ScrollMessageWidget parent) {
this.smw = parent;
this.term = term;
terminalEmulator = new TerminalEmulatorInsideWidget(this);
super(parent);
this.parentWindow.win.onClosing = {
if(term)
term.hangedUp = true;
if(auto wi = cast(TerminalEmulatorWindow) this.parentWindow) {
if(wi.parent)
wi.parent.childClosing(wi);
}
// try to get it to terminate slightly more forcibly too, if possible
if(sigIntExtension)
sigIntExtension();
terminalEmulator.outgoingSignal.notify();
terminalEmulator.incomingSignal.notify();
};
this.parentWindow.win.addEventListener((InputEventInternal ie) {
terminalEmulator.sendRawInput(ie.data);
this.redraw();
terminalEmulator.incomingSignal.notify();
});
}
ScrollMessageWidget smw;
Terminal* term;
void sendRawInput(const(ubyte)[] data) {
if(this.parentWindow) {
this.parentWindow.win.postEvent(new InputEventInternal(data));
terminalEmulator.incomingSignal.wait(); // blocking write basically, wait until the TE confirms the receipt of it
}
}
TerminalEmulatorInsideWidget terminalEmulator;
override void registerMovement() {
super.registerMovement();
terminalEmulator.resized(width, height);
}
override void focus() {
super.focus();
terminalEmulator.attentionReceived();
}
override MouseCursor cursor() { return GenericCursor.Text; }
override void erase(WidgetPainter painter) { /* intentionally blank, paint does it better */ }
override void paint(WidgetPainter painter) {
bool forceRedraw = false;
if(terminalEmulator.invalidateAll || terminalEmulator.clearScreenRequested) {
auto clearColor = terminalEmulator.defaultBackground;
painter.outlineColor = clearColor;
painter.fillColor = clearColor;
painter.drawRectangle(Point(0, 0), this.width, this.height);
terminalEmulator.clearScreenRequested = false;
forceRedraw = true;
}
terminalEmulator.redrawPainter(painter, forceRedraw);
}
}
private class TerminalEmulatorInsideWidget : TerminalEmulator {
private ScrollbackBuffer sbb() { return scrollbackBuffer; }
void resized(int w, int h) {
this.resizeTerminal(w / fontWidth, h / fontHeight);
if(widget && widget.smw) {
widget.smw.setViewableArea(this.width, this.height);
widget.smw.setPageSize(this.width / 2, this.height / 2);
}
clearScreenRequested = true;
if(widget && widget.term)
widget.term.windowSizeChanged = true;
outgoingSignal.notify();
redraw();
}
override void addScrollbackLine(TerminalCell[] line) {
super.addScrollbackLine(line);
if(widget)
if(auto p = cast(TerminalEmulatorWindow) widget.parentWindow) {
foreach(child; p.children)
child.addScrollbackLineFromParent(line);
}
}
override void notifyScrollbackAdded() {
widget.smw.setTotalArea(this.scrollbackWidth > this.width ? this.scrollbackWidth : this.width, this.scrollbackLength > this.height ? this.scrollbackLength : this.height);
}
override void notifyScrollbarPosition(int x, int y) {
widget.smw.setPosition(x, y);
widget.redraw();
}
override void notifyScrollbarRelevant(bool isRelevantHorizontally, bool isRelevantVertically) {
if(isRelevantVertically)
notifyScrollbackAdded();
else
widget.smw.setTotalArea(width, height);
}
override @property public int cursorX() { return super.cursorX; }
override @property public int cursorY() { return super.cursorY; }
protected override void changeCursorStyle(CursorStyle s) { }
string currentTitle;
protected override void changeWindowTitle(string t) {
if(widget && widget.parentWindow && t.length) {
widget.parentWindow.win.title = t;
currentTitle = t;
}
}
protected override void changeWindowIcon(IndexedImage t) {
if(widget && widget.parentWindow && t)
widget.parentWindow.win.icon = t;
}
protected override void changeIconTitle(string) {}
protected override void changeTextAttributes(TextAttributes) {}
protected override void soundBell() {
static if(UsingSimpledisplayX11)
XBell(XDisplayConnection.get(), 50);
}
protected override void demandAttention() {
if(widget && widget.parentWindow)
widget.parentWindow.win.requestAttention();
}
protected override void copyToClipboard(string text) {
setClipboardText(widget.parentWindow.win, text);
}
override int maxScrollbackLength() const {
return int.max; // no scrollback limit for custom programs
}
protected override void pasteFromClipboard(void delegate(in char[]) dg) {
static if(UsingSimpledisplayX11)
getPrimarySelection(widget.parentWindow.win, dg);
else
getClipboardText(widget.parentWindow.win, (in char[] dataIn) {
char[] data;
// change Windows \r\n to plain \n
foreach(char ch; dataIn)
if(ch != 13)
data ~= ch;
dg(data);
});
}
protected override void copyToPrimary(string text) {
static if(UsingSimpledisplayX11)
setPrimarySelection(widget.parentWindow.win, text);
else
{}
}
protected override void pasteFromPrimary(void delegate(in char[]) dg) {
static if(UsingSimpledisplayX11)
getPrimarySelection(widget.parentWindow.win, dg);
}
override void requestExit() {
widget.parentWindow.close();
}
bool echo = false;
override void sendRawInput(in ubyte[] data) {
void send(in ubyte[] data) {
if(data.length == 0)
return;
super.sendRawInput(data);
if(echo)
sendToApplication(data);
}
// need to echo, translate 10 to 13/10 cr-lf
size_t last = 0;
const ubyte[2] crlf = [13, 10];
foreach(idx, ch; data) {
if(ch == 10) {
send(data[last .. idx]);
send(crlf[]);
last = idx + 1;
}
}
if(last < data.length)
send(data[last .. $]);
}
bool focused;
TerminalEmulatorWidget widget;
import arsd.simpledisplay;
import arsd.color;
import core.sync.semaphore;
alias ModifierState = arsd.simpledisplay.ModifierState;
alias Color = arsd.color.Color;
alias fromHsl = arsd.color.fromHsl;
const(ubyte)[] pendingForApplication;
Semaphore outgoingSignal;
Semaphore incomingSignal;
override void sendToApplication(scope const(void)[] what) {
synchronized(this) {
pendingForApplication ~= cast(const(ubyte)[]) what;
}
outgoingSignal.notify();
}
@property int width() { return screenWidth; }
@property int height() { return screenHeight; }
@property bool invalidateAll() { return super.invalidateAll; }
private this(TerminalEmulatorWidget widget) {
this.outgoingSignal = new Semaphore();
this.incomingSignal = new Semaphore();
this.widget = widget;
if(integratedTerminalEmulatorConfiguration.fontName.length) {
this.font = new OperatingSystemFont(integratedTerminalEmulatorConfiguration.fontName, integratedTerminalEmulatorConfiguration.fontSize, FontWeight.medium);
this.fontWidth = font.averageWidth;
this.fontHeight = font.height;
}
if(this.font is null || this.font.isNull)
loadDefaultFont(integratedTerminalEmulatorConfiguration.fontSize);
super(integratedTerminalEmulatorConfiguration.initialWidth, integratedTerminalEmulatorConfiguration.initialHeight);
defaultForeground = integratedTerminalEmulatorConfiguration.defaultForeground;
defaultBackground = integratedTerminalEmulatorConfiguration.defaultBackground;
bool skipNextChar = false;
widget.addEventListener("mousedown", (Event ev) {
int termX = (ev.clientX - paddingLeft) / fontWidth;
int termY = (ev.clientY - paddingTop) / fontHeight;
if((!mouseButtonTracking || (ev.state & ModifierState.shift)) && ev.button == MouseButton.right)
widget.showContextMenu(ev.clientX, ev.clientY);
else
if(sendMouseInputToApplication(termX, termY,
arsd.terminalemulator.MouseEventType.buttonPressed,
cast(arsd.terminalemulator.MouseButton) ev.button,
(ev.state & ModifierState.shift) ? true : false,
(ev.state & ModifierState.ctrl) ? true : false,
(ev.state & ModifierState.alt) ? true : false
))
redraw();
});
widget.addEventListener("mouseup", (Event ev) {
int termX = (ev.clientX - paddingLeft) / fontWidth;
int termY = (ev.clientY - paddingTop) / fontHeight;
if(sendMouseInputToApplication(termX, termY,
arsd.terminalemulator.MouseEventType.buttonReleased,
cast(arsd.terminalemulator.MouseButton) ev.button,
(ev.state & ModifierState.shift) ? true : false,
(ev.state & ModifierState.ctrl) ? true : false,
(ev.state & ModifierState.alt) ? true : false
))
redraw();
});
widget.addEventListener("mousemove", (Event ev) {
int termX = (ev.clientX - paddingLeft) / fontWidth;
int termY = (ev.clientY - paddingTop) / fontHeight;
if(sendMouseInputToApplication(termX, termY,
arsd.terminalemulator.MouseEventType.motion,
cast(arsd.terminalemulator.MouseButton) ev.button,
(ev.state & ModifierState.shift) ? true : false,
(ev.state & ModifierState.ctrl) ? true : false,
(ev.state & ModifierState.alt) ? true : false
))
redraw();
});
widget.addEventListener("keydown", (Event ev) {
if(ev.key == Key.C && (ev.state & ModifierState.shift) && (ev.state & ModifierState.ctrl)) {
// ctrl+c is cancel so ctrl+shift+c ends up doing copy.
copyToClipboard(getSelectedText());
skipNextChar = true;
return;
}
if(ev.key == Key.Insert && (ev.state & ModifierState.ctrl)) {
copyToClipboard(getSelectedText());
return;
}
static string magic() {
string code;
foreach(member; __traits(allMembers, TerminalKey))
if(member != "Escape")
code ~= "case Key." ~ member ~ ": if(sendKeyToApplication(TerminalKey." ~ member ~ "
, (ev.state & ModifierState.shift)?true:false
, (ev.state & ModifierState.alt)?true:false
, (ev.state & ModifierState.ctrl)?true:false
, (ev.state & ModifierState.windows)?true:false
)) redraw(); break;";
return code;
}
switch(ev.key) {
mixin(magic());
default:
// keep going, not special
}
return; // the character event handler will do others
});
widget.addEventListener("char", (Event ev) {
dchar c = ev.character;
if(skipNextChar) {
skipNextChar = false;
return;
}
endScrollback();
char[4] str;
import std.utf;
if(c == '\n') c = '\r'; // terminal seem to expect enter to send 13 instead of 10
auto data = str[0 .. encode(str, c)];
if(c == 0x1c) /* ctrl+\, force quit */ {
version(Posix) {
import core.sys.posix.signal;
pthread_kill(widget.term.threadId, SIGQUIT); // or SIGKILL even?
assert(0);
//import core.sys.posix.pthread;
//pthread_cancel(widget.term.threadId);
//widget.term = null;
} else version(Windows) {
import core.sys.windows.windows;
auto hnd = OpenProcess(SYNCHRONIZE | PROCESS_TERMINATE, TRUE, GetCurrentProcessId());
TerminateProcess(hnd, -1);
assert(0);
}
} else if(c == 3) /* ctrl+c, interrupt */ {
if(sigIntExtension)
sigIntExtension();
if(widget && widget.term) {
widget.term.interrupted = true;
outgoingSignal.notify();
}
} else if(c != 127) {
// on X11, the delete key can send a 127 character too, but that shouldn't be sent to the terminal since xterm shoots \033[3~ instead, which we handle in the KeyEvent handler.
sendToApplication(data);
}
});
}
bool clearScreenRequested = true;
void redraw() {
if(widget.parentWindow is null || widget.parentWindow.win is null || widget.parentWindow.win.closed)
return;
widget.redraw();
}
mixin SdpyDraw;
}
} else {
///
enum IntegratedEmulator = false;
}
/*
void main() {
auto terminal = Terminal(ConsoleOutputType.linear);
terminal.setTrueColor(RGB(255, 0, 255), RGB(255, 255, 255));
terminal.writeln("Hello, world!");
}
*/
/*
ONLY SUPPORTED ON MY TERMINAL EMULATOR IN GENERAL
bracketed section can collapse and scroll independently in the TE. may also pop out into a window (possibly with a comparison window)
hyperlink can either just indicate something to the TE to handle externally
OR
indicate a certain input sequence be triggered when it is clicked (prolly wrapped up as a paste event). this MAY also be a custom event.
internally it can set two bits: one indicates it is a hyperlink, the other just flips each use to separate consecutive sequences.
it might require the content of the paste event to be the visible word but it would bne kinda cool if it could be some secret thing elsewhere.
I could spread a unique id number across bits, one bit per char so the memory isn't too bad.
so it would set a number and a word. this is sent back to the application to handle internally.
1) turn on special input
2) turn off special input
3) special input sends a paste event with a number and the text
4) to make a link, you write out the begin sequence, the text, and the end sequence. including the magic number somewhere.
magic number is allowed to have one bit per char. the terminal discards anything else. terminal.d api will enforce.
if magic number is zero, it is not sent in the paste event. maybe.
or if it is like 255, it is handled as a url and opened externally
tho tbh a url could just be detected by regex pattern
NOTE: if your program requests mouse input, the TE does not process it! Thus the user will have to shift+click for it.
mode 3004 for bracketed hyperlink
hyperlink sequence: \033[?220hnum;text\033[?220l~
*/
|
D
|
/Users/kamil.pyc/Documents/testFastlane/FastlaneTest/build/Build/Intermediates/CodeCoverage/Intermediates/FastlaneTest.build/Debug-iphonesimulator/FastlaneTestUITests.build/Objects-normal/x86_64/FastlaneTestUITests.o : /Users/kamil.pyc/Documents/testFastlane/FastlaneTest/FastlaneTestUITests/FastlaneTestUITests.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/XCTest.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIRemote.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIKeyboardKeys.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIElementQuery.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUICoordinate.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIDevice.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIElementTypeQueryProvider.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIElementTypes.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIElementAttributes.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIElement.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIApplication.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestSuiteRun.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestSuite.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestProbe.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestObservation.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestObservationCenter.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestObserver.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestLog.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestRun.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestCaseRun.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestCase+AsynchronousTesting.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestCase.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestAssertionsImpl.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestAssertions.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCAbstractTest.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestErrors.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestDefines.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTest.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule
/Users/kamil.pyc/Documents/testFastlane/FastlaneTest/build/Build/Intermediates/CodeCoverage/Intermediates/FastlaneTest.build/Debug-iphonesimulator/FastlaneTestUITests.build/Objects-normal/x86_64/FastlaneTestUITests~partial.swiftmodule : /Users/kamil.pyc/Documents/testFastlane/FastlaneTest/FastlaneTestUITests/FastlaneTestUITests.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/XCTest.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIRemote.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIKeyboardKeys.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIElementQuery.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUICoordinate.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIDevice.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIElementTypeQueryProvider.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIElementTypes.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIElementAttributes.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIElement.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIApplication.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestSuiteRun.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestSuite.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestProbe.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestObservation.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestObservationCenter.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestObserver.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestLog.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestRun.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestCaseRun.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestCase+AsynchronousTesting.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestCase.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestAssertionsImpl.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestAssertions.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCAbstractTest.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestErrors.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestDefines.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTest.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule
/Users/kamil.pyc/Documents/testFastlane/FastlaneTest/build/Build/Intermediates/CodeCoverage/Intermediates/FastlaneTest.build/Debug-iphonesimulator/FastlaneTestUITests.build/Objects-normal/x86_64/FastlaneTestUITests~partial.swiftdoc : /Users/kamil.pyc/Documents/testFastlane/FastlaneTest/FastlaneTestUITests/FastlaneTestUITests.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/XCTest.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIRemote.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIKeyboardKeys.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIElementQuery.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUICoordinate.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIDevice.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIElementTypeQueryProvider.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIElementTypes.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIElementAttributes.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIElement.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCUIApplication.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestSuiteRun.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestSuite.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestProbe.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestObservation.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestObservationCenter.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestObserver.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestLog.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestRun.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestCaseRun.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestCase+AsynchronousTesting.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestCase.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestAssertionsImpl.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestAssertions.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCAbstractTest.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestErrors.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTestDefines.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTest.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule
|
D
|
// { dg-additional-options "-mavx2" { target avx2_runtime } }
// { dg-do run { target { avx2_runtime || vect_sizes_32B_16B } } }
// { dg-skip-if "needs gcc/config.d" { ! d_runtime } }
import core.simd;
void test6a()
{
// stack occasionally misaligned
float f = 0;
long4 v;
assert((cast(size_t)&v) % 32 == 0);
v += 1;
}
void test6b()
{
struct S {long4 v;}
S s;
assert((cast(size_t)&s) % 32 == 0);
}
void main()
{
test6a();
test6b();
}
|
D
|
/+
+ Copyright 2022 – 2023 Aya Partridge
+ Copyright 2018 - 2022 Michael D. Parker
+ Distributed under the Boost Software License, Version 1.0.
+ (See accompanying file LICENSE_1_0.txt or copy at
+ http://www.boost.org/LICENSE_1_0.txt)
+/
module sdl.cpuinfo;
import bindbc.sdl.config;
import bindbc.sdl.codegen;
import sdl.stdinc: SDL_bool;
enum SDL_CACHELINE_SIZE = 128;
mixin(joinFnBinds((){
string[][] ret;
ret ~= makeFnBinds([
[q{int}, q{SDL_GetCPUCount}, q{}],
[q{int}, q{SDL_GetCPUCacheLineSize}, q{}],
[q{SDL_bool}, q{SDL_HasRDTSC}, q{}],
[q{SDL_bool}, q{SDL_HasAltiVec}, q{}],
[q{SDL_bool}, q{SDL_HasMMX}, q{}],
[q{SDL_bool}, q{SDL_Has3DNow}, q{}],
[q{SDL_bool}, q{SDL_HasSSE}, q{}],
[q{SDL_bool}, q{SDL_HasSSE2}, q{}],
[q{SDL_bool}, q{SDL_HasSSE3}, q{}],
[q{SDL_bool}, q{SDL_HasSSE41}, q{}],
[q{SDL_bool}, q{SDL_HasSSE42}, q{}],
]);
static if(sdlSupport >= SDLSupport.v2_0_1){
ret ~= makeFnBinds([
[q{int}, q{SDL_GetSystemRAM}, q{}],
]);
}
static if(sdlSupport >= SDLSupport.v2_0_2){
ret ~= makeFnBinds([
[q{SDL_bool}, q{SDL_HasAVX}, q{}],
]);
}
static if(sdlSupport >= SDLSupport.v2_0_4){
ret ~= makeFnBinds([
[q{SDL_bool}, q{SDL_HasAVX2}, q{}],
]);
}
static if(sdlSupport >= SDLSupport.v2_0_6){
ret ~= makeFnBinds([
[q{SDL_bool}, q{SDL_HasNEON}, q{}],
]);
}
static if(sdlSupport >= SDLSupport.v2_0_9){
ret ~= makeFnBinds([
[q{SDL_bool}, q{SDL_HasAVX512F}, q{}],
]);
}
static if(sdlSupport >= SDLSupport.v2_0_10){
ret ~= makeFnBinds([
[q{size_t}, q{SDL_SIMDGetAlignment}, q{}],
[q{void*}, q{SDL_SIMDAlloc}, q{const(size_t) len}],
[q{void}, q{SDL_SIMDFree}, q{void*}],
]);
}
static if(sdlSupport >= SDLSupport.v2_0_12){
ret ~= makeFnBinds([
[q{SDL_bool}, q{SDL_HasARMSIMD}, q{}],
]);
}
static if(sdlSupport >= SDLSupport.v2_0_14){
ret ~= makeFnBinds([
[q{void*}, q{SDL_SIMDRealloc}, q{void* mem, const(size_t) len}],
]);
}
static if(sdlSupport >= SDLSupport.v2_24){
ret ~= makeFnBinds([
[q{SDL_bool}, q{SDL_HasLSX}, q{}],
[q{SDL_bool}, q{SDL_HasLASX}, q{}],
]);
}
return ret;
}()));
|
D
|
/* -*- D -*-
*
* Execution flow trace with arguments
*
* Activate tracing between
* ::nsf::configure dtrace on
* and
* ::nsf::configure dtrace off
*
* Since this D script accesses the C data structures it is sensitive
* to the representation sizes of the data structures (e.g. pointers).
* Make sure to call the script with the appropriate architecture flag
* on Mac OS X; on SunOS, there is apparently a -32 or -64 flag.
*
* Example:
*
* sudo dtrace -arch x86_64 -x bufsize=20m -F -s dtrace/execution-flow-args.d \
* -c "./nxsh dtrace/sample.tcl"
*
* -gustaf neumann
*/
enum {maxstrlen = 50};
/*
* Needed data structures to access the content of Tcl_Objs.
*/
typedef struct Tcl_Obj Tcl_Obj;
typedef struct Tcl_ObjType {
char *name;
void *freeIntRepProc;
void *dupIntRepProc;
void *updateStringProc;
void *setFromAnyProc;
} Tcl_ObjType;
struct Tcl_Obj {
int refCount;
char *bytes;
int length;
Tcl_ObjType *typePtr;
union {
long longValue;
double doubleValue;
void *otherValuePtr;
int64_t wideValue;
struct {
void *ptr1;
void *ptr2;
} twoPtrValue;
struct {
void *ptr;
unsigned long value;
} ptrAndLongRep;
} internalRep;
};
/*
* Handling "nsf::configure dtrace on|off".
*/
nsf*:::configure-probe /!self->tracing && copyinstr(arg0) == "dtrace" / {
self->tracing = (arg1 && copyinstr(arg1) == "on") ? 1 : 0;
}
nsf*:::configure-probe /self->tracing && copyinstr(arg0) == "dtrace" / {
self->tracing = (arg1 && copyinstr(arg1) == "off") ? 0 : 1;
}
/*
* Output object, class, method, number of arguments and first two
* arguments upon method invocation.
*/
nsf*:::method-entry /self->tracing/ {
this->objv = arg3 ? ((Tcl_Obj**)copyin((user_addr_t)((Tcl_Obj**)arg4),
sizeof(Tcl_Obj*) * arg3)) : NULL;
this->i = 0;
this->o = arg3 > this->i && *(this->objv + this->i) ?
(Tcl_Obj*)copyin((user_addr_t)*(this->objv + this->i), sizeof(Tcl_Obj)) : NULL;
this->s0 = this->o ? (this->o->bytes ? copyinstr((user_addr_t)this->o->bytes, maxstrlen) :
lltostr(this->o->internalRep.longValue)) : "";
this->i = 1;
this->o = arg3 > this->i && *(this->objv + this->i) ?
(Tcl_Obj*)copyin((user_addr_t)*(this->objv + this->i), sizeof(Tcl_Obj)) : NULL;
this->s1 = this->o ? (this->o->bytes ? copyinstr((user_addr_t)this->o->bytes, maxstrlen) :
lltostr(this->o->internalRep.longValue)) : "";
printf("%s %s.%s (%d) %s %s",
copyinstr(arg0), copyinstr(arg1), copyinstr(arg2), arg3,
this->s0, this->s1);
}
/*
* Output object, class, method and return code upon method return.
*/
nsf*:::method-return /self->tracing/ {
printf("%s %s.%s -> %d", copyinstr(arg0), copyinstr(arg1), copyinstr(arg2), arg3);
}
|
D
|
/*
This module contains implementations for vectors and matrices an altered version from my glmsolverd package
*/
module arrays;
import std.conv: to;
import std.format: format;
import std.traits: isFloatingPoint, isIntegral, isNumeric;
import std.algorithm: min, max;
import std.math: modf;
import core.memory: GC;
import std.stdio: writeln;
import std.random;
/********************************************* Printer Utility Functions *********************************************/
auto getRange(T)(const(T[]) data)
if(isFloatingPoint!T)
{
real[2] range = [cast(real)data[0], cast(real)data[0]];
foreach(el; data)
{
range[0] = min(range[0], el);
range[1] = max(range[1], el);
}
return range;
}
string getFormat(real[] range, long maxLength = 8, long gap = 2)
{
writeln("range: ", range);
string form = "";
if((range[0] > 0.01) & (range[1] < 1000_000))
{
form = "%" ~ to!(string)(gap + 2 + maxLength) ~ "." ~ to!(string)(maxLength) ~ "g";
}else if((range[0] < 0.0001) | (range[1] > 1000_000))
{
form = "%" ~ to!(string)(gap + 1 + maxLength) ~ "." ~ to!(string)(4) ~ "g";
}
return form;
}
/********************************************* Matrix Class *********************************************/
/*
Faster Array Creation
*/
auto newArray(T)(long n)
{
auto data = (cast(T*)GC.malloc(T.sizeof*n, GC.BlkAttr.NO_SCAN))[0..n];
if(data == null)
assert(0, "Array Allocation Failed!");
return data;
}
/*
Matrix will be column major
*/
mixin template MatrixGubbings(T)
{
private:
T[] data;
long[] dim;
public:
this(T[] _data, long rows, long cols)
{
assert(rows*cols == _data.length,
"dimension of matrix inconsistent with length of array");
data = _data; dim = [rows, cols];
}
this(long n, long m)
{
long _len = n*m;
data = newArray!(T)(_len);
dim = [n, m];
}
this(T[] _data, long[] _dim)
{
long tlen = _dim[0]*_dim[1];
assert(tlen == _data.length,
"dimension of matrix inconsistent with length of array");
data = _data; dim = _dim;
}
this(Matrix!(T) mat)
{
data = mat.data.dup;
dim = mat.dim.dup;
}
@property Matrix!(T) dup() const
{
return Matrix!(T)(data.dup, dim.dup);
}
T opIndex(long i, long j) const
{
return data[dim[0]*j + i];
}
void opIndexAssign(T x, long i, long j)
{
data[dim[0]*j + i] = x;
}
T opIndexOpAssign(string op)(T x, long i, long j)
{
static if((op == "+") | (op == "-") | (op == "*") | (op == "/") | (op == "^^"))
mixin("return data[dim[0]*j + i] " ~ op ~ "= x;");
else static assert(0, "Operator \"" ~ op ~ "\" not implemented");
}
Matrix!(T) opBinary(string op)(Matrix!(T) x)
{
assert( data.length == x.array.length,
"Number of rows and columns in matrices not equal.");
long n = data.length;
auto ret = Matrix!(T)(dim[0], dim[1]);
static if((op == "+") | (op == "-") | (op == "*") | (op == "/") | (op == "^^"))
{
for(long i = 0; i < n; ++i)
{
mixin("ret.array[i] = " ~ "data[i] " ~ op ~ " x.array[i];");
}
}else static assert(0, "Operator \"" ~ op ~ "\" not implemented");
return ret;
}
Matrix!(T) opBinary(string op)(T rhs)
{
ulong n = data.length;
Matrix!(T) ret = Matrix!(T)(dim[0], dim[1]);
static if((op == "+") | (op == "-") | (op == "*") | (op == "/") | (op == "^^"))
{
for(ulong i = 0; i < n; ++i)
{
mixin("ret.array[i] = " ~ "data[i] " ~ op ~ " rhs;");
}
}else static assert(0, "Operator \"" ~ op ~ "\" not implemented");
return ret;
}
Matrix!(T) opBinaryRight(string op)(T lhs)
{
long n = data.length;
Matrix!(T) ret = Matrix!(T)(dim[0], dim[1]);
static if((op == "+") | (op == "-") | (op == "*") | (op == "/") | (op == "^^"))
{
for(long i = 0; i < n; ++i)
{
mixin("ret.array[i] = " ~ "lhs " ~ op ~ " data[i];");
}
}else static assert(0, "Operator \"" ~ op ~ "\" not implemented");
return ret;
}
void opOpAssign(string op)(Matrix!(T) x)
{
assert( data.length == x.array.length,
"Number of rows and columns in matrices not equal.");
long n = data.length;
static if((op == "+") | (op == "-") | (op == "*") | (op == "/") | (op == "^^"))
{
for(long i = 0; i < n; ++i)
{
mixin("data[i] " ~ op ~ "= x.array[i];");
}
}else static assert(0, "Operator \"" ~ op ~ "\" not implemented");
}
/* mat "op"= rhs */
void opOpAssign(string op)(T rhs)
{
long n = data.length;
static if((op == "+") | (op == "-") | (op == "*") | (op == "/") | (op == "^^"))
{
for(long i = 0; i < n; ++i)
{
mixin("data[i] " ~ op ~ "= rhs;");
}
}else static assert(0, "Operator \"" ~ op ~ "\" not implemented");
}
@property long nrow() const
{
return dim[0];
}
@property long ncol() const
{
return dim[1];
}
@property T[] array()
{
return data;
}
@property long len() const
{
return data.length;
}
@property long length() const
{
return data.length;
}
@property size() const
{
return dim.dup;
}
/* Returns transposed matrix (duplicated) */
Matrix!(T) t() const
{
auto _data = data.dup;
long[] _dim = new long[2];
_dim[0] = dim[1]; _dim[1] = dim[0];
if((dim[0] == 1) & (dim[1] == 1)){
} else if(dim[0] != dim[1]) {
for(long j = 0; j < dim[1]; ++j)
{
for(long i = 0; i < dim[0]; ++i)
{
_data[_dim[0]*i + j] = data[dim[0]*j + i];
}
}
} else if(dim[0] == dim[1]) {
for(long j = 0; j < dim[1]; ++j)
{
for(long i = 0; i < dim[0]; ++i)
{
if(i == j)
continue;
_data[_dim[0]*i + j] = data[dim[0]*j + i];
}
}
}
return Matrix!(T)(_data, _dim);
}
/* Appends Vector to the END of the matrix */
void appendColumn(T[] rhs)
{
assert(rhs.length == nrow,
"Vector is not of the same length as number of rows.");
data ~= rhs;
dim[1] += 1;
return;
}
void appendColumn(Matrix!(T) rhs)
{
assert((rhs.nrow == 1) | (rhs.ncol == 1),
"Matrix does not have 1 row or 1 column");
appendColumn(rhs.array);
}
void appendColumn(T _rhs)
{
auto rhs = newArray!(T)(nrow);
rhs[] = _rhs;
appendColumn(rhs);
}
/* Prepends Column Vector to the START of the matrix */
void prependColumn(T[] rhs)
{
assert(rhs.length == nrow,
"Vector is not of the same length as number of rows.");
data = rhs ~ data;
dim[1] += 1;
return;
}
void prependColumn(Matrix!(T) rhs)
{
assert((rhs.nrow == 1) | (rhs.ncol == 1),
"Matrix does not have 1 row or 1 column");
prependColumn(rhs.array);
}
void prependColumn(T _rhs)
{
auto rhs = newArray!(T)(nrow);
rhs[] = _rhs;
prependColumn(rhs);
}
/* Contiguous column select copies the column */
auto columnSelect(long start, long end)
{
assert(end > start, "Starting column is not less than end column");
long nCol = end - start;
long _len = nrow * nCol;
auto arr = newArray!(T)(_len);
auto startIndex = start*nrow;
long iStart = 0;
for(long i = 0; i < nCol; ++i)
{
arr[iStart..((iStart + nrow))] = data[startIndex..(startIndex + nrow)];
startIndex += nrow;
iStart += nrow;
}
return Matrix!(T)(arr, [nrow, nCol]);
}
auto columnSelect(long index)
{
assert(index < ncol, "Selected index is not less than number of columns.");
auto arr = newArray!(T)(nrow);
auto startIndex = index*nrow;
arr[] = data[startIndex..(startIndex + nrow)];
return Matrix!(T)(arr, [nrow, 1]);
}
auto refColumnSelect(long index)
{
assert(index < ncol, "Selected index is not less than number of columns.");
auto startIndex = index*nrow;
return Matrix!(T)(data[startIndex..(startIndex + nrow)], [nrow, 1]);
}
auto refColumnSelectArr(long index)
{
//assert(index < ncol, "Selected index is not less than number of columns.");
auto startIndex = index*nrow;
return data[startIndex..(startIndex + nrow)];
}
/*
Function to remove a column from the matrix.
*/
Matrix!(T) refColumnRemove(long index)
{
/* Remove first column */
if(index == 0)
{
data = data[nrow..$];
dim[1] -= 1;
return this;
/* Remove last column */
}else if(index == (ncol - 1))
{
data = data[0..($ - nrow)];
dim[1]-= 1;
return this;
/* Remove any other column */
}else{
auto start = index*nrow;
long _len = data.length - nrow;
auto _data = newArray!(T)(_len);
_data[0..start] = data[0..start];
_data[start..$] = data[(start + nrow)..$];
data = _data;
dim[1] -= 1;
return this;
}
}
/* Assigns vector in-place to a specific column */
/* Refactor these two methods */
Matrix!(T) refColumnAssign(T[] col, long index)
{
assert(col.length == nrow, "Length of vector is not the same as number of rows");
/* Replace first column */
if(index == 0)
{
data[0..nrow] = col;
return this;
/* Replace last column */
}else if(index == (ncol - 1))
{
data[($ - nrow)..$] = col;
return this;
/* Replace any other column */
}else{
auto start = index*nrow;
data[start..(start + nrow)] = col;
return this;
}
}
Matrix!(T) refColumnAssign(T col, long index)
{
/* Replace first column */
if(index == 0)
{
data[0..nrow] = col;
return this;
/* Replace last column */
}else if(index == (ncol - 1))
{
data[($ - nrow)..$] = col;
return this;
/* Replace any other column */
}else{
auto start = index*nrow;
data[start..(start + nrow)] = col;
return this;
}
}
}
/* Assuming column major */
struct Matrix(T)
if(isFloatingPoint!T)
{
mixin MatrixGubbings!(T);
string toString() const
{
string dform = getFormat(getRange(data));
string repr = format(" Matrix(%d x %d)\n", dim[0], dim[1]);
for(long i = 0; i < dim[0]; ++i)
{
for(long j = 0; j < dim[1]; ++j)
{
repr ~= format(dform, opIndex(i, j));
}
repr ~= "\n";
}
return repr;
}
}
// Create random matrix
/****************************************************************************/
Matrix!T createRandomMatrix(T)(ulong rows, ulong cols)
{
Mt19937_64 gen;
gen.seed(unpredictableSeed);
ulong len = rows*cols;
T[] data = newArray!(T)(len);
for(int i = 0; i < len; ++i)
data[i] = uniform01!(T)(gen);
return Matrix!T(data, rows, cols);
}
Matrix!T createRandomMatrix(T)(ulong m)
{
return createRandomMatrix!(T)(m, m);
}
Matrix!T createRandomMatrix(T)(ulong[] dim)
{
return createRandomMatrix!(T)(dim[0], dim[1]);
}
|
D
|
/**
* Wrap Length module.
*
* License:
* MIT. See LICENSE for full details.
*/
module tkd.widget.common.wraplength;
/**
* These are common commands that apply to all widgets that have them injected.
*/
mixin template WrapLength()
{
/**
* Specifies the maximum line length (in pixels). If this option is less
* than or equal to zero, then automatic wrapping is not performed;
* otherwise the text is split into lines such that no line is longer than
* the specified value.
*
* Params:
* pixels = The maximum width in pixels.
*
* Returns:
* This widget to aid method chaining.
*/
public auto setWrapLength(this T)(int pixels)
{
this._tk.eval("%s configure -wraplength %s", this.id, pixels);
return cast(T) this;
}
}
|
D
|
/*****************************************************************************
*
* Higgs JavaScript Virtual Machine
*
* This file is part of the Higgs project. The project is distributed at:
* https://github.com/maximecb/Higgs
*
* Copyright (c) 2011-2014, Maxime Chevalier-Boisvert. All rights reserved.
*
* This software is licensed under the following license (Modified BSD
* License):
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*****************************************************************************/
module ir.livevars;
import core.memory;
import std.stdio;
import std.array;
import std.string;
import std.stdint;
import std.algorithm;
import ir.ir;
import util.string;
/**
Liveness information for a given function
*/
class LiveInfo
{
/**
Live variable set implementation
*/
struct LiveSet
{
IRDstValue* arr;
uint32_t arrLen;
uint32_t numElems;
void add(IRDstValue val)
{
// If the element is already present, stop
for (size_t i = 0; i < numElems; ++i)
if (arr[i] is val)
return;
if (numElems + 1 > arrLen)
{
if (arrLen is 0)
{
arrLen = 16;
arr = cast(IRDstValue*)GC.malloc(
(IRDstValue*).sizeof * arrLen,
GC.BlkAttr.NO_SCAN |
GC.BlkAttr.NO_INTERIOR
);
}
else
{
auto newLen = 2 * arrLen;
auto newArr = cast(IRDstValue*)GC.malloc(
(IRDstValue*).sizeof * newLen,
GC.BlkAttr.NO_SCAN |
GC.BlkAttr.NO_INTERIOR
);
for (size_t i = 0; i < numElems; ++i)
newArr[i] = arr[i];
GC.free(arr);
arr = newArr;
arrLen = newLen;
}
}
arr[numElems] = val;
numElems += 1;
}
bool has(IRDstValue val)
{
for (size_t i = 0; i < numElems; ++i)
if (arr[i] is val)
return true;
return false;
}
IRDstValue[] elems()
{
return arr[0..numElems];
}
}
/// Live sets indexed by instruction (values live after the instruction)
private LiveSet[IRInstr] liveSets;
/**
Compile a list of all values live before a given instruction
*/
public IRDstValue[] valsLiveBefore(IRInstr beforeInstr)
{
// Get the values live after this instruction
auto liveSet = valsLiveAfter(beforeInstr);
// Remove the instruction itself from the live set
if (beforeInstr.hasUses)
liveSet = array(liveSet.filter!(v => v !is beforeInstr)());
// Add the instruction arguments to the live set
for (size_t aIdx = 0; aIdx < beforeInstr.numArgs; ++aIdx)
{
if (auto dstArg = cast(IRDstValue)beforeInstr.getArg(aIdx))
if (!liveSet.canFind(dstArg))
liveSet ~= dstArg;
}
return liveSet;
}
/**
Compile a list of all values live after a given instruction
*/
public IRDstValue[] valsLiveAfter(IRInstr afterInstr)
{
assert (afterInstr in liveSets);
return liveSets[afterInstr].elems;
}
/**
Test if a value is live at a basic block's entry
*/
public bool liveAtEntry(IRDstValue val, IRBlock block)
{
assert (
val !is null,
"value is null in liveAtEntry"
);
// If the value is a phi node argument, it must be live
for (size_t pIdx = 0; pIdx < block.numIncoming; ++pIdx)
{
auto desc = block.getIncoming(pIdx);
foreach (arg; desc.args)
if (arg.value is val)
return true;
}
// If the value is from this block and is a phi node, it isn't live
if (val.block is block && cast(PhiNode)val)
return false;
// Test if the value is live after the phi nodes
return liveAfterPhi(val, block);
}
/**
Test if a value is live after the phi nodes of a given block
*/
public bool liveAfterPhi(IRDstValue val, IRBlock block)
{
assert (
val !is null,
"value is null in liveAtEntry"
);
assert (
block.firstInstr !is null,
"block contains no instructions"
);
// If the value is the first instruction, it isn't live
if (val is block.firstInstr)
return false;
// If the value is an argument to the first block instruction, it is live
for (size_t aIdx = 0; aIdx < block.firstInstr.numArgs; ++aIdx)
if (val is block.firstInstr.getArg(aIdx))
return true;
// Test if the value is live after the first instruction
return liveAfter(val, block.firstInstr);
}
/**
Test if a value is live before a given instruction
Note: this function is exposed outside of this analysis
*/
public bool liveBefore(IRDstValue val, IRInstr beforeInstr)
{
// Values with no uses are never live
if (val.hasNoUses)
return false;
// If the value is the instruction, it isn't live
if (val is beforeInstr)
return false;
// If the value is an argument to the instruction, it is live
if (beforeInstr.hasArg(val))
return true;
// If the value is live after the instruction, it is live before
return liveAfter(val, beforeInstr);
}
/**
Test if a value is live after a given instruction
Note: this function is exposed outside of this analysis
*/
public bool liveAfter(IRDstValue val, IRInstr afterInstr)
{
auto liveSet = afterInstr in liveSets;
assert (
liveSet !is null,
"no live set for instr: " ~ afterInstr.toString
);
// Values with no uses are never live
if (val.hasNoUses)
return false;
return (*liveSet).has(val);
}
/**
Mark a value as live after a given instruction
*/
private void markLiveAfter(IRDstValue val, IRInstr afterInstr)
{
auto liveSet = afterInstr in liveSets;
assert (
liveSet !is null,
"no live set for instr: " ~ afterInstr.toString
);
// Add the value to the live set
(*liveSet).add(val);
}
/**
Performs liveness analysis on a function body and
returns a liveness query function (closure)
*/
public this(IRFunction fun)
{
assert (
fun.entryBlock !is null,
"function has no IR"
);
//writeln(fun.getName);
// Initialize the live sets for each instruction to the empty set
for (auto block = fun.firstBlock; block !is null; block = block.next)
for (auto instr = block.firstInstr; instr !is null; instr = instr.next)
liveSets[instr] = LiveSet.init;
// Stack of blocks for DFS traversal
IRBlock stack[];
stack.reserve(32768);
/**
Traverse a basic block as part of a liveness analysis
*/
void traverseBlock(IRDstValue defVal, IRBlock block, IRInstr fromInstr)
{
// For each instruction, in reverse order
for (auto instr = fromInstr; instr !is null; instr = instr.prev)
{
// Mark the value as live after this instruction
markLiveAfter(defVal, instr);
// If this is the definition point for the value, stop
if (instr is defVal)
return;
}
// If the value is defined by a phi node from this block, stop
if (defVal.block is block)
{
assert (
cast(PhiNode)defVal !is null,
format(
"value: %s\ndefined in block: %s\nnot found:\n%s",
defVal,
defVal.block.getName,
fun.toString
)
);
return;
}
// Queue the predecessor blocks
for (size_t iIdx = 0; iIdx < block.numIncoming; ++iIdx)
{
stack.assumeSafeAppend() ~= block.getIncoming(iIdx).branch.block;
}
}
/**
Do the liveness traversal for a given use
*/
void liveTraversal(IRDstValue defVal, IRDstValue useVal)
{
assert (defVal !is null);
assert (useVal !is null);
assert (stack.length is 0);
// Get the block the use belongs to
auto useBlock = useVal.block;
assert (useBlock !is null);
// If the use belongs to an instruction
if (auto useInstr = cast(IRInstr)useVal)
{
// Traverse the block starting from the previous instruction
traverseBlock(defVal, useBlock, useInstr.prev);
}
// If the use belongs to a phi node
else if (auto usePhi = cast(PhiNode)useVal)
{
// Find the predecessors which supplies the value and queue them
for (size_t iIdx = 0; iIdx < useBlock.numIncoming; ++iIdx)
{
auto branch = useBlock.getIncoming(iIdx);
auto phiArg = branch.getPhiArg(usePhi);
if (phiArg is defVal)
stack.assumeSafeAppend() ~= branch.branch.block;
}
}
else
{
assert (false);
}
// Until the stack is empty
while (stack.length > 0)
{
// Pop the top of the stack
auto block = stack.back();
stack.length--;
assert (block.lastInstr !is null);
// If the value is live at the exit of this block, skip it
if (liveAfter(defVal, block.lastInstr))
continue;
// Traverse the block starting from the last instruction
traverseBlock(defVal, block, block.lastInstr);
}
}
// Compute the liveness of all values
for (auto block = fun.firstBlock; block !is null; block = block.next)
{
for (auto phi = block.firstPhi; phi !is null; phi = phi.next)
for (auto use = phi.getFirstUse; use !is null; use = use.next)
liveTraversal(phi, use.owner);
for (auto instr = block.firstInstr; instr !is null; instr = instr.next)
for (auto use = instr.getFirstUse; use !is null; use = use.next)
liveTraversal(instr, use.owner);
}
//writeln(" done");
}
}
|
D
|
module secured.openssl;
import deimos.openssl.evp;
import core.stdc.stdint;
private:
enum int EVP_PKEY_ALG_CTRL = 0x1000;
enum int EVP_PKEY_CTRL_HKDF_MD = (EVP_PKEY_ALG_CTRL + 3);
enum int EVP_PKEY_CTRL_HKDF_SALT = (EVP_PKEY_ALG_CTRL + 4);
enum int EVP_PKEY_CTRL_HKDF_KEY = (EVP_PKEY_ALG_CTRL + 5);
enum int EVP_PKEY_CTRL_HKDF_INFO = (EVP_PKEY_ALG_CTRL + 6);
enum int EVP_PKEY_CTRL_HKDF_MODE = (EVP_PKEY_ALG_CTRL + 7);
enum int EVP_PKEY_CTRL_PASS = (EVP_PKEY_ALG_CTRL + 8);
enum int EVP_PKEY_CTRL_SCRYPT_SALT = (EVP_PKEY_ALG_CTRL + 9);
enum int EVP_PKEY_CTRL_SCRYPT_N = (EVP_PKEY_ALG_CTRL + 10);
enum int EVP_PKEY_CTRL_SCRYPT_R = (EVP_PKEY_ALG_CTRL + 11);
enum int EVP_PKEY_CTRL_SCRYPT_P = (EVP_PKEY_ALG_CTRL + 12);
enum int EVP_PKEY_CTRL_SCRYPT_MAXMEM_BYTES = (EVP_PKEY_ALG_CTRL + 13);
extern (C):
nothrow:
public:
ulong ERR_get_error();
ulong ERR_peek_error();
void ERR_error_string_n(ulong e, char *buf, size_t len);
EVP_MD_CTX* EVP_MD_CTX_new();
void EVP_MD_CTX_free(EVP_MD_CTX* free);
void EVP_MD_CIPHER_free(EVP_CIPHER_CTX* free);
int EVP_PBE_scrypt(const char *pass, size_t passlen, const ubyte *salt, size_t saltlen, ulong N, ulong r, ulong p, ulong maxmem, ubyte *key, size_t keylen);
const(EVP_CIPHER)* EVP_chacha20();
const(EVP_CIPHER)* EVP_chacha20_poly1305();
extern(D):
enum int EVP_PKEY_HKDF = 1036;
enum int EVP_PKEY_SCRYPT = 973;
enum int EVP_CTRL_AEAD_SET_IVLEN = 0x9;
enum int EVP_CTRL_AEAD_GET_TAG = 0x10;
enum int EVP_CTRL_AEAD_SET_TAG = 0x11;
int EVP_PKEY_CTX_set_hkdf_md(EVP_PKEY_CTX *pctx, const EVP_MD *md) {
return EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_MD, 0, cast(void *)(md));
}
int EVP_PKEY_CTX_set1_hkdf_salt(EVP_PKEY_CTX *pctx, const ubyte[] salt) {
return EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_SALT, cast(int)salt.length, cast(void *)salt.ptr);
}
int EVP_PKEY_CTX_set1_hkdf_key(EVP_PKEY_CTX *pctx, const ubyte[] key) {
return EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_KEY, cast(int)key.length, cast(void *)key.ptr);
}
int EVP_PKEY_CTX_add1_hkdf_info(EVP_PKEY_CTX *pctx, string info) {
return EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_INFO, cast(int)(cast(ubyte[])info).length, cast(void *)info);
}
int EVP_PKEY_CTX_set1_pbe_pass(EVP_PKEY_CTX *pctx, const ubyte[] password) {
return EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_PASS, cast(int)password.length, cast(void *)(password));
}
int EVP_PKEY_CTX_set1_scrypt_salt(EVP_PKEY_CTX *pctx, const ubyte[] salt) {
return EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_SALT, cast(int)salt.length, cast(void *)(salt));
}
int EVP_PKEY_CTX_set_scrypt_N(EVP_PKEY_CTX *pctx, ulong n) {
return EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_N, 0, cast(void*)n);
}
int EVP_PKEY_CTX_set_scrypt_r(EVP_PKEY_CTX *pctx, ulong r) {
return EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_R, 0, cast(void*)r);
}
int EVP_PKEY_CTX_set_scrypt_p(EVP_PKEY_CTX *pctx, ulong p) {
return EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_P, 0, cast(void*)p);
}
|
D
|
module game.weapon;
import dlib.core.memory;
import dlib.math.vector;
import dlib.math.matrix;
import dlib.math.transformation;
import dlib.geometry.aabb;
import dgl.core.api;
import dgl.core.event;
import dgl.core.interfaces;
import dgl.graphics.entity;
import game.fpcamera;
class Weapon: Entity, Modifier
{
FirstPersonCamera camera;
bool shooting = false;
this(FirstPersonCamera camera, Drawable model)
{
super(model);
this.camera = camera;
}
override Vector3f getPosition()
{
return transformation.translation;
}
override void update(double dt)
{
transformation = camera.gunTransformation;
transformation *= translationMatrix(position);
//transformation *= rotation.toMatrix4x4;
}
override Matrix4x4f getTransformation()
{
return camera.gunTransformation;
}
void bind(double dt)
{
glPushMatrix();
glMultMatrixf(transformation.arrayof.ptr);
}
void unbind()
{
glPopMatrix();
}
override void draw(double dt)
{
bind(dt);
drawModel(dt);
unbind();
}
void shoot() {}
}
|
D
|
/Users/Mandy_Cho/Documents/getS(ch)wifty/Storm/DerivedData/Storm/Build/Intermediates/Storm.build/Debug-iphonesimulator/Storm.build/Objects-normal/x86_64/AppDelegate.o : /Users/Mandy_Cho/Documents/getS(ch)wifty/Storm/Storm/DetailViewController.swift /Users/Mandy_Cho/Documents/getS(ch)wifty/Storm/Storm/MasterViewController.swift /Users/Mandy_Cho/Documents/getS(ch)wifty/Storm/Storm/AppDelegate.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule
/Users/Mandy_Cho/Documents/getS(ch)wifty/Storm/DerivedData/Storm/Build/Intermediates/Storm.build/Debug-iphonesimulator/Storm.build/Objects-normal/x86_64/AppDelegate~partial.swiftmodule : /Users/Mandy_Cho/Documents/getS(ch)wifty/Storm/Storm/DetailViewController.swift /Users/Mandy_Cho/Documents/getS(ch)wifty/Storm/Storm/MasterViewController.swift /Users/Mandy_Cho/Documents/getS(ch)wifty/Storm/Storm/AppDelegate.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule
/Users/Mandy_Cho/Documents/getS(ch)wifty/Storm/DerivedData/Storm/Build/Intermediates/Storm.build/Debug-iphonesimulator/Storm.build/Objects-normal/x86_64/AppDelegate~partial.swiftdoc : /Users/Mandy_Cho/Documents/getS(ch)wifty/Storm/Storm/DetailViewController.swift /Users/Mandy_Cho/Documents/getS(ch)wifty/Storm/Storm/MasterViewController.swift /Users/Mandy_Cho/Documents/getS(ch)wifty/Storm/Storm/AppDelegate.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule
|
D
|
func void B_StopMagicFlee() //испр. - int на void
{
// отключить особое восприятие повреждения
Npc_PercDisable(self,PERC_ASSESSDAMAGE);
// начать убегать
Npc_SetTarget(self,other);
AI_StartState(self,ZS_Flee,0,"");
};
func void B_AssessDamage_MagicFlee()
{
B_OnDamage();
// сообщить всем о драке
Npc_SendPassivePerc(self,PERC_ASSESSFIGHTSOUND,self,other);
// завершить состояние
B_StopMagicFlee();
};
func void ZS_MagicFlee()
{
var int randy;
Npc_PercEnable(self,PERC_ASSESSDAMAGE,B_AssessDamage_MagicFlee);
Npc_PercEnable(self,PERC_ASSESSMAGIC,B_AssessMagic);
B_GuardPassageStatusReset(self);
Npc_SetRefuseTalk(self,0);
Npc_SetTempAttitude(self,Npc_GetPermAttitude(self,hero));
B_StopLookAt(self);
AI_StopPointAt(self);
if(!Npc_HasBodyFlag(self,BS_FLAG_INTERRUPTABLE))
{
AI_Standup(self);
}
else
{
AI_StandupQuick(self);
};
if(self.guild < GIL_SEPERATOR_HUM)
{
randy = Hlp_Random(3);
if(randy == 0)
{
AI_PlayAniBS(self,"T_STAND_2_FEAR_VICTIM1",BS_STAND);
};
if(randy == 1)
{
AI_PlayAniBS(self,"T_STAND_2_FEAR_VICTIM2",BS_STAND);
};
if(randy == 2)
{
AI_PlayAniBS(self,"T_STAND_2_FEAR_VICTIM3",BS_STAND);
};
};
};
func int ZS_MagicFlee_Loop()
{
if(Npc_GetStateTime(self) > SPL_TIME_Fear)
{
Npc_ClearAIQueue(self);
B_StopMagicFlee();
return LOOP_END; //испр. - добавлено
};
return LOOP_CONTINUE;//испр. - добавлено
};
func void ZS_MagicFlee_End()
{
};
|
D
|
# FIXED
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/apps/httpserver_raw/httpd.c
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/opt.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/Users/Owner/workspace_v6_2/enet_lwip/lwipopts.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/debug.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/arch.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/ports/tiva-tm4c129/include/arch/cc.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-arm_5.2.5/include/stdbool.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-arm_5.2.5/include/yvals.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-arm_5.2.5/include/stdarg.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-arm_5.2.5/include/linkage.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-arm_5.2.5/include/_lock.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-arm_5.2.5/include/stdint.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/ports/tiva-tm4c129/include/arch/../../../../../../utils/uartstdio.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-arm_5.2.5/include/stdarg.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/opt.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/stats.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/mem.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/memp.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/memp_std.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/apps/httpserver_raw/httpd.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/err.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/pbuf.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/apps/httpserver_raw/httpd_structs.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/tcp.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/ipv4/lwip/ip.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/def.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/ipv4/lwip/ip_addr.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/netif.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/ipv4/lwip/icmp.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/apps/httpserver_raw/fs.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-arm_5.2.5/include/string.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-arm_5.2.5/include/stdlib.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/driverlib/uart.h
third_party/lwip-1.4.1/apps/httpserver_raw/httpd.obj: C:/ti/TivaWare_C_Series-2.1.4.178/inc/hw_memmap.h
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/apps/httpserver_raw/httpd.c:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/opt.h:
C:/Users/Owner/workspace_v6_2/enet_lwip/lwipopts.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/debug.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/arch.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/ports/tiva-tm4c129/include/arch/cc.h:
C:/ti/ccsv6/tools/compiler/ti-cgt-arm_5.2.5/include/stdbool.h:
C:/ti/ccsv6/tools/compiler/ti-cgt-arm_5.2.5/include/yvals.h:
C:/ti/ccsv6/tools/compiler/ti-cgt-arm_5.2.5/include/stdarg.h:
C:/ti/ccsv6/tools/compiler/ti-cgt-arm_5.2.5/include/linkage.h:
C:/ti/ccsv6/tools/compiler/ti-cgt-arm_5.2.5/include/_lock.h:
C:/ti/ccsv6/tools/compiler/ti-cgt-arm_5.2.5/include/stdint.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/ports/tiva-tm4c129/include/arch/../../../../../../utils/uartstdio.h:
C:/ti/ccsv6/tools/compiler/ti-cgt-arm_5.2.5/include/stdarg.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/opt.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/stats.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/mem.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/memp.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/memp_std.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/apps/httpserver_raw/httpd.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/err.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/pbuf.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/apps/httpserver_raw/httpd_structs.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/tcp.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/ipv4/lwip/ip.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/def.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/ipv4/lwip/ip_addr.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/lwip/netif.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/src/include/ipv4/lwip/icmp.h:
C:/ti/TivaWare_C_Series-2.1.4.178/third_party/lwip-1.4.1/apps/httpserver_raw/fs.h:
C:/ti/ccsv6/tools/compiler/ti-cgt-arm_5.2.5/include/string.h:
C:/ti/ccsv6/tools/compiler/ti-cgt-arm_5.2.5/include/stdlib.h:
C:/ti/TivaWare_C_Series-2.1.4.178/driverlib/uart.h:
C:/ti/TivaWare_C_Series-2.1.4.178/inc/hw_memmap.h:
|
D
|
module render_utils;
import std.conv;
import std.stdio;
import gfm.math.vector;
import derelict.sdl2.sdl;
import derelict.sdl2.ttf;
import misc.rect;
import misc.coords;
import state.render_state;
const auto BLACK = SDL_Color(0, 0, 0, 0);
const auto WHITE = SDL_Color(0xff, 0xff, 0xff, 0xff);
void setRenderDrawColor(
SDL_Renderer *renderer,
SDL_Color color,
ubyte alpha
) {
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, alpha);
}
void renderClear(RenderState state) {
SDL_SetRenderDrawColor(state.renderer, 0, 0, 0, 0xff);
SDL_RenderClear(state.renderer);
}
void drawText(
RenderState state,
string text,
TTF_Font *font,
int x,
int y
) {
state.drawText(text.dup ~ '\0', font, x, y);
}
void drawText(
RenderState state,
char[] text,
TTF_Font *font,
int x,
int y
) {
auto textTexture = state.getTextTexture(text, font, WHITE);
if (textTexture is null) {
writeln(to!string(SDL_GetError()));
return;
}
int w, h;
SDL_QueryTexture(textTexture, null, null, &w, &h);
auto targetLoc = SDL_Rect(x, y, w, h);
SDL_RenderCopy(state.renderer, textTexture, null, &targetLoc);
SDL_DestroyTexture(textTexture);
}
void drawTextCentered(
RenderState state,
string text,
TTF_Font *font,
int x,
int y
) {
state.drawTextCentered(text.dup ~ '\0', font, x, y);
}
void drawTextCentered(
RenderState state,
char[] text,
TTF_Font *font,
int x,
int y
) {
auto textTexture = state.getTextTexture(text, font, WHITE);
if (textTexture is null) {
writeln(to!string(SDL_GetError()));
return;
}
int w, h;
SDL_QueryTexture(textTexture, null, null, &w, &h);
auto targetLoc = SDL_Rect(x - w / 2, y - h / 2, w, h);
SDL_RenderCopy(state.renderer, textTexture, null, &targetLoc);
SDL_DestroyTexture(textTexture);
}
SDL_Texture *getTextTexture(
RenderState state,
char[] text,
TTF_Font *font,
SDL_Color color
) {
auto textSurface = TTF_RenderText_Solid(font, text.ptr, color);
if (textSurface is null) {
writeln(to!string(SDL_GetError()));
return null;
}
scope(exit) SDL_FreeSurface(textSurface);
auto textTexture = SDL_CreateTextureFromSurface(
state.renderer,
textSurface
);
if (textTexture is null) {
writeln(to!string(SDL_GetError()));
return null;
}
return textTexture;
}
void drawRect(
RenderState state,
RenderCoords topLeft,
RenderCoords dimensions,
SDL_Color color,
ubyte alpha,
) {
auto targetRect = getRectFromVectors(
topLeft,
topLeft + dimensions
);
setRenderDrawColor(state.renderer, color, alpha);
SDL_RenderDrawRect(state.renderer, &targetRect);
}
void fillRect(
RenderState state,
RenderCoords topLeft,
RenderCoords dimensions,
SDL_Color color,
ubyte alpha,
) {
auto targetRect = getRectFromVectors(
topLeft,
topLeft + dimensions
);
setRenderDrawColor(state.renderer, color, alpha);
SDL_RenderFillRect(state.renderer, &targetRect);
}
void drawLine(
RenderState state,
RenderCoords point1,
RenderCoords point2,
SDL_Color color,
ubyte alpha,
) {
setRenderDrawColor(state.renderer, color, alpha);
SDL_RenderDrawLine(
state.renderer,
cast(int)point1.x,
cast(int)point1.y,
cast(int)point2.x,
cast(int)point2.y
);
}
|
D
|
instance VLK_406_Herold(Npc_Default)
{
name[0] = "Herold";
guild = GIL_VLK;
id = 406;
voice = 4;
flags = 0;
npcType = npctype_main;
B_SetAttributesToChapter(self,2);
fight_tactic = FAI_HUMAN_COWARD;
EquipItem(self,ItMw_1h_Vlk_Dagger);
B_CreateAmbientInv(self);
B_SetNpcVisual(self,MALE,"Hum_Head_Bald",Face_N_Normal_Sly,BodyTex_N,ITAR_Vlk_SH);
Mdl_SetModelFatness(self,1.5);
Mdl_ApplyOverlayMds(self,"Humans_Arrogance.mds");
B_GiveNpcTalents(self);
B_SetFightSkills(self,30);
daily_routine = Rtn_Start_406;
};
func void Rtn_Start_406()
{
TA_Announce_Herold(8,0,16,30,"NW_CITY_HEROLD_UP");
TA_Stand_ArmsCrossed(16,30,18,0,"NW_CITY_HEROLD_UP");
TA_Announce_Herold(18,0,20,0,"NW_CITY_HEROLD_UP");
TA_Sit_Chair(20,0,8,0,"NW_CITYHALL_UPSTAIRS_02");
};
|
D
|
/Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Fluent.build/Query/QuerySupporting.swift.o : /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/ID.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/SchemaSupporting+CRUD.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/Model+CRUD.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+CRUD.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Utilities/Deprecated.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Service/MigrateCommand.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Service/RevertCommand.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Decode.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Range.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/SoftDeletable.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Aggregate.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/MigrationConfig.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/SchemaSupporting.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Join/JoinSupporting.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/MigrationSupporting.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Transaction/TransactionSupporting.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/QuerySupporting.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/MigrationLog.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Model.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/Model.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/AnyModel.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/Children.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Join/QueryBuilder+Join.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/SchemaSupporting+Migration.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/Migration.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/AnyMigration.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Run.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Service/FluentProvider.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/SchemaBuilder.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/SchemaUpdater.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Filter.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Utilities/FluentError.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/SchemaCreator.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/DatabasesConfig+References.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/Siblings.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/Migrations.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/AnyMigrations.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Operators.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Utilities/Exports.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/Parent.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Service/CommandConfig+Fluent.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Cache/KeyedCacheSupporting+Fluent.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/DatabaseConnection+Fluent.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/ModelEvent.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/Pivot.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Sort.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Cache/CacheEntry.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/FluentProperty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/NIO.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Async.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Command.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Service.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Console.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Logging.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/NIOConcurrencyHelpers.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/NIOFoundationCompat.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/DatabaseKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOAtomics/include/cpp_magic.h /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIODarwin/include/c_nio_darwin.h /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOAtomics/include/c-atomics.h /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOLinux/include/c_nio_linux.h /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/swift-nio-zlib-support.git--1071467962839356487/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIOSHA1.build/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIOOpenSSL.build/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIOZlib.build/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIODarwin.build/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIOHTTPParser.build/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIOAtomics.build/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIOLinux.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
/Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Fluent.build/QuerySupporting~partial.swiftmodule : /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/ID.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/SchemaSupporting+CRUD.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/Model+CRUD.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+CRUD.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Utilities/Deprecated.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Service/MigrateCommand.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Service/RevertCommand.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Decode.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Range.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/SoftDeletable.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Aggregate.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/MigrationConfig.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/SchemaSupporting.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Join/JoinSupporting.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/MigrationSupporting.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Transaction/TransactionSupporting.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/QuerySupporting.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/MigrationLog.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Model.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/Model.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/AnyModel.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/Children.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Join/QueryBuilder+Join.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/SchemaSupporting+Migration.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/Migration.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/AnyMigration.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Run.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Service/FluentProvider.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/SchemaBuilder.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/SchemaUpdater.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Filter.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Utilities/FluentError.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/SchemaCreator.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/DatabasesConfig+References.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/Siblings.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/Migrations.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/AnyMigrations.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Operators.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Utilities/Exports.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/Parent.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Service/CommandConfig+Fluent.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Cache/KeyedCacheSupporting+Fluent.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/DatabaseConnection+Fluent.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/ModelEvent.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/Pivot.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Sort.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Cache/CacheEntry.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/FluentProperty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/NIO.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Async.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Command.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Service.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Console.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Logging.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/NIOConcurrencyHelpers.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/NIOFoundationCompat.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/DatabaseKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOAtomics/include/cpp_magic.h /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIODarwin/include/c_nio_darwin.h /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOAtomics/include/c-atomics.h /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOLinux/include/c_nio_linux.h /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/swift-nio-zlib-support.git--1071467962839356487/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIOSHA1.build/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIOOpenSSL.build/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIOZlib.build/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIODarwin.build/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIOHTTPParser.build/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIOAtomics.build/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIOLinux.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
/Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Fluent.build/QuerySupporting~partial.swiftdoc : /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/ID.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/SchemaSupporting+CRUD.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/Model+CRUD.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+CRUD.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Utilities/Deprecated.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Service/MigrateCommand.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Service/RevertCommand.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Decode.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Range.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/SoftDeletable.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Aggregate.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/MigrationConfig.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/SchemaSupporting.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Join/JoinSupporting.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/MigrationSupporting.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Transaction/TransactionSupporting.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/QuerySupporting.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/MigrationLog.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Model.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/Model.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/AnyModel.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/Children.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Join/QueryBuilder+Join.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/SchemaSupporting+Migration.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/Migration.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/AnyMigration.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Run.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Service/FluentProvider.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/SchemaBuilder.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/SchemaUpdater.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Filter.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Utilities/FluentError.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/SchemaCreator.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/DatabasesConfig+References.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/Siblings.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/Migrations.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Migration/AnyMigrations.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Operators.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Utilities/Exports.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/Parent.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Service/CommandConfig+Fluent.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Cache/KeyedCacheSupporting+Fluent.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/DatabaseConnection+Fluent.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/ModelEvent.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Model/Pivot.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/QueryBuilder/QueryBuilder+Sort.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Cache/CacheEntry.swift /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/FluentProperty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/NIO.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Async.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Command.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Service.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Console.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Logging.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/NIOConcurrencyHelpers.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/NIOFoundationCompat.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/DatabaseKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOAtomics/include/cpp_magic.h /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIODarwin/include/c_nio_darwin.h /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOAtomics/include/c-atomics.h /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOLinux/include/c_nio_linux.h /Users/user/Documents/RiseTimeAssets/server/.build/checkouts/swift-nio-zlib-support.git--1071467962839356487/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIOSHA1.build/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIOOpenSSL.build/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIOZlib.build/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIODarwin.build/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIOHTTPParser.build/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIOAtomics.build/module.modulemap /Users/user/Documents/RiseTimeAssets/server/.build/x86_64-apple-macosx10.10/debug/CNIOLinux.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
|
D
|
/**
* Read a file from disk and store it in memory.
*
* Copyright: Copyright (C) 1999-2023 by The D Language Foundation, All Rights Reserved
* Authors: Walter Bright, https://www.digitalmars.com
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/root/file.d, root/_file.d)
* Documentation: https://dlang.org/phobos/dmd_root_file.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/root/file.d
*/
module dmd.root.file;
import core.stdc.errno;
import core.stdc.stdio;
import core.stdc.stdlib;
import core.stdc.string : strerror;
import core.sys.posix.fcntl;
import core.sys.posix.unistd;
import core.sys.windows.winbase;
import core.sys.windows.winnt;
import dmd.root.filename;
import dmd.root.rmem;
import dmd.root.string;
import dmd.common.file;
import dmd.common.string;
nothrow:
/// Owns a (rmem-managed) buffer.
struct Buffer
{
ubyte[] data;
nothrow:
this(this) @disable;
~this() pure nothrow
{
mem.xfree(data.ptr);
}
/// Transfers ownership of the buffer to the caller.
ubyte[] extractSlice() pure nothrow @nogc @safe
{
auto result = data;
data = null;
return result;
}
}
///
struct File
{
///
static struct ReadResult
{
bool success;
Buffer buffer;
/// Transfers ownership of the buffer to the caller.
ubyte[] extractSlice() pure nothrow @nogc @safe
{
return buffer.extractSlice();
}
/// ditto
/// Include the null-terminator at the end of the buffer in the returned array.
ubyte[] extractDataZ() @nogc nothrow pure
{
auto result = buffer.extractSlice();
return result.ptr[0 .. result.length + 1];
}
}
nothrow:
/// Read the full content of a file.
static ReadResult read(const(char)[] name)
{
ReadResult result;
version (Posix)
{
size_t size;
stat_t buf;
ssize_t numread;
//printf("File::read('%s')\n",name);
int fd = name.toCStringThen!(slice => open(slice.ptr, O_RDONLY));
if (fd == -1)
{
//perror("\topen error");
return result;
}
//printf("\tfile opened\n");
if (fstat(fd, &buf))
{
//perror("\tfstat error");
close(fd);
return result;
}
size = cast(size_t)buf.st_size;
ubyte* buffer = cast(ubyte*)mem.xmalloc_noscan(size + 4);
numread = .read(fd, buffer, size);
if (numread != size)
{
//perror("\tread error");
goto err2;
}
if (close(fd) == -1)
{
//perror("\tclose error");
goto err;
}
// Always store a wchar ^Z past end of buffer so scanner has a
// sentinel, although ^Z got obselete, so fill with two 0s and add
// two more so lexer doesn't read pass the buffer.
buffer[size .. size + 4] = 0;
result.success = true;
result.buffer.data = buffer[0 .. size];
return result;
err2:
close(fd);
err:
mem.xfree(buffer);
return result;
}
else version (Windows)
{
DWORD size;
DWORD numread;
// work around Windows file path length limitation
// (see documentation for extendedPathThen).
HANDLE h = name.extendedPathThen!
(p => CreateFileW(p.ptr,
GENERIC_READ,
FILE_SHARE_READ,
null,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
null));
if (h == INVALID_HANDLE_VALUE)
return result;
size = GetFileSize(h, null);
ubyte* buffer = cast(ubyte*)mem.xmalloc_noscan(size + 4);
if (ReadFile(h, buffer, size, &numread, null) != TRUE)
goto err2;
if (numread != size)
goto err2;
if (!CloseHandle(h))
goto err;
// Always store a wchar ^Z past end of buffer so scanner has a
// sentinel, although ^Z got obselete, so fill with two 0s and add
// two more so lexer doesn't read pass the buffer.
buffer[size .. size + 4] = 0;
result.success = true;
result.buffer.data = buffer[0 .. size];
return result;
err2:
CloseHandle(h);
err:
mem.xfree(buffer);
return result;
}
else
{
assert(0);
}
}
/// Write a file, returning `true` on success.
static bool write(const(char)* name, const void[] data)
{
import dmd.common.file : writeFile;
return writeFile(name, data);
}
///ditto
static bool write(const(char)[] name, const void[] data)
{
return name.toCStringThen!((fname) => write(fname.ptr, data));
}
/// Delete a file.
extern (C++) static void remove(const(char)* name)
{
version (Posix)
{
.remove(name);
}
else version (Windows)
{
name.toDString.extendedPathThen!(p => DeleteFileW(p.ptr));
}
else
{
static assert(0);
}
}
/***************************************************
* Update file
*
* If the file exists and is identical to what is to be written,
* merely update the timestamp on the file.
* Otherwise, write the file.
*
* The idea is writes are much slower than reads, and build systems
* often wind up generating identical files.
* Params:
* name = name of file to update
* data = updated contents of file
* Returns:
* `true` on success
*/
static bool update(const(char)* namez, const void[] data)
{
enum log = false;
if (log) printf("update %s\n", namez);
if (data.length != File.size(namez))
return write(namez, data); // write new file
if (log) printf("same size\n");
/* The file already exists, and is the same size.
* Read it in, and compare for equality.
*/
//if (FileMapping!(const ubyte)(namez)[] != data[])
return write(namez, data); // contents not same, so write new file
//if (log) printf("same contents\n");
/* Contents are identical, so set timestamp of existing file to current time
*/
//return touch(namez);
}
///ditto
static bool update(const(char)[] name, const void[] data)
{
return name.toCStringThen!(fname => update(fname.ptr, data));
}
/// Size of a file in bytes.
/// Params: namez = null-terminated filename
/// Returns: `ulong.max` on any error, the length otherwise.
static ulong size(const char* namez)
{
version (Posix)
{
stat_t buf;
if (stat(namez, &buf) == 0)
return buf.st_size;
}
else version (Windows)
{
const nameStr = namez.toDString();
import core.sys.windows.windows;
WIN32_FILE_ATTRIBUTE_DATA fad = void;
// Doesn't exist, not a regular file, different size
if (nameStr.extendedPathThen!(p => GetFileAttributesExW(p.ptr, GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, &fad)) != 0)
return (ulong(fad.nFileSizeHigh) << 32UL) | fad.nFileSizeLow;
}
else static assert(0);
// Error cases go here.
return ulong.max;
}
}
private
{
version (linux) version (PPC)
{
// https://issues.dlang.org/show_bug.cgi?id=22823
// Define our own version of stat_t, as older versions of the compiler
// had the st_size field at the wrong offset on PPC.
alias stat_t_imported = core.sys.posix.sys.stat.stat_t;
static if (stat_t_imported.st_size.offsetof != 48)
{
extern (C) nothrow @nogc:
struct stat_t
{
ulong[6] __pad1;
ulong st_size;
ulong[6] __pad2;
}
version (CRuntime_Glibc)
{
int fstat64(int, stat_t*) @trusted;
alias fstat = fstat64;
int stat64(const scope char*, stat_t*) @system;
alias stat = stat64;
}
else
{
int fstat(int, stat_t*) @trusted;
int stat(const scope char*, stat_t*) @system;
}
}
}
}
|
D
|
// REQUIRED_ARGS: -unittest
module issue19925;
unittest {
with (S) {
a(); // Compiles!
b(); // Fails!
}
}
struct S {
static void a() {}
static void opDispatch(string name)() {}
}
|
D
|
/**
* Contains traits for runtime internal usage.
*
* Copyright: Copyright Digital Mars 2014 -.
* License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
* Authors: Martin Nowak
* Source: $(DRUNTIMESRC core/internal/_traits.d)
*/
module core.internal.traits;
alias AliasSeq(TList...) = TList;
template Fields(T)
{
static if (is(T == struct) || is(T == union))
alias Fields = typeof(T.tupleof[0 .. $ - __traits(isNested, T)]);
else static if (is(T == class))
alias Fields = typeof(T.tupleof);
else
alias Fields = AliasSeq!T;
}
T trustedCast(T, U)(auto ref U u) @trusted pure nothrow
{
return cast(T)u;
}
template Unconst(T)
{
static if (is(T U == immutable U)) alias Unconst = U;
else static if (is(T U == inout const U)) alias Unconst = U;
else static if (is(T U == inout U)) alias Unconst = U;
else static if (is(T U == const U)) alias Unconst = U;
else alias Unconst = T;
}
/// taken from std.traits.Unqual
template Unqual(T)
{
version (none) // Error: recursive alias declaration @@@BUG1308@@@
{
static if (is(T U == const U)) alias Unqual = Unqual!U;
else static if (is(T U == immutable U)) alias Unqual = Unqual!U;
else static if (is(T U == inout U)) alias Unqual = Unqual!U;
else static if (is(T U == shared U)) alias Unqual = Unqual!U;
else alias Unqual = T;
}
else // workaround
{
static if (is(T U == immutable U)) alias Unqual = U;
else static if (is(T U == shared inout const U)) alias Unqual = U;
else static if (is(T U == shared inout U)) alias Unqual = U;
else static if (is(T U == shared const U)) alias Unqual = U;
else static if (is(T U == shared U)) alias Unqual = U;
else static if (is(T U == inout const U)) alias Unqual = U;
else static if (is(T U == inout U)) alias Unqual = U;
else static if (is(T U == const U)) alias Unqual = U;
else alias Unqual = T;
}
}
// [For internal use]
template ModifyTypePreservingTQ(alias Modifier, T)
{
static if (is(T U == immutable U)) alias ModifyTypePreservingTQ = immutable Modifier!U;
else static if (is(T U == shared inout const U)) alias ModifyTypePreservingTQ = shared inout const Modifier!U;
else static if (is(T U == shared inout U)) alias ModifyTypePreservingTQ = shared inout Modifier!U;
else static if (is(T U == shared const U)) alias ModifyTypePreservingTQ = shared const Modifier!U;
else static if (is(T U == shared U)) alias ModifyTypePreservingTQ = shared Modifier!U;
else static if (is(T U == inout const U)) alias ModifyTypePreservingTQ = inout const Modifier!U;
else static if (is(T U == inout U)) alias ModifyTypePreservingTQ = inout Modifier!U;
else static if (is(T U == const U)) alias ModifyTypePreservingTQ = const Modifier!U;
else alias ModifyTypePreservingTQ = Modifier!T;
}
@safe unittest
{
alias Intify(T) = int;
static assert(is(ModifyTypePreservingTQ!(Intify, real) == int));
static assert(is(ModifyTypePreservingTQ!(Intify, const real) == const int));
static assert(is(ModifyTypePreservingTQ!(Intify, inout real) == inout int));
static assert(is(ModifyTypePreservingTQ!(Intify, inout const real) == inout const int));
static assert(is(ModifyTypePreservingTQ!(Intify, shared real) == shared int));
static assert(is(ModifyTypePreservingTQ!(Intify, shared const real) == shared const int));
static assert(is(ModifyTypePreservingTQ!(Intify, shared inout real) == shared inout int));
static assert(is(ModifyTypePreservingTQ!(Intify, shared inout const real) == shared inout const int));
static assert(is(ModifyTypePreservingTQ!(Intify, immutable real) == immutable int));
}
// Substitute all `inout` qualifiers that appears in T to `const`
template substInout(T)
{
static if (is(T == immutable))
{
alias substInout = T;
}
else static if (is(T : shared const U, U) || is(T : const U, U))
{
// U is top-unqualified
mixin("alias substInout = "
~ (is(T == shared) ? "shared " : "")
~ (is(T == const) || is(T == inout) ? "const " : "") // substitute inout to const
~ "substInoutForm!U;");
}
else
static assert(0);
}
private template substInoutForm(T)
{
static if (is(T == struct) || is(T == class) || is(T == union) || is(T == interface))
{
alias substInoutForm = T; // prevent matching to the form of alias-this-ed type
}
else static if (is(T : V[K], K, V)) alias substInoutForm = substInout!V[substInout!K];
else static if (is(T : U[n], U, size_t n)) alias substInoutForm = substInout!U[n];
else static if (is(T : U[], U)) alias substInoutForm = substInout!U[];
else static if (is(T : U*, U)) alias substInoutForm = substInout!U*;
else alias substInoutForm = T;
}
/// used to declare an extern(D) function that is defined in a different module
template externDFunc(string fqn, T:FT*, FT) if (is(FT == function))
{
static if (is(FT RT == return) && is(FT Args == function))
{
import core.demangle : mangleFunc;
enum decl = {
string s = "extern(D) RT externDFunc(Args)";
foreach (attr; __traits(getFunctionAttributes, FT))
s ~= " " ~ attr;
return s ~ ";";
}();
pragma(mangle, mangleFunc!T(fqn)) mixin(decl);
}
else
static assert(0);
}
template staticIota(int beg, int end)
{
static if (beg + 1 >= end)
{
static if (beg >= end)
{
alias staticIota = AliasSeq!();
}
else
{
alias staticIota = AliasSeq!(+beg);
}
}
else
{
enum mid = beg + (end - beg) / 2;
alias staticIota = AliasSeq!(staticIota!(beg, mid), staticIota!(mid, end));
}
}
private struct __InoutWorkaroundStruct {}
@property T rvalueOf(T)(T val) { return val; }
@property T rvalueOf(T)(inout __InoutWorkaroundStruct = __InoutWorkaroundStruct.init);
@property ref T lvalueOf(T)(inout __InoutWorkaroundStruct = __InoutWorkaroundStruct.init);
// taken from std.traits.isAssignable
template isAssignable(Lhs, Rhs = Lhs)
{
enum isAssignable = __traits(compiles, lvalueOf!Lhs = rvalueOf!Rhs) && __traits(compiles, lvalueOf!Lhs = lvalueOf!Rhs);
}
// taken from std.traits.isInnerClass
template isInnerClass(T) if (is(T == class))
{
static if (is(typeof(T.outer)))
{
template hasOuterMember(T...)
{
static if (T.length == 0)
enum hasOuterMember = false;
else
enum hasOuterMember = T[0] == "outer" || hasOuterMember!(T[1 .. $]);
}
enum isInnerClass = __traits(isSame, typeof(T.outer), __traits(parent, T)) && !hasOuterMember!(__traits(allMembers, T));
}
else
enum isInnerClass = false;
}
template dtorIsNothrow(T)
{
enum dtorIsNothrow = is(typeof(function{T t=void;}) : void function() nothrow);
}
// taken from std.meta.allSatisfy
template allSatisfy(alias F, T...)
{
static foreach (Ti; T)
{
static if (!is(typeof(allSatisfy) == bool) && // not yet defined
!F!(Ti))
{
enum allSatisfy = false;
}
}
static if (!is(typeof(allSatisfy) == bool)) // if not yet defined
{
enum allSatisfy = true;
}
}
// taken from std.meta.anySatisfy
template anySatisfy(alias F, Ts...)
{
static foreach (T; Ts)
{
static if (!is(typeof(anySatisfy) == bool) && // not yet defined
F!T)
{
enum anySatisfy = true;
}
}
static if (!is(typeof(anySatisfy) == bool)) // if not yet defined
{
enum anySatisfy = false;
}
}
// simplified from std.traits.maxAlignment
template maxAlignment(U...)
{
static if (U.length == 0)
static assert(0);
else static if (U.length == 1)
enum maxAlignment = U[0].alignof;
else static if (U.length == 2)
enum maxAlignment = U[0].alignof > U[1].alignof ? U[0].alignof : U[1].alignof;
else
{
enum a = maxAlignment!(U[0 .. ($+1)/2]);
enum b = maxAlignment!(U[($+1)/2 .. $]);
enum maxAlignment = a > b ? a : b;
}
}
template classInstanceAlignment(T)
if (is(T == class))
{
alias classInstanceAlignment = maxAlignment!(void*, typeof(T.tupleof));
}
/// See $(REF hasElaborateMove, std,traits)
template hasElaborateMove(S)
{
static if (__traits(isStaticArray, S) && S.length)
{
enum bool hasElaborateMove = hasElaborateMove!(typeof(S.init[0]));
}
else static if (is(S == struct))
{
enum hasElaborateMove = (is(typeof(S.init.opPostMove(lvalueOf!S))) &&
!is(typeof(S.init.opPostMove(rvalueOf!S)))) ||
anySatisfy!(.hasElaborateMove, Fields!S);
}
else
{
enum bool hasElaborateMove = false;
}
}
// std.traits.hasElaborateDestructor
template hasElaborateDestructor(S)
{
static if (__traits(isStaticArray, S) && S.length)
{
enum bool hasElaborateDestructor = hasElaborateDestructor!(typeof(S.init[0]));
}
else static if (is(S == struct))
{
enum hasElaborateDestructor = __traits(hasMember, S, "__dtor")
|| anySatisfy!(.hasElaborateDestructor, Fields!S);
}
else
{
enum bool hasElaborateDestructor = false;
}
}
// std.traits.hasElaborateCopyDestructor
template hasElaborateCopyConstructor(S)
{
static if (__traits(isStaticArray, S) && S.length)
{
enum bool hasElaborateCopyConstructor = hasElaborateCopyConstructor!(typeof(S.init[0]));
}
else static if (is(S == struct))
{
enum hasElaborateCopyConstructor = __traits(hasCopyConstructor, S) || __traits(hasPostblit, S);
}
else
{
enum bool hasElaborateCopyConstructor = false;
}
}
@safe unittest
{
static struct S
{
int x;
this(return scope ref typeof(this) rhs) { }
this(int x, int y) {}
}
static assert(hasElaborateCopyConstructor!S);
static struct S2
{
int x;
this(int x, int y) {}
}
static assert(!hasElaborateCopyConstructor!S2);
static struct S3
{
int x;
this(return scope ref typeof(this) rhs, int x = 42) { }
this(int x, int y) {}
}
static assert(hasElaborateCopyConstructor!S3);
}
template hasElaborateAssign(S)
{
static if (__traits(isStaticArray, S) && S.length)
{
enum bool hasElaborateAssign = hasElaborateAssign!(typeof(S.init[0]));
}
else static if (is(S == struct))
{
enum hasElaborateAssign = is(typeof(S.init.opAssign(rvalueOf!S))) ||
is(typeof(S.init.opAssign(lvalueOf!S))) ||
anySatisfy!(.hasElaborateAssign, Fields!S);
}
else
{
enum bool hasElaborateAssign = false;
}
}
template hasIndirections(T)
{
static if (is(T == struct) || is(T == union))
enum hasIndirections = anySatisfy!(.hasIndirections, Fields!T);
else static if (__traits(isStaticArray, T) && is(T : E[N], E, size_t N))
enum hasIndirections = is(E == void) ? true : hasIndirections!E;
else static if (isFunctionPointer!T)
enum hasIndirections = false;
else
enum hasIndirections = isPointer!T || isDelegate!T || isDynamicArray!T ||
__traits(isAssociativeArray, T) || is (T == class) || is(T == interface);
}
template hasUnsharedIndirections(T)
{
static if (is(T == struct) || is(T == union))
enum hasUnsharedIndirections = anySatisfy!(.hasUnsharedIndirections, Fields!T);
else static if (is(T : E[N], E, size_t N))
enum hasUnsharedIndirections = is(E == void) ? false : hasUnsharedIndirections!E;
else static if (isFunctionPointer!T)
enum hasUnsharedIndirections = false;
else static if (isPointer!T)
enum hasUnsharedIndirections = !is(T : shared(U)*, U);
else static if (isDynamicArray!T)
enum hasUnsharedIndirections = !is(T : shared(V)[], V);
else static if (is(T == class) || is(T == interface))
enum hasUnsharedIndirections = !is(T : shared(W), W);
else
enum hasUnsharedIndirections = isDelegate!T || __traits(isAssociativeArray, T); // TODO: how to handle these?
}
enum bool isAggregateType(T) = is(T == struct) || is(T == union) ||
is(T == class) || is(T == interface);
enum bool isPointer(T) = is(T == U*, U) && !isAggregateType!T;
enum bool isDynamicArray(T) = is(DynamicArrayTypeOf!T) && !isAggregateType!T;
template OriginalType(T)
{
template Impl(T)
{
static if (is(T U == enum)) alias Impl = OriginalType!U;
else alias Impl = T;
}
alias OriginalType = ModifyTypePreservingTQ!(Impl, T);
}
template DynamicArrayTypeOf(T)
{
static if (is(AliasThisTypeOf!T AT) && !is(AT[] == AT))
alias X = DynamicArrayTypeOf!AT;
else
alias X = OriginalType!T;
static if (is(Unqual!X : E[], E) && !is(typeof({ enum n = X.length; })))
alias DynamicArrayTypeOf = X;
else
static assert(0, T.stringof ~ " is not a dynamic array");
}
private template AliasThisTypeOf(T)
if (isAggregateType!T)
{
alias members = __traits(getAliasThis, T);
static if (members.length == 1)
alias AliasThisTypeOf = typeof(__traits(getMember, T.init, members[0]));
else
static assert(0, T.stringof~" does not have alias this type");
}
template isFunctionPointer(T...)
if (T.length == 1)
{
static if (is(T[0] U) || is(typeof(T[0]) U))
{
static if (is(U F : F*) && is(F == function))
enum bool isFunctionPointer = true;
else
enum bool isFunctionPointer = false;
}
else
enum bool isFunctionPointer = false;
}
template isDelegate(T...)
if (T.length == 1)
{
static if (is(typeof(& T[0]) U : U*) && is(typeof(& T[0]) U == delegate))
{
// T is a (nested) function symbol.
enum bool isDelegate = true;
}
else static if (is(T[0] W) || is(typeof(T[0]) W))
{
// T is an expression or a type. Take the type of it and examine.
enum bool isDelegate = is(W == delegate);
}
else
enum bool isDelegate = false;
}
// std.meta.Filter
template Filter(alias pred, TList...)
{
static if (TList.length == 0)
{
alias Filter = AliasSeq!();
}
else static if (TList.length == 1)
{
static if (pred!(TList[0]))
alias Filter = AliasSeq!(TList[0]);
else
alias Filter = AliasSeq!();
}
else
{
alias Filter =
AliasSeq!(
Filter!(pred, TList[ 0 .. $/2]),
Filter!(pred, TList[$/2 .. $ ]));
}
}
// std.meta.staticMap
template staticMap(alias F, T...)
{
static if (T.length == 0)
{
alias staticMap = AliasSeq!();
}
else static if (T.length == 1)
{
alias staticMap = AliasSeq!(F!(T[0]));
}
else
{
alias staticMap =
AliasSeq!(
staticMap!(F, T[ 0 .. $/2]),
staticMap!(F, T[$/2 .. $ ]));
}
}
// std.exception.assertCTFEable
version (CoreUnittest) package(core)
void assertCTFEable(alias dg)()
{
static assert({ cast(void) dg(); return true; }());
cast(void) dg();
}
// std.traits.FunctionTypeOf
/*
Get the function type from a callable object `func`.
Using builtin `typeof` on a property function yields the types of the
property value, not of the property function itself. Still,
`FunctionTypeOf` is able to obtain function types of properties.
Note:
Do not confuse function types with function pointer types; function types are
usually used for compile-time reflection purposes.
*/
template FunctionTypeOf(func...)
if (func.length == 1 /*&& isCallable!func*/)
{
static if (is(typeof(& func[0]) Fsym : Fsym*) && is(Fsym == function) || is(typeof(& func[0]) Fsym == delegate))
{
alias FunctionTypeOf = Fsym; // HIT: (nested) function symbol
}
else static if (is(typeof(& func[0].opCall) Fobj == delegate))
{
alias FunctionTypeOf = Fobj; // HIT: callable object
}
else static if (is(typeof(& func[0].opCall) Ftyp : Ftyp*) && is(Ftyp == function))
{
alias FunctionTypeOf = Ftyp; // HIT: callable type
}
else static if (is(func[0] T) || is(typeof(func[0]) T))
{
static if (is(T == function))
alias FunctionTypeOf = T; // HIT: function
else static if (is(T Fptr : Fptr*) && is(Fptr == function))
alias FunctionTypeOf = Fptr; // HIT: function pointer
else static if (is(T Fdlg == delegate))
alias FunctionTypeOf = Fdlg; // HIT: delegate
else
static assert(0);
}
else
static assert(0);
}
@safe unittest
{
class C
{
int value() @property { return 0; }
}
static assert(is( typeof(C.value) == int ));
static assert(is( FunctionTypeOf!(C.value) == function ));
}
@system unittest
{
int test(int a);
int propGet() @property;
int propSet(int a) @property;
int function(int) test_fp;
int delegate(int) test_dg;
static assert(is( typeof(test) == FunctionTypeOf!(typeof(test)) ));
static assert(is( typeof(test) == FunctionTypeOf!test ));
static assert(is( typeof(test) == FunctionTypeOf!test_fp ));
static assert(is( typeof(test) == FunctionTypeOf!test_dg ));
alias int GetterType() @property;
alias int SetterType(int) @property;
static assert(is( FunctionTypeOf!propGet == GetterType ));
static assert(is( FunctionTypeOf!propSet == SetterType ));
interface Prop { int prop() @property; }
Prop prop;
static assert(is( FunctionTypeOf!(Prop.prop) == GetterType ));
static assert(is( FunctionTypeOf!(prop.prop) == GetterType ));
class Callable { int opCall(int) { return 0; } }
auto call = new Callable;
static assert(is( FunctionTypeOf!call == typeof(test) ));
struct StaticCallable { static int opCall(int) { return 0; } }
StaticCallable stcall_val;
StaticCallable* stcall_ptr;
static assert(is( FunctionTypeOf!stcall_val == typeof(test) ));
static assert(is( FunctionTypeOf!stcall_ptr == typeof(test) ));
interface Overloads
{
void test(string);
real test(real);
int test(int);
int test() @property;
}
alias ov = __traits(getVirtualFunctions, Overloads, "test");
alias F_ov0 = FunctionTypeOf!(ov[0]);
alias F_ov1 = FunctionTypeOf!(ov[1]);
alias F_ov2 = FunctionTypeOf!(ov[2]);
alias F_ov3 = FunctionTypeOf!(ov[3]);
static assert(is(F_ov0* == void function(string)));
static assert(is(F_ov1* == real function(real)));
static assert(is(F_ov2* == int function(int)));
static assert(is(F_ov3* == int function() @property));
alias F_dglit = FunctionTypeOf!((int a){ return a; });
static assert(is(F_dglit* : int function(int)));
}
// std.traits.ReturnType
/*
Get the type of the return value from a function,
a pointer to function, a delegate, a struct
with an opCall, a pointer to a struct with an opCall,
or a class with an `opCall`. Please note that $(D_KEYWORD ref)
is not part of a type, but the attribute of the function
(see template $(LREF functionAttributes)).
*/
template ReturnType(func...)
if (func.length == 1 /*&& isCallable!func*/)
{
static if (is(FunctionTypeOf!func R == return))
alias ReturnType = R;
else
static assert(0, "argument has no return type");
}
//
@safe unittest
{
int foo();
ReturnType!foo x; // x is declared as int
}
@safe unittest
{
struct G
{
int opCall (int i) { return 1;}
}
alias ShouldBeInt = ReturnType!G;
static assert(is(ShouldBeInt == int));
G g;
static assert(is(ReturnType!g == int));
G* p;
alias pg = ReturnType!p;
static assert(is(pg == int));
class C
{
int opCall (int i) { return 1;}
}
static assert(is(ReturnType!C == int));
C c;
static assert(is(ReturnType!c == int));
class Test
{
int prop() @property { return 0; }
}
alias R_Test_prop = ReturnType!(Test.prop);
static assert(is(R_Test_prop == int));
alias R_dglit = ReturnType!((int a) { return a; });
static assert(is(R_dglit == int));
}
// std.traits.Parameters
/*
Get, as a tuple, the types of the parameters to a function, a pointer
to function, a delegate, a struct with an `opCall`, a pointer to a
struct with an `opCall`, or a class with an `opCall`.
*/
template Parameters(func...)
if (func.length == 1 /*&& isCallable!func*/)
{
static if (is(FunctionTypeOf!func P == function))
alias Parameters = P;
else
static assert(0, "argument has no parameters");
}
//
@safe unittest
{
int foo(int, long);
void bar(Parameters!foo); // declares void bar(int, long);
void abc(Parameters!foo[1]); // declares void abc(long);
}
@safe unittest
{
int foo(int i, bool b) { return 0; }
static assert(is(Parameters!foo == AliasSeq!(int, bool)));
static assert(is(Parameters!(typeof(&foo)) == AliasSeq!(int, bool)));
struct S { real opCall(real r, int i) { return 0.0; } }
S s;
static assert(is(Parameters!S == AliasSeq!(real, int)));
static assert(is(Parameters!(S*) == AliasSeq!(real, int)));
static assert(is(Parameters!s == AliasSeq!(real, int)));
class Test
{
int prop() @property { return 0; }
}
alias P_Test_prop = Parameters!(Test.prop);
static assert(P_Test_prop.length == 0);
alias P_dglit = Parameters!((int a){});
static assert(P_dglit.length == 1);
static assert(is(P_dglit[0] == int));
}
// Return `true` if `Type` has `member` that evaluates to `true` in a static if condition
enum isTrue(Type, string member) = __traits(compiles, { static if (__traits(getMember, Type, member)) {} else static assert(0); });
unittest
{
static struct T
{
enum a = true;
enum b = false;
enum c = 1;
enum d = 45;
enum e = "true";
enum f = "";
enum g = null;
alias h = bool;
}
static assert( isTrue!(T, "a"));
static assert(!isTrue!(T, "b"));
static assert( isTrue!(T, "c"));
static assert( isTrue!(T, "d"));
static assert( isTrue!(T, "e"));
static assert( isTrue!(T, "f"));
static assert(!isTrue!(T, "g"));
static assert(!isTrue!(T, "h"));
}
|
D
|
// Written in the D programming language
/**
* Compress/decompress data using the $(LINK2 http://www._zlib.net, zlib library).
*
* References:
* $(LINK2 http://en.wikipedia.org/wiki/Zlib, Wikipedia)
* License:
* Public Domain
*
* Macros:
* WIKI = Phobos/StdZlib
*/
module std.zlib;
//debug=zlib; // uncomment to turn on debugging printf's
private import etc.c.zlib;
// Values for 'mode'
enum
{
Z_NO_FLUSH = 0,
Z_SYNC_FLUSH = 2,
Z_FULL_FLUSH = 3,
Z_FINISH = 4,
}
/*************************************
* Errors throw a ZlibException.
*/
class ZlibException : Exception
{
this(int errnum)
{ string msg;
switch (errnum)
{
case Z_STREAM_END: msg = "stream end"; break;
case Z_NEED_DICT: msg = "need dict"; break;
case Z_ERRNO: msg = "errno"; break;
case Z_STREAM_ERROR: msg = "stream error"; break;
case Z_DATA_ERROR: msg = "data error"; break;
case Z_MEM_ERROR: msg = "mem error"; break;
case Z_BUF_ERROR: msg = "buf error"; break;
case Z_VERSION_ERROR: msg = "version error"; break;
default: msg = "unknown error"; break;
}
super(msg);
}
}
/**************************************************
* Compute the Adler32 checksum of the data in buf[]. adler is the starting
* value when computing a cumulative checksum.
*/
uint adler32(uint adler, const(void)[] buf)
{
return etc.c.zlib.adler32(adler, cast(ubyte *)buf.ptr, buf.length);
}
unittest
{
static ubyte[] data = [1,2,3,4,5,6,7,8,9,10];
uint adler;
debug(zlib) printf("D.zlib.adler32.unittest\n");
adler = adler32(0u, cast(void[])data);
debug(zlib) printf("adler = %x\n", adler);
assert(adler == 0xdc0037);
}
/*********************************
* Compute the CRC32 checksum of the data in buf[]. crc is the starting value
* when computing a cumulative checksum.
*/
uint crc32(uint crc, const(void)[] buf)
{
return etc.c.zlib.crc32(crc, cast(ubyte *)buf.ptr, buf.length);
}
unittest
{
static ubyte[] data = [1,2,3,4,5,6,7,8,9,10];
uint crc;
debug(zlib) printf("D.zlib.crc32.unittest\n");
crc = crc32(0u, cast(void[])data);
debug(zlib) printf("crc = %x\n", crc);
assert(crc == 0x2520577b);
}
/*********************************************
* Compresses the data in srcbuf[] using compression _level level.
* The default value
* for level is 6, legal values are 1..9, with 1 being the least compression
* and 9 being the most.
* Returns the compressed data.
*/
const(void)[] compress(const(void)[] srcbuf, int level)
in
{
assert(-1 <= level && level <= 9);
}
body
{
int err;
ubyte[] destbuf;
uint destlen;
destlen = srcbuf.length + ((srcbuf.length + 1023) / 1024) + 12;
destbuf = new ubyte[destlen];
err = etc.c.zlib.compress2(destbuf.ptr, &destlen, cast(ubyte *)srcbuf, srcbuf.length, level);
if (err)
{ delete destbuf;
throw new ZlibException(err);
}
destbuf.length = destlen;
return destbuf;
}
/*********************************************
* ditto
*/
const(void)[] compress(const(void)[] buf)
{
return compress(buf, Z_DEFAULT_COMPRESSION);
}
/*********************************************
* Decompresses the data in srcbuf[].
* Params: destlen = size of the uncompressed data.
* It need not be accurate, but the decompression will be faster if the exact
* size is supplied.
* Returns: the decompressed data.
*/
const(void)[] uncompress(const(void)[] srcbuf, uint destlen = 0u, int winbits = 15)
{
int err;
ubyte[] destbuf;
if (!destlen)
destlen = srcbuf.length * 2 + 1;
while (1)
{
etc.c.zlib.z_stream zs;
destbuf = new ubyte[destlen];
zs.next_in = cast(ubyte*) srcbuf;
zs.avail_in = srcbuf.length;
zs.next_out = destbuf.ptr;
zs.avail_out = destlen;
err = etc.c.zlib.inflateInit2(&zs, winbits);
if (err)
{ delete destbuf;
throw new ZlibException(err);
}
err = etc.c.zlib.inflate(&zs, Z_NO_FLUSH);
switch (err)
{
case Z_OK:
etc.c.zlib.inflateEnd(&zs);
destlen = destbuf.length * 2;
continue;
case Z_STREAM_END:
destbuf.length = zs.total_out;
err = etc.c.zlib.inflateEnd(&zs);
if (err != Z_OK)
goto Lerr;
return destbuf;
default:
etc.c.zlib.inflateEnd(&zs);
Lerr:
delete destbuf;
throw new ZlibException(err);
}
}
}
unittest
{
ubyte[] src = cast(ubyte[])
"the quick brown fox jumps over the lazy dog\r
the quick brown fox jumps over the lazy dog\r
";
ubyte[] dst;
ubyte[] result;
//arrayPrint(src);
dst = cast(ubyte[])compress(cast(void[])src);
//arrayPrint(dst);
result = cast(ubyte[])uncompress(cast(void[])dst);
//arrayPrint(result);
assert(result == src);
}
/+
void arrayPrint(ubyte[] array)
{
//printf("array %p,%d\n", (void*)array, array.length);
for (int i = 0; i < array.length; i++)
{
printf("%02x ", array[i]);
if (((i + 1) & 15) == 0)
printf("\n");
}
printf("\n\n");
}
+/
/*********************************************
* Used when the data to be compressed is not all in one buffer.
*/
class Compress
{
private:
z_stream zs;
int level = Z_DEFAULT_COMPRESSION;
int inited;
void error(int err)
{
if (inited)
{ deflateEnd(&zs);
inited = 0;
}
throw new ZlibException(err);
}
public:
/**
* Construct. level is the same as for D.zlib.compress().
*/
this(int level)
in
{
assert(1 <= level && level <= 9);
}
body
{
this.level = level;
}
/// ditto
this()
{
}
~this()
{ int err;
if (inited)
{
inited = 0;
err = deflateEnd(&zs);
if (err)
error(err);
}
}
/**
* Compress the data in buf and return the compressed data.
* The buffers
* returned from successive calls to this should be concatenated together.
*/
const(void)[] compress(const(void)[] buf)
{ int err;
ubyte[] destbuf;
if (buf.length == 0)
return null;
if (!inited)
{
err = deflateInit(&zs, level);
if (err)
error(err);
inited = 1;
}
destbuf = new ubyte[zs.avail_in + buf.length];
zs.next_out = destbuf.ptr;
zs.avail_out = destbuf.length;
if (zs.avail_in)
buf = cast(void[])zs.next_in[0 .. zs.avail_in] ~ buf;
zs.next_in = cast(ubyte*) buf.ptr;
zs.avail_in = buf.length;
err = deflate(&zs, Z_NO_FLUSH);
if (err != Z_STREAM_END && err != Z_OK)
{ delete destbuf;
error(err);
}
destbuf.length = destbuf.length - zs.avail_out;
return destbuf;
}
/***
* Compress and return any remaining data.
* The returned data should be appended to that returned by compress().
* Params:
* mode = one of the following:
* $(DL
$(DT Z_SYNC_FLUSH )
$(DD Syncs up flushing to the next byte boundary.
Used when more data is to be compressed later on.)
$(DT Z_FULL_FLUSH )
$(DD Syncs up flushing to the next byte boundary.
Used when more data is to be compressed later on,
and the decompressor needs to be restartable at this
point.)
$(DT Z_FINISH)
$(DD (default) Used when finished compressing the data. )
)
*/
void[] flush(int mode = Z_FINISH)
in
{
assert(mode == Z_FINISH || mode == Z_SYNC_FLUSH || mode == Z_FULL_FLUSH);
}
body
{
void[] destbuf;
ubyte[512] tmpbuf = void;
int err;
if (!inited)
return null;
/* may be zs.avail_out+<some constant>
* zs.avail_out is set nonzero by deflate in previous compress()
*/
//tmpbuf = new void[zs.avail_out];
zs.next_out = tmpbuf.ptr;
zs.avail_out = tmpbuf.length;
while( (err = deflate(&zs, mode)) != Z_STREAM_END)
{
if (err == Z_OK)
{
if (zs.avail_out != 0 && mode != Z_FINISH)
break;
else if(zs.avail_out == 0)
{
destbuf ~= tmpbuf;
zs.next_out = tmpbuf.ptr;
zs.avail_out = tmpbuf.length;
continue;
}
err = Z_BUF_ERROR;
}
delete destbuf;
error(err);
}
destbuf ~= tmpbuf[0 .. (tmpbuf.length - zs.avail_out)];
if (mode == Z_FINISH)
{
err = deflateEnd(&zs);
inited = 0;
if (err)
error(err);
}
return destbuf;
}
}
/******
* Used when the data to be decompressed is not all in one buffer.
*/
class UnCompress
{
private:
z_stream zs;
int inited;
int done;
uint destbufsize;
void error(int err)
{
if (inited)
{ inflateEnd(&zs);
inited = 0;
}
throw new ZlibException(err);
}
public:
/**
* Construct. destbufsize is the same as for D.zlib.uncompress().
*/
this(uint destbufsize)
{
this.destbufsize = destbufsize;
}
/** ditto */
this()
{
}
~this()
{ int err;
if (inited)
{
inited = 0;
err = inflateEnd(&zs);
if (err)
error(err);
}
done = 1;
}
/**
* Decompress the data in buf and return the decompressed data.
* The buffers returned from successive calls to this should be concatenated
* together.
*/
const(void)[] uncompress(const(void)[] buf)
in
{
assert(!done);
}
body
{ int err;
ubyte[] destbuf;
if (buf.length == 0)
return null;
if (!inited)
{
err = inflateInit(&zs);
if (err)
error(err);
inited = 1;
}
if (!destbufsize)
destbufsize = buf.length * 2;
destbuf = new ubyte[zs.avail_in * 2 + destbufsize];
zs.next_out = destbuf.ptr;
zs.avail_out = destbuf.length;
if (zs.avail_in)
buf = cast(void[])zs.next_in[0 .. zs.avail_in] ~ buf;
zs.next_in = cast(ubyte*) buf;
zs.avail_in = buf.length;
err = inflate(&zs, Z_NO_FLUSH);
if (err != Z_STREAM_END && err != Z_OK)
{ delete destbuf;
error(err);
}
destbuf.length = destbuf.length - zs.avail_out;
return destbuf;
}
/**
* Decompress and return any remaining data.
* The returned data should be appended to that returned by uncompress().
* The UnCompress object cannot be used further.
*/
void[] flush()
in
{
assert(!done);
}
out
{
assert(done);
}
body
{
ubyte[] extra;
ubyte[] destbuf;
int err;
done = 1;
if (!inited)
return null;
L1:
destbuf = new ubyte[zs.avail_in * 2 + 100];
zs.next_out = destbuf.ptr;
zs.avail_out = destbuf.length;
err = etc.c.zlib.inflate(&zs, Z_NO_FLUSH);
if (err == Z_OK && zs.avail_out == 0)
{
extra ~= destbuf;
goto L1;
}
if (err != Z_STREAM_END)
{
delete destbuf;
if (err == Z_OK)
err = Z_BUF_ERROR;
error(err);
}
destbuf = destbuf.ptr[0 .. zs.next_out - destbuf.ptr];
err = etc.c.zlib.inflateEnd(&zs);
inited = 0;
if (err)
error(err);
if (extra.length)
destbuf = extra ~ destbuf;
return destbuf;
}
}
/* ========================== unittest ========================= */
private import std.stdio;
private import std.random;
unittest // by Dave
{
debug(zlib) printf("std.zlib.unittest\n");
bool CompressThenUncompress (ubyte[] src)
{
try {
ubyte[] dst = cast(ubyte[])std.zlib.compress(cast(void[])src);
double ratio = (dst.length / cast(double)src.length);
debug(zlib) writef("src.length: ", src.length, ", dst: ", dst.length, ", Ratio = ", ratio);
ubyte[] uncompressedBuf;
uncompressedBuf = cast(ubyte[])std.zlib.uncompress(cast(void[])dst);
assert(src.length == uncompressedBuf.length);
assert(src == uncompressedBuf);
}
catch {
debug(zlib) writefln(" ... Exception thrown when src.length = ", src.length, ".");
return false;
}
return true;
}
// smallish buffers
for(int idx = 0; idx < 25; idx++) {
char[] buf = new char[rand() % 100];
// Alternate between more & less compressible
foreach(inout char c; buf) c = ' ' + (rand() % (idx % 2 ? 91 : 2));
if(CompressThenUncompress(cast(ubyte[])buf)) {
debug(zlib) printf("; Success.\n");
} else {
return;
}
}
// larger buffers
for(int idx = 0; idx < 25; idx++) {
char[] buf = new char[rand() % 1000/*0000*/];
// Alternate between more & less compressible
foreach(inout char c; buf) c = ' ' + (rand() % (idx % 2 ? 91 : 10));
if(CompressThenUncompress(cast(ubyte[])buf)) {
debug(zlib) printf("; Success.\n");
} else {
return;
}
}
debug(zlib) printf("PASSED std.zlib.unittest\n");
}
unittest // by Artem Rebrov
{
Compress cmp = new Compress;
UnCompress decmp = new UnCompress;
const(void)[] input;
input = "tesatdffadf";
const(void)[] buf = cmp.compress(input);
buf ~= cmp.flush();
const(void)[] output = decmp.uncompress(buf);
//writefln("input = '%s'", cast(char[])input);
//writefln("output = '%s'", cast(char[])output);
assert( output[] == input[] );
}
|
D
|
/Users/sakaguchishinichi/notification/PandaNotif/Build/Intermediates/PandaNotif.build/Debug-iphonesimulator/PandaNotif.build/Objects-normal/x86_64/SoundTableViewController.o : /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/EditTableViewController.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/ViewController.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/PNDMinutesTableViewDataSource.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/CustomCell.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/PNDAlarmTableViewClass.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/SoundTableViewController.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/RepeatTableViewController.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/PNDAlarmEntity.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/AppDelegate.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/PNDTableViewDataSource.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/PNDAlarmCalculateClass.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/PNDAlarmFireClass.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Security.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/CoreImage.swiftmodule
/Users/sakaguchishinichi/notification/PandaNotif/Build/Intermediates/PandaNotif.build/Debug-iphonesimulator/PandaNotif.build/Objects-normal/x86_64/SoundTableViewController~partial.swiftmodule : /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/EditTableViewController.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/ViewController.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/PNDMinutesTableViewDataSource.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/CustomCell.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/PNDAlarmTableViewClass.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/SoundTableViewController.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/RepeatTableViewController.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/PNDAlarmEntity.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/AppDelegate.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/PNDTableViewDataSource.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/PNDAlarmCalculateClass.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/PNDAlarmFireClass.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Security.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/CoreImage.swiftmodule
/Users/sakaguchishinichi/notification/PandaNotif/Build/Intermediates/PandaNotif.build/Debug-iphonesimulator/PandaNotif.build/Objects-normal/x86_64/SoundTableViewController~partial.swiftdoc : /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/EditTableViewController.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/ViewController.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/PNDMinutesTableViewDataSource.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/CustomCell.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/PNDAlarmTableViewClass.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/SoundTableViewController.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/RepeatTableViewController.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/PNDAlarmEntity.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/AppDelegate.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/PNDTableViewDataSource.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/PNDAlarmCalculateClass.swift /Users/sakaguchishinichi/notification/PandaNotif/PandaNotif/PNDAlarmFireClass.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Security.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/CoreImage.swiftmodule
|
D
|
module voxelman.entity.plugininfo;
enum id = "voxelman.entity";
enum semver = "0.5.0";
enum deps = [];
enum clientdeps = [];
enum serverdeps = [];
|
D
|
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Asim Ullah - Ported for use in draw2d (c.f Bugzilla 71684). [Sep 10, 2004]
* Port to the D programming language:
* Frank Benoit <benoit@tionex.de>
*******************************************************************************/
module dwtx.draw2d.GridLayout;
import dwt.dwthelper.utils;
import dwtx.dwtxhelper.Collection;
import dwt.DWT;
import dwtx.draw2d.geometry.Dimension;
import dwtx.draw2d.geometry.Rectangle;
import dwtx.draw2d.AbstractLayout;
import dwtx.draw2d.IFigure;
import dwtx.draw2d.GridData;
/**
* Lays out children into a Grid arrangement in which overall aligment and
* spacing can be configured, as well as specfic layout requirements for the
* each individual member of the GridLayout. This layout is a Draw2D port of the
* swt GridLayout.
*
* <code>GridLayout</code> has a number of configuration fields, and the
* Figures it lays out can have an associated layout data object, called
* <code>GridData</code> (similar to the swt GridData object). The power of
* <code>GridLayout</code> lies in the ability to configure
* <code>GridData</code> for each Figure in the layout.
* <p>
* The following code creates a container Figure managed by a
* <code>GridLayout</code> with 2 columns, containing 3 RectangleFigure
* shapes, the last of which has been given further layout instructions. Note
* that it is the <code>GridLayout</code> method <code>setConstraint</code>
* that binds the child <code>Figure</code> to its layout
* <code>GridData</code> object.
*
* <pre>
* Figure container = new Figure();
* GridLayout gridLayout = new GridLayout();
* gridLayout.numColumns = 2;
* container.setLayout(gridLayout);
*
* Shape rect;
* rect = new RectangleFigure();
* container.add(rect);
*
* rect = new RectangleFigure();
* container.add(rect);
*
* rect = new RectangleFigure();
* GridData gridData = new GridData();
* gridData.widthHint = 150;
* layout.setConstraint(rect, gridData);
*
* container.add(rect);
* </pre>
*
* <p>
* The <code>numColumns</code> field is the most important field in a
* <code>GridLayout</code>. Widgets are laid out in columns from left to
* right, and a new row is created when <code>numColumns</code>+ 1 figures
* are added to the <code>Figure<code> parent container.
*
* @see GridData
*
*/
public class GridLayout : AbstractLayout {
/**
* numColumns specifies the number of cell columns in the layout.
*
* The default value is 1.
*/
public int numColumns = 1;
/**
* makeColumnsEqualWidth specifies whether all columns in the layout will be
* forced to have the same width.
*
* The default value is false.
*/
public bool makeColumnsEqualWidth = false;
/**
* marginWidth specifies the number of pixels of horizontal margin that will
* be placed along the left and right edges of the layout.
*
* The default value is 5.
*/
public int marginWidth = 5;
/**
* marginHeight specifies the number of pixels of vertical margin that will
* be placed along the top and bottom edges of the layout.
*
* The default value is 5.
*/
public int marginHeight = 5;
/**
* horizontalSpacing specifies the number of pixels between the right edge
* of one cell and the left edge of its neighbouring cell to the right.
*
* The default value is 5.
*/
public int horizontalSpacing = 5;
/**
* verticalSpacing specifies the number of pixels between the bottom edge of
* one cell and the top edge of its neighbouring cell underneath.
*
* The default value is 5.
*/
public int verticalSpacing = 5;
/** The layout contraints */
protected Map constraints;
/**
* Default Constructor
*/
public this() {
//super();
constraints = new HashMap();
}
/**
* Constructs a new instance of this class given the number of columns, and
* whether or not the columns should be forced to have the same width.
*
* @param numColumns
* the number of columns in the grid
* @param makeColumnsEqualWidth
* whether or not the columns will have equal width
*
*/
public this(int numColumns, bool makeColumnsEqualWidth) {
this.numColumns = numColumns;
this.makeColumnsEqualWidth = makeColumnsEqualWidth;
}
/**
* @param child
* @param wHint
* @param hHint
* @return the child size.
*/
protected Dimension getChildSize(IFigure child, int wHint, int hHint) {
return child.getPreferredSize(wHint, hHint);
}
GridData getData(IFigure[][] grid, int row, int column, int rowCount,
int columnCount, bool first) {
IFigure figure = grid[row][column];
if (figure !is null) {
GridData data = cast(GridData) getConstraint(figure);
int hSpan = Math.max(1, Math.min(data.horizontalSpan, columnCount));
int vSpan = Math.max(1, data.verticalSpan);
int i = first ? row + vSpan - 1 : row - vSpan + 1;
int j = first ? column + hSpan - 1 : column - hSpan + 1;
if (0 <= i && i < rowCount) {
if (0 <= j && j < columnCount) {
if (figure is grid[i][j])
return data;
}
}
}
return null;
}
void initChildren(IFigure container) {
List children = container.getChildren();
for (int i = 0; i < children.size(); i++) {
IFigure child = cast(IFigure) children.get(i);
if (child.getLayoutManager() is null)
child.setLayoutManager(this);
}
}
/*
* (non-Javadoc)
*
* @see dwtx.draw2d.AbstractLayout#calculatePreferredSize(dwtx.draw2d.IFigure,
* int, int)
*/
protected Dimension calculatePreferredSize(IFigure container, int wHint,
int hHint) {
Dimension size = layout(container, false, 0, 0, wHint, hHint, /* flushCache */
true);
if (wHint !is DWT.DEFAULT)
size.width = wHint;
if (hHint !is DWT.DEFAULT)
size.height = hHint;
return size;
}
/*
* (non-Javadoc)
*
* @see dwtx.draw2d.LayoutManager#layout(dwtx.draw2d.IFigure)
*/
public void layout(IFigure container) {
// initChildren( container);
Rectangle rect = container.getClientArea();
layout(container, true, rect.x, rect.y, rect.width, rect.height, /* flushCache */
true);
}
Dimension layout(IFigure container, bool move, int x, int y, int width,
int height, bool flushCache) {
if (numColumns < 1)
return new Dimension(marginWidth * 2, marginHeight * 2);
List children = container.getChildren();
for (int i = 0; i < children.size(); i++) {
IFigure child = cast(IFigure) children.get(i);
GridData data = cast(GridData) getConstraint(child);
if (data is null)
setConstraint(child, data = new GridData());
if (flushCache)
data.flushCache();
data.computeSize(child, flushCache);
}
/* Build the grid */
int row = 0, column = 0, rowCount = 0, columnCount = numColumns;
IFigure[][] grid = new IFigure[][](4,columnCount);
for (int i = 0; i < children.size(); i++) {
IFigure child = cast(IFigure) children.get(i);
GridData data = cast(GridData) getConstraint(child);
int hSpan = Math.max(1, Math.min(data.horizontalSpan, columnCount));
int vSpan = Math.max(1, data.verticalSpan);
while (true) {
int lastRow = row + vSpan;
if (lastRow >= grid.length) {
IFigure[][] newGrid = new IFigure[][](lastRow + 4, columnCount );
SimpleType!(IFigure[]).arraycopy(grid, 0, newGrid, 0, grid.length);
grid = newGrid;
}
if (grid[row] is null) {
grid[row] = new IFigure[columnCount];
}
while (column < columnCount && grid[row][column] !is null) {
column++;
}
int endCount = column + hSpan;
if (endCount <= columnCount) {
int index = column;
while (index < endCount && grid[row][index] is null) {
index++;
}
if (index is endCount)
break;
column = index;
}
if (column + hSpan >= columnCount) {
column = 0;
row++;
}
}
for (int j = 0; j < vSpan; j++) {
if (grid[row + j] is null) {
grid[row + j] = new IFigure[columnCount];
}
for (int k = 0; k < hSpan; k++) {
grid[row + j][column + k] = child;
}
}
rowCount = Math.max(rowCount, row + vSpan);
column += hSpan;
}
/* Column widths */
int availableWidth = width - horizontalSpacing * (columnCount - 1)
- marginWidth * 2;
int expandCount = 0;
int[] widths = new int[columnCount];
int[] minWidths = new int[columnCount];
bool[] expandColumn = new bool[columnCount];
for (int j = 0; j < columnCount; j++) {
for (int i = 0; i < rowCount; i++) {
GridData data = getData(grid, i, j, rowCount, columnCount, true);
if (data !is null) {
int hSpan = Math.max(1, Math.min(data.horizontalSpan,
columnCount));
if (hSpan is 1) {
int w = data.cacheWidth + data.horizontalIndent;
widths[j] = Math.max(widths[j], w);
if (data.grabExcessHorizontalSpace) {
if (!expandColumn[j])
expandCount++;
expandColumn[j] = true;
}
if (data.widthHint !is DWT.DEFAULT
|| !data.grabExcessHorizontalSpace) {
minWidths[j] = Math.max(minWidths[j], w);
}
}
}
}
for (int i = 0; i < rowCount; i++) {
GridData data = getData(grid, i, j, rowCount, columnCount,
false);
if (data !is null) {
int hSpan = Math.max(1, Math.min(data.horizontalSpan,
columnCount));
if (hSpan > 1) {
int spanWidth = 0, spanMinWidth = 0, spanExpandCount = 0;
for (int k = 0; k < hSpan; k++) {
spanWidth += widths[j - k];
spanMinWidth += minWidths[j - k];
if (expandColumn[j - k])
spanExpandCount++;
}
if (data.grabExcessHorizontalSpace
&& spanExpandCount is 0) {
expandCount++;
expandColumn[j] = true;
}
int w = data.cacheWidth + data.horizontalIndent
- spanWidth - (hSpan - 1) * horizontalSpacing;
if (w > 0) {
if (spanExpandCount is 0) {
widths[j] += w;
} else {
int delta = w / spanExpandCount;
int remainder = w % spanExpandCount, last = -1;
for (int k = 0; k < hSpan; k++) {
if (expandColumn[j - k]) {
widths[last = j - k] += delta;
}
}
if (last > -1)
widths[last] += remainder;
}
}
if (data.widthHint !is DWT.DEFAULT
|| !data.grabExcessHorizontalSpace) {
w = data.cacheWidth + data.horizontalIndent
- spanMinWidth - (hSpan - 1)
* horizontalSpacing;
if (w > 0) {
if (spanExpandCount is 0) {
minWidths[j] += w;
} else {
int delta = w / spanExpandCount;
int remainder = w % spanExpandCount, last = -1;
for (int k = 0; k < hSpan; k++) {
if (expandColumn[j - k]) {
minWidths[last = j - k] += delta;
}
}
if (last > -1)
minWidths[last] += remainder;
}
}
}
}
}
}
}
if (makeColumnsEqualWidth) {
int minColumnWidth = 0;
int columnWidth = 0;
for (int i = 0; i < columnCount; i++) {
minColumnWidth = Math.max(minColumnWidth, minWidths[i]);
columnWidth = Math.max(columnWidth, widths[i]);
}
columnWidth = width is DWT.DEFAULT || expandCount is 0 ? columnWidth
: Math.max(minColumnWidth, availableWidth / columnCount);
for (int i = 0; i < columnCount; i++) {
expandColumn[i] = expandCount > 0;
widths[i] = columnWidth;
}
} else {
if (width !is DWT.DEFAULT && expandCount > 0) {
int totalWidth = 0;
for (int i = 0; i < columnCount; i++) {
totalWidth += widths[i];
}
int count = expandCount;
int delta = (availableWidth - totalWidth) / count;
int remainder = (availableWidth - totalWidth) % count;
int last = -1;
while (totalWidth !is availableWidth) {
for (int j = 0; j < columnCount; j++) {
if (expandColumn[j]) {
if (widths[j] + delta > minWidths[j]) {
widths[last = j] = widths[j] + delta;
} else {
widths[j] = minWidths[j];
expandColumn[j] = false;
count--;
}
}
}
if (last > -1)
widths[last] += remainder;
for (int j = 0; j < columnCount; j++) {
for (int i = 0; i < rowCount; i++) {
GridData data = getData(grid, i, j, rowCount,
columnCount, false);
if (data !is null) {
int hSpan = Math.max(1, Math.min(
data.horizontalSpan, columnCount));
if (hSpan > 1) {
if (data.widthHint !is DWT.DEFAULT
|| !data.grabExcessHorizontalSpace) {
int spanWidth = 0, spanExpandCount = 0;
for (int k = 0; k < hSpan; k++) {
spanWidth += widths[j - k];
if (expandColumn[j - k])
spanExpandCount++;
}
int w = data.cacheWidth
+ data.horizontalIndent
- spanWidth - (hSpan - 1)
* horizontalSpacing;
if (w > 0) {
if (spanExpandCount is 0) {
widths[j] += w;
} else {
int delta2 = w
/ spanExpandCount;
int remainder2 = w
% spanExpandCount, last2 = -1;
for (int k = 0; k < hSpan; k++) {
if (expandColumn[j - k]) {
widths[last2 = j - k] += delta2;
}
}
if (last2 > -1)
widths[last2] += remainder2;
}
}
}
}
}
}
}
if (count is 0)
break;
totalWidth = 0;
for (int i = 0; i < columnCount; i++) {
totalWidth += widths[i];
}
delta = (availableWidth - totalWidth) / count;
remainder = (availableWidth - totalWidth) % count;
last = -1;
}
}
}
/* Wrapping */
GridData[] flush = null;
int flushLength = 0;
if (width !is DWT.DEFAULT) {
for (int j = 0; j < columnCount; j++) {
for (int i = 0; i < rowCount; i++) {
GridData data = getData(grid, i, j, rowCount, columnCount,
false);
if (data !is null) {
if (data.heightHint is DWT.DEFAULT) {
IFigure child = grid[i][j];
// TEMPORARY CODE
int hSpan = Math.max(1, Math.min(
data.horizontalSpan, columnCount));
int currentWidth = 0;
for (int k = 0; k < hSpan; k++) {
currentWidth += widths[j - k];
}
currentWidth += (hSpan - 1) * horizontalSpacing
- data.horizontalIndent;
if ((currentWidth !is data.cacheWidth && data.horizontalAlignment is DWT.FILL)
|| (data.cacheWidth > currentWidth)) {
int trim = 0;
/*
* // *Note*: Left this in place from DWT //
* GridLayout. Not sure if Draw2D Borders or //
* Scrollbars 'trim' will need to be takeninto
* account.
*
* if (child instanceof Group) { Group g
* =(Group)child; trim = g.getSize ().x -
* g.getClientArea ().width; } else if (child
* instanceof Scrollable) { Rectangle rect =
* ((Scrollable) child).computeTrim (0, 0, 0,0);
* trim = rect.width; } else { trim =
* child.getBorderWidth () * 2; }
*/
int oldWidthHint = data.widthHint;
data.widthHint = Math.max(0, currentWidth
- trim);
data.cacheWidth = data.cacheHeight = DWT.DEFAULT;
data.computeSize(child, false);
data.widthHint = oldWidthHint;
if (flush is null)
flush = new GridData[children.size()];
flush[flushLength++] = data;
}
}
}
}
}
}
/* Row heights */
int availableHeight = height - verticalSpacing * (rowCount - 1)
- marginHeight * 2;
expandCount = 0;
int[] heights = new int[rowCount];
int[] minHeights = new int[rowCount];
bool[] expandRow = new bool[rowCount];
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < columnCount; j++) {
GridData data = getData(grid, i, j, rowCount, columnCount, true);
if (data !is null) {
int vSpan = Math.max(1, Math.min(data.verticalSpan,
rowCount));
if (vSpan is 1) {
int h = data.cacheHeight; // + data.verticalIndent;
heights[i] = Math.max(heights[i], h);
if (data.grabExcessVerticalSpace) {
if (!expandRow[i])
expandCount++;
expandRow[i] = true;
}
if (data.heightHint !is DWT.DEFAULT
|| !data.grabExcessVerticalSpace) {
minHeights[i] = Math.max(minHeights[i], h);
}
}
}
}
for (int j = 0; j < columnCount; j++) {
GridData data = getData(grid, i, j, rowCount, columnCount,
false);
if (data !is null) {
int vSpan = Math.max(1, Math.min(data.verticalSpan,
rowCount));
if (vSpan > 1) {
int spanHeight = 0, spanMinHeight = 0, spanExpandCount = 0;
for (int k = 0; k < vSpan; k++) {
spanHeight += heights[i - k];
spanMinHeight += minHeights[i - k];
if (expandRow[i - k])
spanExpandCount++;
}
if (data.grabExcessVerticalSpace
&& spanExpandCount is 0) {
expandCount++;
expandRow[i] = true;
}
int h = data.cacheHeight - spanHeight - (vSpan - 1)
* verticalSpacing; // + data.verticalalIndent
if (h > 0) {
if (spanExpandCount is 0) {
heights[i] += h;
} else {
int delta = h / spanExpandCount;
int remainder = h % spanExpandCount, last = -1;
for (int k = 0; k < vSpan; k++) {
if (expandRow[i - k]) {
heights[last = i - k] += delta;
}
}
if (last > -1)
heights[last] += remainder;
}
}
if (data.heightHint !is DWT.DEFAULT
|| !data.grabExcessVerticalSpace) {
h = data.cacheHeight - spanMinHeight - (vSpan - 1)
* verticalSpacing; // + data.verticalIndent
if (h > 0) {
if (spanExpandCount is 0) {
minHeights[i] += h;
} else {
int delta = h / spanExpandCount;
int remainder = h % spanExpandCount, last = -1;
for (int k = 0; k < vSpan; k++) {
if (expandRow[i - k]) {
minHeights[last = i - k] += delta;
}
}
if (last > -1)
minHeights[last] += remainder;
}
}
}
}
}
}
}
if (height !is DWT.DEFAULT && expandCount > 0) {
int totalHeight = 0;
for (int i = 0; i < rowCount; i++) {
totalHeight += heights[i];
}
int count = expandCount;
int delta = (availableHeight - totalHeight) / count;
int remainder = (availableHeight - totalHeight) % count;
int last = -1;
while (totalHeight !is availableHeight) {
for (int i = 0; i < rowCount; i++) {
if (expandRow[i]) {
if (heights[i] + delta > minHeights[i]) {
heights[last = i] = heights[i] + delta;
} else {
heights[i] = minHeights[i];
expandRow[i] = false;
count--;
}
}
}
if (last > -1)
heights[last] += remainder;
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < columnCount; j++) {
GridData data = getData(grid, i, j, rowCount,
columnCount, false);
if (data !is null) {
int vSpan = Math.max(1, Math.min(data.verticalSpan,
rowCount));
if (vSpan > 1) {
if (data.heightHint !is DWT.DEFAULT
|| !data.grabExcessVerticalSpace) {
int spanHeight = 0, spanExpandCount = 0;
for (int k = 0; k < vSpan; k++) {
spanHeight += heights[i - k];
if (expandRow[i - k])
spanExpandCount++;
}
int h = data.cacheHeight - spanHeight
- (vSpan - 1) * verticalSpacing; // +
// data.verticalIndent
if (h > 0) {
if (spanExpandCount is 0) {
heights[i] += h;
} else {
int delta2 = h / spanExpandCount;
int remainder2 = h
% spanExpandCount, last2 = -1;
for (int k = 0; k < vSpan; k++) {
if (expandRow[i - k]) {
heights[last2 = i - k] += delta2;
}
}
if (last2 > -1)
heights[last2] += remainder2;
}
}
}
}
}
}
}
if (count is 0)
break;
totalHeight = 0;
for (int i = 0; i < rowCount; i++) {
totalHeight += heights[i];
}
delta = (availableHeight - totalHeight) / count;
remainder = (availableHeight - totalHeight) % count;
last = -1;
}
}
/* Position the IFigures */
if (move) {
int gridY = y + marginHeight;
for (int i = 0; i < rowCount; i++) {
int gridX = x + marginWidth;
for (int j = 0; j < columnCount; j++) {
GridData data = getData(grid, i, j, rowCount, columnCount,
true);
if (data !is null) {
int hSpan = Math.max(1, Math.min(data.horizontalSpan,
columnCount));
int vSpan = Math.max(1, data.verticalSpan);
int cellWidth = 0, cellHeight = 0;
for (int k = 0; k < hSpan; k++) {
cellWidth += widths[j + k];
}
for (int k = 0; k < vSpan; k++) {
cellHeight += heights[i + k];
}
cellWidth += horizontalSpacing * (hSpan - 1);
int childX = gridX + data.horizontalIndent;
int childWidth = Math.min(data.cacheWidth, cellWidth);
switch (data.horizontalAlignment) {
case DWT.CENTER:
case GridData.CENTER:
childX = gridX
+ Math.max(0, (cellWidth - childWidth) / 2);
break;
case DWT.RIGHT:
case DWT.END:
case GridData.END:
childX = gridX
+ Math.max(0, cellWidth - childWidth);
break;
case DWT.FILL:
childWidth = cellWidth - data.horizontalIndent;
break;
default:
}
cellHeight += verticalSpacing * (vSpan - 1);
int childY = gridY; // + data.verticalIndent;
int childHeight = Math
.min(data.cacheHeight, cellHeight);
switch (data.verticalAlignment) {
case DWT.CENTER:
case GridData.CENTER:
childY = gridY
+ Math.max(0,
(cellHeight - childHeight) / 2);
break;
case DWT.BOTTOM:
case DWT.END:
case GridData.END:
childY = gridY
+ Math.max(0, cellHeight - childHeight);
break;
case DWT.FILL:
childHeight = cellHeight; // -
// data.verticalIndent;
break;
default:
}
IFigure child = grid[i][j];
if (child !is null) {
// following param could be replaced by
// Rectangle.SINGLETON
child.setBounds(new Rectangle(childX, childY,
childWidth, childHeight));
}
}
gridX += widths[j] + horizontalSpacing;
}
gridY += heights[i] + verticalSpacing;
}
}
// clean up cache
for (int i = 0; i < flushLength; i++) {
flush[i].cacheWidth = flush[i].cacheHeight = -1;
}
int totalDefaultWidth = 0;
int totalDefaultHeight = 0;
for (int i = 0; i < columnCount; i++) {
totalDefaultWidth += widths[i];
}
for (int i = 0; i < rowCount; i++) {
totalDefaultHeight += heights[i];
}
totalDefaultWidth += horizontalSpacing * (columnCount - 1)
+ marginWidth * 2;
totalDefaultHeight += verticalSpacing * (rowCount - 1) + marginHeight
* 2;
return new Dimension(totalDefaultWidth, totalDefaultHeight);
}
/*
* (non-Javadoc)
*
* @see dwtx.draw2d.LayoutManager#getConstraint(dwtx.draw2d.IFigure)
*/
public Object getConstraint(IFigure child) {
return constraints.get(cast(Object)child);
}
/**
* Sets the layout constraint of the given figure. The constraints can only
* be of type {@link GridData}.
*
* @see LayoutManager#setConstraint(IFigure, Object)
*/
public void setConstraint(IFigure figure, Object newConstraint) {
super.setConstraint(figure, newConstraint);
if (newConstraint !is null) {
constraints.put(cast(Object)figure, newConstraint);
}
}
}
|
D
|
module sidal.parser;
import std.algorithm;
import std.range : ElementType, isInputRange;
import std.stdio : File;
enum SourceType
{
file,
string,
generic
}
struct GenericSource
{
alias Empty = bool function(void*) nothrow @nogc;
alias Fill = Throwable function(ref GenericSource, void*, ref char[]) nothrow @nogc;
alias Finalize = void function(void*) nothrow @nogc;
enum max_data_size = 32;
void[max_data_size] data_store;
size_t used;
Empty rEmpty;
Fill rFill;
Finalize rFinalize;
this(T)(auto ref T t) if(isInputRange!T && is(ElementType!T == char))
{
*cast(T*)data_store.ptr = t;
static Throwable range_fill(T* range, ref char[] toFill)
{
if(range.empty) return null;
try
{
foreach(i, ref c; toFill)
{
c = range.token;
range.popFront();
if(range.empty)
{
toFill.length = i + 1;
break;
}
}
}
catch(Throwable t)
{
return t;
}
return null;
}
static bool range_empty(T* range)
{
return range.empty;
}
static void range_finalize(T* range)
{
static if(__traits(compiles, range.__dtor()))
range.__dtor();
}
rEmpty = cast(Empty)&range_empty;
rFill = cast(Fill)&range_fill;
rFinalize = cast(Finalize)&range_finalize;
}
this(T)(auto ref T t) if(isInputRange!T && is(ElementType!T == char[]) && T.sizeof <= max_data_size)
{
*cast(T*)data_store.ptr = t;
static Throwable range_fill(ref GenericSource this_, T* range, ref char[] toFill)
{
if(range.empty) return null;
try
{
size_t filled = 0, size = 0;
do
{
size = min(range.token.length - this_.used, toFill.length - filled);
toFill[filled .. filled + size] = range.token[this_.used .. this_.used + size];
this_.used += size;
filled += size;
if(this_.used >= range.token.length)
{
this_.used = 0;
range.popFront();
if(range.empty)
break;
}
}
while(size > 0);
toFill = toFill[0 .. filled];
}
catch(Throwable t)
{
return t;
}
return null;
}
static bool range_empty(T* range)
{
return range.empty;
}
static void range_finalize(T* range)
{
static if(__traits(compiles, range.__dtor()))
{
range.__dtor();
}
}
rEmpty = cast(Empty)&range_empty;
rFill = cast(Fill)&range_fill;
rFinalize = cast(Finalize)&range_finalize;
}
void finalize() { return rFinalize(data_store.ptr); }
nothrow @nogc:
bool empty() { return rEmpty(data_store.ptr); }
Throwable fill(ref char[] data) { return rFill(this, data_store.ptr, data); }
}
struct FileSource
{
private:
File file;
bool empty;
public:
this(File f)
{
file = f;
empty = !file.isOpen;
}
nothrow:
Throwable finalize()
{
try
{
file.detach();
}
catch(Throwable t)
{
return t;
}
return null;
}
Throwable fill(ref char[] toFill)
{
if(empty) return null;
try
{
toFill = file.rawRead(toFill);
if (toFill.length == 0)
{
file.detach();
empty = true;
}
}
catch(Throwable t)
{
return t;
}
return null;
}
}
struct StringSource
{
private const(char)[] front;
private bool inplace;
this(char[] str)
{
this.front = str;
auto p = &str[$ - 1];
if(*p++ == '\0' || *p == '\0')
inplace = true;
}
this(const(char)[] str)
{
this.front = str;
this.inplace = false;
}
nothrow:
bool empty() { return front.length == 0; }
Throwable fill(ref char[] toFill)
{
if(empty) return null;
if(inplace)
{
toFill = cast(char[])front;
front = front[$ .. $];
return null;
}
size_t size = min(toFill.length, front.length);
toFill[0 .. size] = front[0 .. size];
toFill = toFill[0 .. size];
front = front[size .. $];
return null;
}
}
enum TokenTag : ubyte
{
type,
name,
ident,
divider,
string,
floating,
integer,
objectStart,
objectEnd,
itemDivider,
error
}
struct SidalToken
{
TokenTag tag;
union
{
char[] value;
double floating;
ulong integer;
size_t level;
Throwable error;
}
}
struct SidalParser
{
enum terminator = '\0';
SourceType type;
//Workaround for union. Destructor in file prevents us from using it properly :S
//union
//{
// FileSource chunk;
// StringSource string;
// GenericSource generic
//}
void[max(FileSource.sizeof, StringSource.sizeof, GenericSource.sizeof)] range_data;
void chunk(ref FileSource range) { *(cast(FileSource*)range_data) = range; }
void string(ref StringSource range) { *(cast(StringSource*)range_data) = range; }
void generic(ref GenericSource range) { *cast(GenericSource*)range_data = range; }
nothrow FileSource* chunk() { return cast(FileSource*)range_data.ptr; }
nothrow StringSource* string() { return cast(StringSource*)range_data.ptr; }
nothrow GenericSource* generic() { return cast(GenericSource*)range_data.ptr; }
char[] buffer;
char* bptr;
size_t length;
bool inplace;
size_t level, lines, column;
SidalToken token;
bool empty;
this(File file, char[] buffer)
{
this(FileSource(file), buffer);
}
this(const(char)[] s, char[] buffer)
{
this(StringSource(s), buffer);
}
this(Range)(Range range, char[] buffer) if(isInputRange!Range)
{
this(GenericSource!Range(range), buffer);
}
this(FileSource range, char[] buffer)
{
this.type = SourceType.file;
this.chunk = range;
this.buffer = buffer;
this.level = this.length = this.column = 0;
this.empty = range.empty;
if(!empty)
{
nextBuffer();
if(token.tag == TokenTag.error)
throw token.error;
popFront();
}
}
this(StringSource range, char[] buffer)
{
this.type = SourceType.string;
this.string = range;
this.buffer = buffer;
this.level = this.length = this.column = 0;
this.empty = range.empty;
if(!empty)
{
nextBuffer();
if(token.tag == TokenTag.error)
throw token.error;
popFront();
}
}
this(GenericSource range, char[] buffer)
{
this.type = SourceType.generic;
this.generic = range;
this.buffer = buffer;
this.level = this.length = this.column = 0;
this.empty = range.empty;
if(!empty)
{
nextBuffer();
if(token.tag == TokenTag.error)
throw token.error;
popFront();
}
}
~this()
{
switch(type)
{
case SourceType.file:
chunk.finalize();
break;
case SourceType.generic:
generic.finalize();
break;
default: break;
}
}
nothrow:
void popFront()
{
outer:
for(;;bptr++)
retry:
switch(*bptr)
{
case '\n':
lines++; column = 0;
break;
case ' ': case '\t': case '\r': break;
case ',':
token.tag = TokenTag.divider;
token.level = level;
bptr++;
break outer;
case '(':
token.tag = TokenTag.objectStart;
token.level = level++;
bptr++;
break outer;
case ')':
token.tag = TokenTag.objectEnd;
token.level = --level;
bptr++;
break outer;
case ':':
token.tag = TokenTag.itemDivider;
token.level = level;
bptr++;
break outer;
case '"':
bptr++;
parseString(bptr);
return;
case '-':
bptr++;
return parseNumber(-1);
case '+':
bptr++;
goto numberStart;
case '0': .. case '9':
case '.':
numberStart:
return parseNumber(1);
case 'a': .. case 'z':
case 'A': .. case 'Z':
case '_':
//We parse an identifier name or type
return parseType(bptr);
case terminator:
if(nextBuffer)
goto retry;
return;
default: makeError(); return;
}
}
bool getData(size_t size, ref char[] data)
{
Throwable t;
final switch(type)
{
case SourceType.file: empty = chunk.empty; t = chunk.fill(data); break;
case SourceType.string: empty = string.empty; t = string.fill(data); break;
case SourceType.generic: empty = generic.empty; t = generic.fill(data); break;
}
data.ptr[data.length] = '\0';
bptr = data.ptr;
length = data.length + size;
column += length;
if(t)
{
token.tag = TokenTag.error;
token.error = t;
return empty;
}
return !empty;
}
bool nextBuffer()
{
char[] data = buffer[0 .. $ - 1];
return getData(0, data);
}
bool moveBuffer(ref char* start)
{
if(start < buffer.ptr)
{
int i;
return false;
}
size_t offset = start - buffer.ptr;
size_t size = length - offset;
import std.c.string;
memmove(buffer.ptr, start, size);
char[] data = buffer[size .. $ - 1];
bool res = getData(size, data);
start = buffer.ptr;
return res;
}
void parseString(char* b)
{
stringOuter:
for(;; bptr++)
{
stringRetry:
switch(*bptr)
{
case '"':
token.tag = TokenTag.string;
token.value = b[0 .. bptr - b];
bptr++;
return;
case terminator:
if(!moveBuffer(b))
{
if(token.tag == TokenTag.error)
return;
break stringOuter;
}
goto stringRetry;
default: break;
}
}
makeError();
}
void parseHex(int sign, ref ulong value)
{
for(;; bptr++)
{
hexRetry:
if(*bptr >= '0' && *bptr <= '9')
value *= 0x10 + *bptr - '0';
else if((*bptr | 0x20) >= 'a' && (*bptr | 0x20) <= 'f')
value *= 0x10 + (*bptr | 0x20) - 'a';
else if(*bptr == terminator)
{
if(!nextBuffer)
{
if(token.tag == TokenTag.error)
return;
break;
}
goto hexRetry;
}
else
break;
}
token.tag = TokenTag.integer;
token.integer = value;
}
__gshared static double[20] powE =
[10e-1, 10e-2, 10e-3, 10e-4, 10e-5, 10e-6, 10e-7, 10e-8, 10e-9, 10e-10,
10e-11, 10e-12, 10e-13, 10e-14, 10e-15, 10e-16, 10e-17, 10e-18, 10e-19, 10e-20];
void parseFloat(int sign, ref ulong value)
{
char* b = bptr;
double begin = value;
value = 0;
for(;;bptr++)
{
floatRetry:
if(*bptr >= '0' && *bptr <= '9')
value = value * 10 + *bptr - '0';
else if(*bptr == terminator)
{
if(!moveBuffer(b))
{
if(token.tag == TokenTag.error)
return;
break;
}
goto floatRetry;
}
else break;
}
token.tag = TokenTag.floating;
token.floating = (begin + (cast(double)value) * powE[bptr - b]) * sign;
}
import std.c.stdio;
void parseNumber(int sign)
{
ulong value = 0;
for(;;bptr++)
{
numberRetry:
if(*bptr >= '0' && *bptr <= '9')
value = value * 10 + *bptr - '0';
else if(*bptr == terminator)
{
if(!nextBuffer)
{
if(token.tag == TokenTag.error)
return;
break;
}
goto numberRetry;
}
else
break;
}
switch(*bptr)
{
default: break;
case 'x' : case 'X':
bptr++;
value = 0;
parseHex(sign, value);
return;
case '.':
bptr++;
parseFloat(sign, value);
return;
}
token.tag = TokenTag.integer;
token.integer = value * sign;
return;
}
//Types:
// ident(([( )*])* / ([( )*ident( )*])*)*
//Examples: Simple:
// float2
// float2[ ]
// int[ string]
// int[ int[ string][]]
// Examples: hard (look after whitespace label)
// float2 [ ]
// float2 [ string ] [ ]
void parseType(char* b)
{
uint lbracks = 0, rbracks = 0;
typeOuter:
for(;;bptr++)
typeRetry:
{
switch(*bptr)
{
case terminator:
if(!moveBuffer(b))
{
if(token.tag == TokenTag.error)
return;
break typeOuter;
}
else
goto typeRetry;
default:
break typeOuter;
case '\n': lines++; column = 0; goto case;
case '\t': case '\r': case ' ': break typeOuter;
case ']':
if(lbracks == rbracks)
goto typeFail;
rbracks++;
break;
case '[': lbracks++; break;
case '0': .. case '9':
case 'a': .. case 'z':
case 'A': .. case 'Z':
case '_':
break;
}
}
if(lbracks != rbracks || (rbracks > 0 && bptr[-1] != ']'))
goto typeFail;
token.value = b[0 .. bptr - b];
for(;; bptr++)
{
typeRetry2:
switch(*bptr)
{
case terminator:
if(!moveBuffer(b))
{
//Last thing in the stream.
//It can only be an ident here.
//If it's not then the stream is wrong anyway!
token.tag = TokenTag.ident;
return;
}
else
goto typeRetry2;
default:
goto typeFail;
case '\n': lines++; column = 0; break;
case ' ': case '\t': case '\r': break;
case '=':
token.tag = TokenTag.name;
bptr++;
return;
case ',': case ')':
token.tag = TokenTag.ident;
return;
case 'a': .. case 'z':
case 'A': .. case 'Z':
case '_':
case '(':
token.tag = TokenTag.type;
return;
}
}
typeFail:
makeError();
return;
}
void makeError()
{
//assert(false);
//token = sidalToken(TokenTag.error, 0);
token.tag = TokenTag.error;
}
@disable this(this);
}
|
D
|
*
*
0
2
1
*
|
D
|
get or gather together
call for and obtain payment of
assemble or get together
get or bring together
gather or collect
brought together in one place
in full control of your faculties
|
D
|
private
{
alias ushort Base;
alias Base[] Genome;
alias void function() Behavior;
@safe Genome mutate(const Genome genome)
{
return genome.dup;
}
Behavior compileGenome(const Genome genome)
{
return null;
}
}
class Organism
{
const Behavior behavior;
this(const Genome parent)
{
this.behavior = compileGenome(mutate(parent));
}
}
|
D
|
/Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/Service.build/Environment/Environment.swift.o : /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/ServiceID.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Utilities/Deprecated.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/Service.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/ServiceCache.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Utilities/Extendable.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/ServiceType.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Config/Config.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Provider/Provider.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Container/Container.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Container/SubContainer.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Container/BasicSubContainer.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Container/BasicContainer.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Utilities/ServiceError.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Container/ContainerAlias.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/Services.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Utilities/Exports.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Environment/Environment.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/ServiceFactory.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/BasicServiceFactory.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/TypeServiceFactory.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/NIO.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/Async.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/NIOConcurrencyHelpers.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/NIOFoundationCompat.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOAtomics/include/cpp_magic.h /Users/godemodegame/Desktop/ATMApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOLinux/include/ifaddrs-android.h /Users/godemodegame/Desktop/ATMApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIODarwin/include/CNIODarwin.h /Users/godemodegame/Desktop/ATMApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/godemodegame/Desktop/ATMApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOLinux/include/CNIOLinux.h /Users/godemodegame/Desktop/ATMApp/.build/checkouts/swift-nio-zlib-support.git--1071467962839356487/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIOSHA1.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIOOpenSSL.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CCryptoOpenSSL.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIOZlib.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIODarwin.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIOHTTPParser.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIOAtomics.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIOLinux.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
/Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/Service.build/Environment~partial.swiftmodule : /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/ServiceID.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Utilities/Deprecated.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/Service.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/ServiceCache.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Utilities/Extendable.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/ServiceType.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Config/Config.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Provider/Provider.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Container/Container.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Container/SubContainer.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Container/BasicSubContainer.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Container/BasicContainer.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Utilities/ServiceError.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Container/ContainerAlias.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/Services.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Utilities/Exports.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Environment/Environment.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/ServiceFactory.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/BasicServiceFactory.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/TypeServiceFactory.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/NIO.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/Async.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/NIOConcurrencyHelpers.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/NIOFoundationCompat.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOAtomics/include/cpp_magic.h /Users/godemodegame/Desktop/ATMApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOLinux/include/ifaddrs-android.h /Users/godemodegame/Desktop/ATMApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIODarwin/include/CNIODarwin.h /Users/godemodegame/Desktop/ATMApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/godemodegame/Desktop/ATMApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOLinux/include/CNIOLinux.h /Users/godemodegame/Desktop/ATMApp/.build/checkouts/swift-nio-zlib-support.git--1071467962839356487/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIOSHA1.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIOOpenSSL.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CCryptoOpenSSL.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIOZlib.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIODarwin.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIOHTTPParser.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIOAtomics.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIOLinux.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
/Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/Service.build/Environment~partial.swiftdoc : /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/ServiceID.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Utilities/Deprecated.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/Service.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/ServiceCache.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Utilities/Extendable.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/ServiceType.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Config/Config.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Provider/Provider.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Container/Container.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Container/SubContainer.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Container/BasicSubContainer.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Container/BasicContainer.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Utilities/ServiceError.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Container/ContainerAlias.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/Services.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Utilities/Exports.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Environment/Environment.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/ServiceFactory.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/BasicServiceFactory.swift /Users/godemodegame/Desktop/ATMApp/.build/checkouts/service.git--3029908809087319447/Sources/Service/Services/TypeServiceFactory.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/NIO.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/Async.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/NIOConcurrencyHelpers.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/NIOFoundationCompat.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/godemodegame/Desktop/ATMApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOAtomics/include/cpp_magic.h /Users/godemodegame/Desktop/ATMApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOLinux/include/ifaddrs-android.h /Users/godemodegame/Desktop/ATMApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIODarwin/include/CNIODarwin.h /Users/godemodegame/Desktop/ATMApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/godemodegame/Desktop/ATMApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOLinux/include/CNIOLinux.h /Users/godemodegame/Desktop/ATMApp/.build/checkouts/swift-nio-zlib-support.git--1071467962839356487/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIOSHA1.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIOOpenSSL.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CCryptoOpenSSL.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIOZlib.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIODarwin.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIOHTTPParser.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIOAtomics.build/module.modulemap /Users/godemodegame/Desktop/ATMApp/.build/x86_64-apple-macosx10.10/debug/CNIOLinux.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
|
D
|
/Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/DatabaseKit.build/Connection/DatabaseStringFindable.swift.o : /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/Deprecated.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/KeyedCache.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/DatabaseKeyedCache.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/DictionaryKeyedCache.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/MemoryKeyedCache.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/DatabaseConnectionPoolCache.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/DatabaseStringFindable.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/DatabaseConnectable.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Database/DatabaseQueryable.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/URL+DatabaseName.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Database/Database.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Database/ConfiguredDatabase.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Database/DatabaseConfig.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/DatabaseConnectionPoolConfig.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/KeyedCacheSupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Log/LogSupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Log/DatabaseLog.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/Container+ConnectionPool.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/DatabaseConnectionPool.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/Container+CachedConnection.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/DatabaseConnection.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/Container+NewConnection.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Service/DatabaseKitProvider.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Log/DatabaseLogger.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Database/DatabaseIdentifier.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Log/DatabaseLogHandler.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Log/PrintLogHandler.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/DatabaseKitError.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Database/Databases.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/Exports.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Service.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio-zlib-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/DatabaseKit.build/Connection/DatabaseStringFindable~partial.swiftmodule : /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/Deprecated.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/KeyedCache.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/DatabaseKeyedCache.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/DictionaryKeyedCache.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/MemoryKeyedCache.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/DatabaseConnectionPoolCache.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/DatabaseStringFindable.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/DatabaseConnectable.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Database/DatabaseQueryable.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/URL+DatabaseName.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Database/Database.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Database/ConfiguredDatabase.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Database/DatabaseConfig.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/DatabaseConnectionPoolConfig.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/KeyedCacheSupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Log/LogSupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Log/DatabaseLog.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/Container+ConnectionPool.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/DatabaseConnectionPool.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/Container+CachedConnection.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/DatabaseConnection.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/Container+NewConnection.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Service/DatabaseKitProvider.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Log/DatabaseLogger.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Database/DatabaseIdentifier.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Log/DatabaseLogHandler.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Log/PrintLogHandler.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/DatabaseKitError.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Database/Databases.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/Exports.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Service.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio-zlib-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/DatabaseKit.build/Connection/DatabaseStringFindable~partial.swiftdoc : /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/Deprecated.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/KeyedCache.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/DatabaseKeyedCache.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/DictionaryKeyedCache.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/MemoryKeyedCache.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/DatabaseConnectionPoolCache.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/DatabaseStringFindable.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/DatabaseConnectable.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Database/DatabaseQueryable.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/URL+DatabaseName.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Database/Database.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Database/ConfiguredDatabase.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Database/DatabaseConfig.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/DatabaseConnectionPoolConfig.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/KeyedCache/KeyedCacheSupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Log/LogSupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Log/DatabaseLog.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/Container+ConnectionPool.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/ConnectionPool/DatabaseConnectionPool.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/Container+CachedConnection.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/DatabaseConnection.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Connection/Container+NewConnection.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Service/DatabaseKitProvider.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Log/DatabaseLogger.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Database/DatabaseIdentifier.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Log/DatabaseLogHandler.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Log/PrintLogHandler.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/DatabaseKitError.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Database/Databases.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/database-kit/Sources/DatabaseKit/Utilities/Exports.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Service.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio-zlib-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
|
D
|
import std.stdio;
void printTuple(T...)() if(T.length != 0) {
foreach(i, _; T)
writeln(T[i].stringof);
}
void printThreeValues(int a, string b, double c) {
writefln("%s, %s, %s", a, b, c);
}
struct UnpackMe {
int meaningOfLife;
string meaningOfFood;
double lifeOf;
}
void printThreeTemplateParams(T, string U, alias V)() {
writefln("%s, %s, %s", T.stringof, U, V.stringof);
}
void printTuple2(T...)(T args) {
foreach(i, _; T)
pragma(msg, T[i].stringof);
foreach(item; args)
writeln(item);
}
void main() {
import std.meta : AliasSeq;
AliasSeq!(int, string, double) isdTuple1;
alias ISD = AliasSeq!(int, string, double);
ISD isdTuple2;
printTuple!isdTuple1;
printTuple!ISD;
isdTuple1[0] = 42;
isdTuple1[1] = "Pizza!";
isdTuple1[2] = 3.14;
printThreeValues(isdTuple1);
auto um = UnpackMe(42, "Pizza!", 3.14);
printThreeValues(um.tupleof);
printThreeTemplateParams!(AliasSeq!(int, "Hello", std.stdio));
printTuple2(42, "Pizza!", 3.14);
}
|
D
|
#!/usr/bin/rdmd
import std.stdio, std.string, std.algorithm;
void main() {
size_t[string] dictionary;
foreach (line; stdin.byLine()) {
// Break sentence into words
// Add each word in the sentence to the vocabulary
foreach (word; splitter(strip(line))) {
if (word in dictionary) continue; // Nothing to do
auto newID = dictionary.length;
dictionary[word.idup] = newID;
writeln(newID, '\t', word);
}
}
}
|
D
|
/Users/petercernak/vapor/TILApp/Build/Intermediates.noindex/TILApp.build/Debug/Command.build/Objects-normal/x86_64/CommandOption.o : /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Command/Command.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Base/CommandRunnable.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Run/Output+Autocomplete.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Config/CommandConfig.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Base/CommandOption.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Run/Console+Run.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Run/Output+Help.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Group/CommandGroup.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Group/BasicCommandGroup.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Utilities/CommandError.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Config/Commands.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Utilities/Utilities.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Utilities/Exports.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Command/CommandArgument.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Run/CommandInput.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Run/CommandContext.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Users/petercernak/vapor/TILApp/Build/Products/Debug/NIO.framework/Modules/NIO.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Async.framework/Modules/Async.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Service.framework/Modules/Service.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Console.framework/Modules/Console.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Core.framework/Modules/Core.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Logging.framework/Modules/Logging.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Debugging.framework/Modules/Debugging.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/COperatingSystem.framework/Modules/COperatingSystem.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/NIOConcurrencyHelpers.framework/Modules/NIOConcurrencyHelpers.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Bits.framework/Modules/Bits.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/NIOFoundationCompat.framework/Modules/NIOFoundationCompat.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIOAtomics/include/cpp_magic.h /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIODarwin/include/c_nio_darwin.h /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIOAtomics/include/c-atomics.h /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIOLinux/include/c_nio_linux.h /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOSHA1/module.modulemap /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio-zlib-support.git--6538424668019974428/module.modulemap /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIODarwin/module.modulemap /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOAtomics/module.modulemap /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOLinux/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/petercernak/vapor/TILApp/Build/Intermediates.noindex/TILApp.build/Debug/Command.build/Objects-normal/x86_64/CommandOption~partial.swiftmodule : /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Command/Command.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Base/CommandRunnable.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Run/Output+Autocomplete.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Config/CommandConfig.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Base/CommandOption.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Run/Console+Run.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Run/Output+Help.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Group/CommandGroup.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Group/BasicCommandGroup.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Utilities/CommandError.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Config/Commands.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Utilities/Utilities.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Utilities/Exports.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Command/CommandArgument.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Run/CommandInput.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Run/CommandContext.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Users/petercernak/vapor/TILApp/Build/Products/Debug/NIO.framework/Modules/NIO.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Async.framework/Modules/Async.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Service.framework/Modules/Service.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Console.framework/Modules/Console.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Core.framework/Modules/Core.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Logging.framework/Modules/Logging.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Debugging.framework/Modules/Debugging.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/COperatingSystem.framework/Modules/COperatingSystem.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/NIOConcurrencyHelpers.framework/Modules/NIOConcurrencyHelpers.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Bits.framework/Modules/Bits.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/NIOFoundationCompat.framework/Modules/NIOFoundationCompat.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIOAtomics/include/cpp_magic.h /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIODarwin/include/c_nio_darwin.h /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIOAtomics/include/c-atomics.h /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIOLinux/include/c_nio_linux.h /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOSHA1/module.modulemap /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio-zlib-support.git--6538424668019974428/module.modulemap /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIODarwin/module.modulemap /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOAtomics/module.modulemap /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOLinux/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/petercernak/vapor/TILApp/Build/Intermediates.noindex/TILApp.build/Debug/Command.build/Objects-normal/x86_64/CommandOption~partial.swiftdoc : /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Command/Command.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Base/CommandRunnable.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Run/Output+Autocomplete.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Config/CommandConfig.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Base/CommandOption.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Run/Console+Run.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Run/Output+Help.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Group/CommandGroup.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Group/BasicCommandGroup.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Utilities/CommandError.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Config/Commands.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Utilities/Utilities.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Utilities/Exports.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Command/CommandArgument.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Run/CommandInput.swift /Users/petercernak/vapor/TILApp/.build/checkouts/console.git-5752444009020230057/Sources/Command/Run/CommandContext.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Users/petercernak/vapor/TILApp/Build/Products/Debug/NIO.framework/Modules/NIO.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Async.framework/Modules/Async.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Service.framework/Modules/Service.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Console.framework/Modules/Console.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Core.framework/Modules/Core.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Logging.framework/Modules/Logging.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Debugging.framework/Modules/Debugging.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/COperatingSystem.framework/Modules/COperatingSystem.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/NIOConcurrencyHelpers.framework/Modules/NIOConcurrencyHelpers.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Bits.framework/Modules/Bits.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/NIOFoundationCompat.framework/Modules/NIOFoundationCompat.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIOAtomics/include/cpp_magic.h /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIODarwin/include/c_nio_darwin.h /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIOAtomics/include/c-atomics.h /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIOLinux/include/c_nio_linux.h /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOSHA1/module.modulemap /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio-zlib-support.git--6538424668019974428/module.modulemap /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIODarwin/module.modulemap /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOAtomics/module.modulemap /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOLinux/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
|
D
|
/*
* Finds the smallest cropped sub-matrix that contains all the 1s from a larger matrix.
* Copyright 2012 James Otten <james_otten@lavabit.com>
*/
import std.stdio;
immutable HEIGHT = 11;
immutable LENGTH = 16;
int input[HEIGHT][LENGTH] = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,1,1,0,0,1,1,1,0,0,0,0],
[0,0,0,0,0,0,1,1,1,1,0,1,0,0,0,0],
[0,0,0,0,0,1,1,0,0,1,1,1,0,0,0,0],
[0,0,0,0,0,1,1,0,1,1,1,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0],
[0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]];
void main() {
int hmin = LENGTH - 1, hmax = 0, vmin = HEIGHT - 1, vmax = 0;
for(int i = 0; i < HEIGHT; i++) {
for(int j = 0; j < LENGTH; j++) {
if(input[i][j] == 1) {
if(i < hmin) hmin = i;
else if(i > hmax) hmax = i;
if(j < vmin) vmin = j;
else if(j > vmax) vmax = j;
}
}
}
for(int i = hmin; i <= hmax; i++) {
for(int j = vmin; j <= vmax; j++)
write(input[i][j]);
writeln();
}
}
|
D
|
/home/sky/Workshop/solana-app/target/release/build/anyhow-e705641556862b76/build_script_build-e705641556862b76: /home/sky/.cargo/registry/src/github.com-1ecc6299db9ec823/anyhow-1.0.44/build.rs
/home/sky/Workshop/solana-app/target/release/build/anyhow-e705641556862b76/build_script_build-e705641556862b76.d: /home/sky/.cargo/registry/src/github.com-1ecc6299db9ec823/anyhow-1.0.44/build.rs
/home/sky/.cargo/registry/src/github.com-1ecc6299db9ec823/anyhow-1.0.44/build.rs:
|
D
|
/// Generate by tools
module org.apache.http.protocol.ResponseConnControl;
import java.lang.exceptions;
public class ResponseConnControl
{
public this()
{
implMissing();
}
}
|
D
|
(plural) the lay members of a male religious order
a male with the same parents as someone else
a male person who is a fellow member (of a fraternity or religion or other group
a close friend who accompanies his buddies in their activities
used as a term of address for those male persons engaged in the same movement
(Roman Catholic Church) a title given to a monk and used as form of address
|
D
|
import derelict.sdl2.sdl;
import cosmos.exception;
import cosmos.window;
import cosmos.canvas;
import cosmos.face;
import cosmos.board;
import cosmos.resources;
import cosmos.game;
import std.stdio;
@property auto toMessage(in SDL_Event ev)
in {
assert(ev.type == SDL_KEYDOWN ||
ev.type == SDL_KEYUP);
} body {
if (ev.type == SDL_KEYDOWN)
{
switch(ev.key.keysym.sym) with(Message)
{
case SDLK_RIGHT:
return MoveRight;
case SDLK_LEFT:
return MoveLeft;
case SDLK_DOWN:
return FastFall;
case SDLK_SPACE:
return RotateRight;
case SDLK_p:
return Pause;
case SDLK_r:
return Resume;
case SDLK_q:
return Quit;
default:
return DoNothing;
}
}
else
{
switch(ev.key.keysym.sym) with(Message)
{
case SDLK_DOWN:
return SlowFall;
default:
return DoNothing;
}
}
}
void main()
{
auto window = new Window("Cosmos", 800, 600);
scope(exit) window.destroy();
auto canvas = window.canvas;
scope(exit) canvas.destroy();
auto background = new Image(BACKGROUND, 800, 600);
scope(exit) background.destroy();
auto game = new Game();
scope(exit) game.destroy();
{
canvas.clear();
scope(exit) canvas.show();
canvas.draw(background, 0, 0);
canvas.draw(game, 250, 50);
}
MainLoop:
while (true)
{
SDL_Event e = void;
canvas.clear();
scope(exit) canvas.show();
canvas.draw(background, 0, 0);
scope(exit)
{
game.update();
canvas.draw(game, 250, 50);
}
while (SDL_PollEvent(&e))
{
switch (e.type)
{
case SDL_QUIT:
break MainLoop;
case SDL_KEYDOWN, SDL_KEYUP:
game.recieve(e.toMessage);
break;
default:
break;
}
}
}
}
|
D
|
/// Generate by tools
module org.apache.commons.imaging.common.bytesource.ByteSourceArray;
import java.lang.exceptions;
public class ByteSourceArray
{
public this()
{
implMissing();
}
}
|
D
|
/*
* Copyright 2016-2018 Philip Pavlick
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License, excepting that
* Derivative Works are not required to carry prominent notices in changed
* files. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* swash-tentative status: TENTATIVE */
// magicfx.d: Defines flags for determining spell effects and other attributes
// of spells. For defining actual spells, see ``magic.d''
import global;
//////////////////////////
// Spell Target Options //
//////////////////////////
// These flags determine what kind of spell it is; i.e. projectile, shielding,
// targeted-at-self, etcetera.
// The spell instantaneously affects the caster
enum TARGET_AT_SELF = 0;
// The spell instantaneously forms a shield around the caster
enum SHIELD = 1;
// The spell instantaneously places a ward on a spot next to the caster
enum WARD = 2;
// The spell affects the next monster the caster touches
enum TOUCH = 3;
// The spell fires a projectile that impacts the first monster it touches
enum PROJECTILE = 4;
// The spell fires a projectile that explodes on impact with a monster or wall
enum EXPLOSION = 5;
// The spell fires a beam that impacts all characters in its path until it
// touches a wall or is absorbed
enum BEAM = 6;
// The spell instantaneously affects a targeted monster
enum LINE_OF_SIGHT = 7;
// The spell instantaneously affects a targeted area; if the spell duration is
// greater than 0, the area of effect will persist.
// AFFECT_AREA must be greater than the other magic effect flags, because the
// formula (X - AFFECT_AREA), where X is the number given for the magic effect
// flag, is used to determine the radius of the effect.
enum AFFECT_AREA = 8;
///////////////////
// Spell Effects //
///////////////////
// These flags determine the actual effect of the spell.
// Healing Magic
///////////////////
/// This flag determines that the spell effect is governed by healing magic
enum HEALING_EFFECT = 0x1000;
enum RESTORE_HEALTH = HEALING_EFFECT | 0x0001;
enum RESTORE_STAMINA = HEALING_EFFECT | 0x0002;
enum CURE_POISON = HEALING_EFFECT | 0x0004;
enum CURE_DISEASE = HEALING_EFFECT | 0x0008;
enum REMOVE_CURSE = HEALING_EFFECT | 0x0010;
enum PROTECTION = HEALING_EFFECT | 0x0020;
enum CURE_PARALYSIS = HEALING_EFFECT | 0x0040;
// Thaumaturgy
/////////////////
/// This flag determines that the spell effect is governed by thaumaturgy
enum THAUMATURGY_EFFECT = 0x2000;
enum WATER_WALKING = THAUMATURGY_EFFECT | 0x0001;
enum WATER_BREATHING = THAUMATURGY_EFFECT | 0x0002;
enum LEVITATE = THAUMATURGY_EFFECT | 0x0004;
enum DISENTANGLE = THAUMATURGY_EFFECT | 0x0008;
enum INVISIBILITY = THAUMATURGY_EFFECT | 0x0010;
enum TURN_UNDEAD = THAUMATURGY_EFFECT | 0x0020;
enum BANISH_UNDEAD = THAUMATURGY_EFFECT | 0x0040;
enum BANISH_DEMON = THAUMATURGY_EFFECT | 0x0080;
enum SUMMON_FAMILIAR = THAUMATURGY_EFFECT | 0x0100;
enum TELEKINESIS = THAUMATURGY_EFFECT | 0x0200;
enum IDENTIFY_ITEM = THAUMATURGY_EFFECT | 0x0400;
enum WISH_FOR_ITEM = THAUMATURGY_EFFECT | 0x0800;
// Offensive
///////////////
/// This flag determines that the spell effect is govened by offensive magic
enum OFFENSIVE_EFFECT = 0x4000;
enum FIRE = OFFENSIVE_EFFECT | 0x0001;
enum THUNDER = OFFENSIVE_EFFECT | 0x0002;
enum WIND = OFFENSIVE_EFFECT | 0x0004;
enum ICE = OFFENSIVE_EFFECT | 0x0008;
enum VENOM = OFFENSIVE_EFFECT | 0x0010;
enum ACID = OFFENSIVE_EFFECT | 0x0020;
enum THORNS = OFFENSIVE_EFFECT | 0x0040;
enum NECROTIZE = OFFENSIVE_EFFECT | 0x0080;
enum PARALYZE = OFFENSIVE_EFFECT | 0x0100;
enum BLIND = OFFENSIVE_EFFECT | 0x0200;
// Charm
///////////
/// This flag determines that the spell effect is governed by charm magic
enum CHARM_EFFECT = 0x8000;
enum PACIFY = CHARM_EFFECT | 0x0001;
enum ENCOURAGE = CHARM_EFFECT | 0x0002;
enum ENRAGE = CHARM_EFFECT | 0x0004;
enum BETRAY = CHARM_EFFECT | 0x0008;
enum FEAR = CHARM_EFFECT | 0x0010;
enum HYPNOTIZE = CHARM_EFFECT | 0x0020;
|
D
|
module requests.utils;
import std.range;
import std.string;
import std.datetime;
import std.algorithm.sorting;
import std.experimental.logger;
import std.typecons;
import std.algorithm;
import std.conv;
//import requests.streams;
__gshared immutable short[string] standard_ports;
shared static this() {
standard_ports["http"] = 80;
standard_ports["https"] = 443;
standard_ports["ftp"] = 21;
}
string Getter_Setter(T)(string name) {
return `
@property final auto ` ~ name ~ `() pure inout @safe @nogc nothrow {
return _` ~ name ~ `;
}
@property final void ` ~ name ~ `(` ~ T.stringof ~ ` setter_arg) pure @nogc nothrow {
_` ~ name ~ `= setter_arg;
}
`;
}
string Setter(T)(string name) {
return `
@property final void ` ~ name ~ `(` ~ T.stringof ~ ` setter_arg) pure @nogc nothrow {
_` ~ name ~ `= setter_arg;
}
`;
}
string Getter(string name) {
return `
@property final auto ` ~ name ~ `() pure inout @safe @nogc nothrow {
return _` ~ name ~ `;
}
`;
}
//auto getter(string name) {
// return `
// @property final auto ` ~ name ~ `() const @safe @nogc {
// return __` ~ name ~ `;
// }
// `;
//}
//auto setter(string name) {
// string member = "__" ~ name;
// string t = "typeof(this."~member~")";
// return `
// @property final void ` ~ name ~`(` ~ t ~ ` s) pure @nogc nothrow {`~
// member ~`=s;
// }
// `;
//}
unittest {
struct S {
private {
int _i;
string _s;
bool _b;
}
mixin(Getter("i"));
mixin(Setter!int("i"));
mixin(Getter("b"));
}
S s;
assert(s.i == 0);
s.i = 1;
assert(s.i == 1);
assert(s.b == false);
}
template rank(R) {
static if ( isInputRange!R ) {
enum size_t rank = 1 + rank!(ElementType!R);
} else {
enum size_t rank = 0;
}
}
unittest {
assert(rank!(char) == 0);
assert(rank!(string) == 1);
assert(rank!(ubyte[][]) == 2);
}
// test if p1 is sub-path of p2 (used to find Cookie to send)
bool pathMatches(string p1, string p2) pure @safe @nogc {
import std.algorithm;
return p1.startsWith(p2);
}
package unittest {
assert("/abc/def".pathMatches("/"));
assert("/abc/def".pathMatches("/abc"));
assert("/abc/def".pathMatches("/abc/def"));
assert(!"/def".pathMatches("/abc"));
}
// test if d1 is subbomain of d2 (used to find Cookie to send)
// Host names can be specified either as an IP address or a HDN string.
// Sometimes we compare one host name with another. (Such comparisons
// SHALL be case-insensitive.) Host A's name domain-matches host B's if
//
// * their host name strings string-compare equal; or
//
// * A is a HDN string and has the form NB, where N is a non-empty
// name string, B has the form .B', and B' is a HDN string. (So,
// x.y.com domain-matches .Y.com but not Y.com.)
package bool domainMatches(string d1, string d2) pure @safe @nogc {
import std.algorithm;
return d1==d2 ||
(d2.startsWith(".") && d1.endsWith(d2));
}
package unittest {
assert("x.example.com".domainMatches(".example.com"));
assert(!"x.example.com".domainMatches("example.com"));
assert(!"example.com".domainMatches(".x.example.com"));
assert("example.com".domainMatches("example.com"));
assert(!"example.com".domainMatches(""));
assert(!"".domainMatches("example.com"));
}
string[] dump(in ubyte[] data) {
import std.stdio;
import std.range;
import std.ascii;
import std.format;
import std.algorithm;
string[] res;
foreach(i,chunk; data.chunks(16).enumerate) {
string r;
r ~= format("%05X ", i*16);
ubyte[] left, right;
if ( chunk.length > 8 ) {
left = chunk[0..8].dup;
right= chunk[8..$].dup;
} else {
left = chunk.dup;
}
r ~= format("%-24.24s ", left.map!(c => format("%02X", c)).join(" "));
r ~= format("%-24.24s ", right.map!(c => format("%02X", c)).join(" "));
r ~= format("|%-16s|", chunk.map!(c => isPrintable(c)?cast(char)c:'.'));
res ~= r;
}
return res;
}
static string urlEncoded(string p) pure @safe {
immutable string[dchar] translationTable = [
' ': "%20", '!': "%21", '*': "%2A", '\'': "%27", '(': "%28", ')': "%29",
';': "%3B", ':': "%3A", '@': "%40", '&': "%26", '=': "%3D", '+': "%2B",
'$': "%24", ',': "%2C", '/': "%2F", '?': "%3F", '#': "%23", '[': "%5B",
']': "%5D", '%': "%25",
];
return p.translate(translationTable);
}
package unittest {
assert(urlEncoded(`abc !#$&'()*+,/:;=?@[]`) == "abc%20%21%23%24%26%27%28%29%2A%2B%2C%2F%3A%3B%3D%3F%40%5B%5D");
}
private static immutable char[string] hex2chr;
shared static this() {
foreach(c; 0..255) {
hex2chr["%02X".format(c)] = cast(char)c;
}
}
string urlDecode(string p) {
import std.string;
import std.algorithm;
import core.exception;
if ( !p.canFind("%") ) {
return p.replace("+", " ");
}
string[] res;
auto parts = p.replace("+", " ").split("%");
res ~= parts[0];
foreach(part; parts[1..$]) {
if ( part.length<2 ) {
res ~= "%" ~ part;
continue;
}
try {
res ~= hex2chr[part[0..2]] ~ part[2..$];
} catch (RangeError e) {
res ~= "%" ~ part;
}
}
return res.join();
}
package unittest {
assert(urlEncoded(`abc !#$&'()*+,/:;=?@[]`) == "abc%20%21%23%24%26%27%28%29%2A%2B%2C%2F%3A%3B%3D%3F%40%5B%5D");
assert(urlDecode("a+bc%20%21%23%24%26%27%28%29%2A%2B%2C%2F%3A%3B%3D%3F%40%5B%5D") == `a bc !#$&'()*+,/:;=?@[]`);
}
public alias Cookie = Tuple!(string, "path", string, "domain", string, "attr", string, "value");
public alias QueryParam = Tuple!(string, "key", string, "value");
struct Cookies {
Cookie[] _array;
alias _array this;
}
///
/// create QueryParam[] from assoc.array string[string]
//
QueryParam[] aa2params(string[string] aa)
{
return aa.byKeyValue.map!(p => QueryParam(p.key, p.value)).array;
}
///
/// Create QueryParam[] from any args
///
auto queryParams(A...)(A args) pure @safe nothrow {
QueryParam[] res;
static if ( args.length >= 2 ) {
res = [QueryParam(args[0].to!string, args[1].to!string)] ~ queryParams(args[2..$]);
}
return res;
}
bool responseMustNotIncludeBody(ushort code) pure nothrow @nogc @safe
{
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.4
if ((code / 100 == 1) || code == 204 || code == 304 ) return true;
return false;
}
|
D
|
module noded.node;
import rx;
import noded.port;
///
struct ChangeValueEvent {
public{
Node[] affectedNodes;
}//public
private{
}//private
}//struct ChangeValueEvent
struct ChangeStructEvent{
public{
Node[] affectedNodes;
}//public
private{
}//private
}//struct ChangeValueEvent
///
class Node {
public{
Port[] inputs;
Port[] outputs;
this(){
_changeValue = new SubjectObject!ChangeValueEvent;
_changeStruct = new SubjectObject!ChangeStructEvent;
}
Observable!ChangeValueEvent changeValue(){
return _changeValue;
}
Observable!ChangeStructEvent changeStruct(){
return _changeStruct;
}
Node update(){
return this;
}
}//public
private{
SubjectObject!ChangeValueEvent _changeValue;
SubjectObject!ChangeStructEvent _changeStruct;
}
}//class Node
unittest{
auto node = new Node();
node.inputs ~= port!(float);
assert(node.inputs[0].validate!(float));
}
private Node[] affectedNodes(Node node){
Node[] result;
foreach (output; node.outputs) {
foreach (port; output.connections){
result ~= port.base;
}
}
return result;
}
unittest{
}
|
D
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.