code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
from __future__ import absolute_import # What follows is part of a hack to make control breaking work on windows even # if scipy.stats ims imported. See: # http://stackoverflow.com/questions/15457786/ctrl-c-crashes-python-after-importing-scipy-stats import sys import os import imp import ctypes if sys.platform == 'win32': basepath = imp.find_module('numpy')[1] ctypes.CDLL(os.path.join(basepath, 'core', 'libmmd.dll')) ctypes.CDLL(os.path.join(basepath, 'core', 'libifcoremd.dll')) from .adadelta import Adadelta from .adam import Adam from .asgd import Asgd from .bfgs import Bfgs, Lbfgs, Sbfgs from .cg import ConjugateGradient, NonlinearConjugateGradient from .gd import GradientDescent from .nes import Xnes from .rmsprop import RmsProp from .rprop import Rprop from .smd import Smd from radagrad import Radagrad from adagrad import Adagrad from adagrad_full import AdagradFull
gabobert/climin
climin/__init__.py
Python
bsd-3-clause
899
class euler4 { public static boolean isPal(int number) { String num = number + ""; int numLen = num.length(); if(num.length() == 6) { String half1 = num.substring(0, numLen/2); String half2 = num.substring(numLen/2, numLen); System.out.println(half1 + "\t" + half2); } return true; } public static int largestPalindrome() { int factor1 = 999; int factor2 = 999; int product; while(factor1 >= 100) { while(factor2 >= 100) { product = factor1 * factor2; } } return 0; } public static void main(String[] args) { isPal(261162); } }
ProgrammerKid/eulerJava
euler4.java
Java
bsd-3-clause
579
#The DF of a tidal stream import copy import numpy import multiprocessing import scipy from scipy import special, interpolate, integrate if int(scipy.__version__.split('.')[1]) < 10: #pragma: no cover from scipy.maxentropy import logsumexp else: from scipy.misc import logsumexp from galpy.orbit import Orbit from galpy.util import bovy_coords, fast_cholesky_invert, \ bovy_conversion, multi, bovy_plot, stable_cho_factor, bovy_ars import warnings from galpy.util import galpyWarning _INTERPDURINGSETUP= True _USEINTERP= True _USESIMPLE= True _labelDict= {'x': r'$X$', 'y': r'$Y$', 'z': r'$Z$', 'r': r'$R$', 'phi': r'$\phi$', 'vx':r'$V_X$', 'vy':r'$V_Y$', 'vz':r'$V_Z$', 'vr':r'$V_R$', 'vt':r'$V_T$', 'll':r'$\mathrm{Galactic\ longitude\, (deg)}$', 'bb':r'$\mathrm{Galactic\ latitude\, (deg)}$', 'dist':r'$\mathrm{distance\, (kpc)}$', 'pmll':r'$\mu_l\,(\mathrm{mas\,yr}^{-1})$', 'pmbb':r'$\mu_b\,(\mathrm{mas\,yr}^{-1})$', 'vlos':r'$V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$'} class streamdf(object): """The DF of a tidal stream""" def __init__(self,sigv,progenitor=None,pot=None,aA=None, tdisrupt=None,sigMeanOffset=6.,leading=True, sigangle=None, deltaAngleTrack=None,nTrackChunks=None,nTrackIterations=None, progIsTrack=False, Vnorm=220.,Rnorm=8., R0=8.,Zsun=0.025,vsun=[-11.1,8.*30.24,7.25], multi=None,interpTrack=_INTERPDURINGSETUP, useInterp=_USEINTERP,nosetup=False): """ NAME: __init__ PURPOSE: Initialize a quasi-isothermal DF INPUT: sigv - radial velocity dispersion of the progenitor tdisrupt= (5 Gyr) time since start of disruption (natural units) leading= (True) if True, model the leading part of the stream if False, model the trailing part progenitor= progenitor orbit as Orbit instance (will be re-integrated, so don't bother integrating the orbit before) progIsTrack= (False) if True, then the progenitor (x,v) is actually the (x,v) of the stream track at zero angle separation; useful when initializing with an orbit fit; the progenitor's position will be calculated pot= Potential instance or list thereof aA= actionAngle instance used to convert (x,v) to actions sigMeanOffset= (6.) offset between the mean of the frequencies and the progenitor, in units of the largest eigenvalue of the frequency covariance matrix (along the largest eigenvector), should be positive; to model the trailing part, set leading=False sigangle= (sigv/122/[1km/s]=1.8sigv in natural coordinates) estimate of the angle spread of the debris initially deltaAngleTrack= (None) angle to estimate the stream track over (rad) nTrackChunks= (floor(deltaAngleTrack/0.15)+1) number of chunks to divide the progenitor track in nTrackIterations= Number of iterations to perform when establishing the track; each iteration starts from a previous approximation to the track in (x,v) and calculates a new track based on the deviation between the previous track and the desired track in action-angle coordinates; if not set, an appropriate value is determined based on the magnitude of the misalignment between stream and orbit, with larger numbers of iterations for larger misalignments interpTrack= (might change), interpolate the stream track while setting up the instance (can be done by hand by calling self._interpolate_stream_track() and self._interpolate_stream_track_aA()) useInterp= (might change), use interpolation by default when calculating approximated frequencies and angles nosetup= (False) if True, don't setup the stream track and anything else that is expensive multi= (None) if set, use multi-processing Coordinate transformation inputs: Vnorm= (220) circular velocity to normalize velocities with Rnorm= (8) Galactocentric radius to normalize positions with R0= (8) Galactocentric radius of the Sun (kpc) Zsun= (0.025) Sun's height above the plane (kpc) vsun= ([-11.1,241.92,7.25]) Sun's motion in cylindrical coordinates (vR positive away from center) OUTPUT: object HISTORY: 2013-09-16 - Started - Bovy (IAS) 2013-11-25 - Started over - Bovy (IAS) """ self._sigv= sigv if tdisrupt is None: self._tdisrupt= 5./bovy_conversion.time_in_Gyr(Vnorm,Rnorm) else: self._tdisrupt= tdisrupt self._sigMeanOffset= sigMeanOffset if pot is None: #pragma: no cover raise IOError("pot= must be set") self._pot= pot self._aA= aA if not self._aA._pot == self._pot: raise IOError("Potential in aA does not appear to be the same as given potential pot") if (multi is True): #if set to boolean, enable cpu_count processes self._multi= multiprocessing.cpu_count() else: self._multi= multi self._progenitor_setup(progenitor,leading) self._offset_setup(sigangle,leading,deltaAngleTrack) # if progIsTrack, calculate the progenitor that gives a track that is approximately the given orbit if progIsTrack: self._setup_progIsTrack() self._setup_coord_transform(Rnorm,Vnorm,R0,Zsun,vsun,progenitor) #Determine the stream track if not nosetup: self._determine_nTrackIterations(nTrackIterations) self._determine_stream_track(nTrackChunks) self._useInterp= useInterp if interpTrack or self._useInterp: self._interpolate_stream_track() self._interpolate_stream_track_aA() self.calc_stream_lb() self._determine_stream_spread() return None def _progenitor_setup(self,progenitor,leading): """The part of the setup relating to the progenitor's orbit""" #Progenitor orbit: Calculate actions, frequencies, and angles for the progenitor self._progenitor= progenitor() #call to get new Orbit # Make sure we do not use physical coordinates self._progenitor.turn_physical_off() acfs= self._aA.actionsFreqsAngles(self._progenitor,maxn=3, _firstFlip=(not leading)) self._progenitor_jr= acfs[0][0] self._progenitor_lz= acfs[1][0] self._progenitor_jz= acfs[2][0] self._progenitor_Omegar= acfs[3] self._progenitor_Omegaphi= acfs[4] self._progenitor_Omegaz= acfs[5] self._progenitor_Omega= numpy.array([acfs[3],acfs[4],acfs[5]]).reshape(3) self._progenitor_angler= acfs[6] self._progenitor_anglephi= acfs[7] self._progenitor_anglez= acfs[8] self._progenitor_angle= numpy.array([acfs[6],acfs[7],acfs[8]]).reshape(3) #Calculate dO/dJ Jacobian at the progenitor self._dOdJp= calcaAJac(self._progenitor._orb.vxvv, self._aA,dxv=None,dOdJ=True, _initacfs=acfs) self._dOdJpEig= numpy.linalg.eig(self._dOdJp) return None def _offset_setup(self,sigangle,leading,deltaAngleTrack): """The part of the setup related to calculating the stream/progenitor offset""" #From the progenitor orbit, determine the sigmas in J and angle self._sigjr= (self._progenitor.rap()-self._progenitor.rperi())/numpy.pi*self._sigv self._siglz= self._progenitor.rperi()*self._sigv self._sigjz= 2.*self._progenitor.zmax()/numpy.pi*self._sigv #Estimate the frequency covariance matrix from a diagonal J matrix x dOdJ self._sigjmatrix= numpy.diag([self._sigjr**2., self._siglz**2., self._sigjz**2.]) self._sigomatrix= numpy.dot(self._dOdJp, numpy.dot(self._sigjmatrix,self._dOdJp.T)) #Estimate angle spread as the ratio of the largest to the middle eigenvalue self._sigomatrixEig= numpy.linalg.eig(self._sigomatrix) self._sigomatrixEigsortIndx= numpy.argsort(self._sigomatrixEig[0]) self._sortedSigOEig= sorted(self._sigomatrixEig[0]) if sigangle is None: self._sigangle= self._sigv*1.8 else: self._sigangle= sigangle self._sigangle2= self._sigangle**2. self._lnsigangle= numpy.log(self._sigangle) #Estimate the frequency mean as lying along the direction of the largest eigenvalue self._dsigomeanProgDirection= self._sigomatrixEig[1][:,numpy.argmax(self._sigomatrixEig[0])] self._progenitor_Omega_along_dOmega= \ numpy.dot(self._progenitor_Omega,self._dsigomeanProgDirection) #Make sure we are modeling the correct part of the stream self._leading= leading self._sigMeanSign= 1. if self._leading and self._progenitor_Omega_along_dOmega < 0.: self._sigMeanSign= -1. elif not self._leading and self._progenitor_Omega_along_dOmega > 0.: self._sigMeanSign= -1. self._progenitor_Omega_along_dOmega*= self._sigMeanSign self._sigomean= self._progenitor_Omega\ +self._sigMeanOffset*self._sigMeanSign\ *numpy.sqrt(numpy.amax(self._sigomatrixEig[0]))\ *self._dsigomeanProgDirection #numpy.dot(self._dOdJp, # numpy.array([self._sigjr,self._siglz,self._sigjz])) self._dsigomeanProg= self._sigomean-self._progenitor_Omega self._meandO= self._sigMeanOffset\ *numpy.sqrt(numpy.amax(self._sigomatrixEig[0])) #Store cholesky of sigomatrix for fast evaluation self._sigomatrixNorm=\ numpy.sqrt(numpy.sum(self._sigomatrix**2.)) self._sigomatrixinv, self._sigomatrixLogdet= \ fast_cholesky_invert(self._sigomatrix/self._sigomatrixNorm, tiny=10.**-15.,logdet=True) self._sigomatrixinv/= self._sigomatrixNorm deltaAngleTrackLim = (self._sigMeanOffset+4.) * numpy.sqrt( self._sortedSigOEig[2]) * self._tdisrupt if (deltaAngleTrack is None): deltaAngleTrack = deltaAngleTrackLim else: if (deltaAngleTrack > deltaAngleTrackLim): warnings.warn("WARNING: angle range large compared to plausible value.", galpyWarning) self._deltaAngleTrack= deltaAngleTrack return None def _setup_coord_transform(self,Rnorm,Vnorm,R0,Zsun,vsun,progenitor): #Set the coordinate-transformation parameters; check that these do not conflict with those in the progenitor orbit object; need to use the original, since this objects _progenitor has physical turned off if progenitor._roSet \ and (numpy.fabs(Rnorm-progenitor._orb._ro) > 10.**-.8 \ or numpy.fabs(R0-progenitor._orb._ro) > 10.**-8.): warnings.warn("Warning: progenitor's ro does not agree with streamdf's Rnorm and R0; this may have unexpected consequences when projecting into observables", galpyWarning) if progenitor._voSet \ and numpy.fabs(Vnorm-progenitor._orb._vo) > 10.**-8.: warnings.warn("Warning: progenitor's vo does not agree with streamdf's Vnorm; this may have unexpected consequences when projecting into observables", galpyWarning) if (progenitor._roSet or progenitor._voSet) \ and numpy.fabs(Zsun-progenitor._orb._zo) > 10.**-8.: warnings.warn("Warning: progenitor's zo does not agree with streamdf's Zsun; this may have unexpected consequences when projecting into observables", galpyWarning) if (progenitor._roSet or progenitor._voSet) \ and numpy.any(numpy.fabs(vsun-numpy.array([0.,Vnorm,0.])\ -progenitor._orb._solarmotion) > 10.**-8.): warnings.warn("Warning: progenitor's solarmotion does not agree with streamdf's vsun (after accounting for Vnorm); this may have unexpected consequences when projecting into observables", galpyWarning) self._Vnorm= Vnorm self._Rnorm= Rnorm self._R0= R0 self._Zsun= Zsun self._vsun= vsun return None def _setup_progIsTrack(self): """If progIsTrack, the progenitor orbit that was passed to the streamdf initialization is the track at zero angle separation; this routine computes an actual progenitor position that gives the desired track given the parameters of the streamdf""" # We need to flip the sign of the offset, to go to the progenitor self._sigMeanSign*= -1. # Use _determine_stream_track_single to calculate the track-progenitor # offset at zero angle separation prog_stream_offset=\ _determine_stream_track_single(self._aA, self._progenitor, 0., #time = 0 self._progenitor_angle, self._sigMeanSign, self._dsigomeanProgDirection, self.meanOmega, 0.) #angle = 0 # Setup the new progenitor orbit progenitor= Orbit(prog_stream_offset[3]) # Flip the offset sign again self._sigMeanSign*= -1. # Now re-do the previous setup self._progenitor_setup(progenitor,self._leading) self._offset_setup(self._sigangle,self._leading, self._deltaAngleTrack) return None def misalignment(self,isotropic=False): """ NAME: misalignment PURPOSE: calculate the misalignment between the progenitor's frequency and the direction along which the stream disrupts INPUT: isotropic= (False), if True, return the misalignment assuming an isotropic action distribution OUTPUT: misalignment in degree HISTORY: 2013-12-05 - Written - Bovy (IAS) """ if isotropic: dODir= self._dOdJpEig[1][:,numpy.argmax(numpy.fabs(self._dOdJpEig[0]))] else: dODir= self._dsigomeanProgDirection out= numpy.arccos(numpy.sum(self._progenitor_Omega*dODir)/numpy.sqrt(numpy.sum(self._progenitor_Omega**2.)))/numpy.pi*180. if out > 90.: return out-180. else: return out def freqEigvalRatio(self,isotropic=False): """ NAME: freqEigvalRatio PURPOSE: calculate the ratio between the largest and 2nd-to-largest (in abs) eigenvalue of sqrt(dO/dJ^T V_J dO/dJ) (if this is big, a 1D stream will form) INPUT: isotropic= (False), if True, return the ratio assuming an isotropic action distribution (i.e., just of dO/dJ) OUTPUT: ratio between eigenvalues of |dO / dJ| HISTORY: 2013-12-05 - Written - Bovy (IAS) """ if isotropic: sortedEig= sorted(numpy.fabs(self._dOdJpEig[0])) return sortedEig[2]/sortedEig[1] else: return numpy.sqrt(self._sortedSigOEig)[2]\ /numpy.sqrt(self._sortedSigOEig)[1] def estimateTdisrupt(self,deltaAngle): """ NAME: estimateTdisrupt PURPOSE: estimate the time of disruption INPUT: deltaAngle- spread in angle since disruption OUTPUT: time in natural units HISTORY: 2013-11-27 - Written - Bovy (IAS) """ return deltaAngle\ /numpy.sqrt(numpy.sum(self._dsigomeanProg**2.)) ############################STREAM TRACK FUNCTIONS############################# def plotTrack(self,d1='x',d2='z',interp=True,spread=0,simple=_USESIMPLE, *args,**kwargs): """ NAME: plotTrack PURPOSE: plot the stream track INPUT: d1= plot this on the X axis ('x','y','z','R','phi','vx','vy','vz','vR','vt','ll','bb','dist','pmll','pmbb','vlos') d2= plot this on the Y axis (same list as for d1) interp= (True) if True, use the interpolated stream track spread= (0) if int > 0, also plot the spread around the track as spread x sigma scaleToPhysical= (False), if True, plot positions in kpc and velocities in km/s simple= (False), if True, use a simple estimate for the spread in perpendicular angle bovy_plot.bovy_plot args and kwargs OUTPUT: plot to output device HISTORY: 2013-12-09 - Written - Bovy (IAS) """ if not hasattr(self,'_ObsTrackLB') and \ (d1.lower() == 'll' or d1.lower() == 'bb' or d1.lower() == 'dist' or d1.lower() == 'pmll' or d1.lower() == 'pmbb' or d1.lower() == 'vlos' or d2.lower() == 'll' or d2.lower() == 'bb' or d2.lower() == 'dist' or d2.lower() == 'pmll' or d2.lower() == 'pmbb' or d2.lower() == 'vlos'): self.calc_stream_lb() phys= kwargs.pop('scaleToPhysical',False) tx= self._parse_track_dim(d1,interp=interp,phys=phys) ty= self._parse_track_dim(d2,interp=interp,phys=phys) bovy_plot.bovy_plot(tx,ty,*args, xlabel=_labelDict[d1.lower()], ylabel=_labelDict[d2.lower()], **kwargs) if spread: addx, addy= self._parse_track_spread(d1,d2,interp=interp,phys=phys, simple=simple) if ('ls' in kwargs and kwargs['ls'] == 'none') \ or ('linestyle' in kwargs \ and kwargs['linestyle'] == 'none'): kwargs.pop('ls',None) kwargs.pop('linestyle',None) spreadls= 'none' else: spreadls= '-.' spreadmarker= kwargs.pop('marker',None) spreadcolor= kwargs.pop('color',None) spreadlw= kwargs.pop('lw',1.) bovy_plot.bovy_plot(tx+spread*addx,ty+spread*addy,ls=spreadls, marker=spreadmarker,color=spreadcolor, lw=spreadlw, overplot=True) bovy_plot.bovy_plot(tx-spread*addx,ty-spread*addy,ls=spreadls, marker=spreadmarker,color=spreadcolor, lw=spreadlw, overplot=True) return None def plotProgenitor(self,d1='x',d2='z',*args,**kwargs): """ NAME: plotProgenitor PURPOSE: plot the progenitor orbit INPUT: d1= plot this on the X axis ('x','y','z','R','phi','vx','vy','vz','vR','vt','ll','bb','dist','pmll','pmbb','vlos') d2= plot this on the Y axis (same list as for d1) scaleToPhysical= (False), if True, plot positions in kpc and velocities in km/s bovy_plot.bovy_plot args and kwargs OUTPUT: plot to output device HISTORY: 2013-12-09 - Written - Bovy (IAS) """ tts= self._progenitor._orb.t[self._progenitor._orb.t \ < self._trackts[self._nTrackChunks-1]] obs= [self._R0,0.,self._Zsun] obs.extend(self._vsun) phys= kwargs.pop('scaleToPhysical',False) tx= self._parse_progenitor_dim(d1,tts,ro=self._Rnorm,vo=self._Vnorm, obs=obs,phys=phys) ty= self._parse_progenitor_dim(d2,tts,ro=self._Rnorm,vo=self._Vnorm, obs=obs,phys=phys) bovy_plot.bovy_plot(tx,ty,*args, xlabel=_labelDict[d1.lower()], ylabel=_labelDict[d2.lower()], **kwargs) return None def _parse_track_dim(self,d1,interp=True,phys=False): """Parse the dimension to plot the stream track for""" if interp: interpStr= 'interpolated' else: interpStr= '' if d1.lower() == 'x': tx= self.__dict__['_%sObsTrackXY' % interpStr][:,0] elif d1.lower() == 'y': tx= self.__dict__['_%sObsTrackXY' % interpStr][:,1] elif d1.lower() == 'z': tx= self.__dict__['_%sObsTrackXY' % interpStr][:,2] elif d1.lower() == 'r': tx= self.__dict__['_%sObsTrack' % interpStr][:,0] elif d1.lower() == 'phi': tx= self.__dict__['_%sObsTrack' % interpStr][:,5] elif d1.lower() == 'vx': tx= self.__dict__['_%sObsTrackXY' % interpStr][:,3] elif d1.lower() == 'vy': tx= self.__dict__['_%sObsTrackXY' % interpStr][:,4] elif d1.lower() == 'vz': tx= self.__dict__['_%sObsTrackXY' % interpStr][:,5] elif d1.lower() == 'vr': tx= self.__dict__['_%sObsTrack' % interpStr][:,1] elif d1.lower() == 'vt': tx= self.__dict__['_%sObsTrack' % interpStr][:,2] elif d1.lower() == 'll': tx= self.__dict__['_%sObsTrackLB' % interpStr][:,0] elif d1.lower() == 'bb': tx= self.__dict__['_%sObsTrackLB' % interpStr][:,1] elif d1.lower() == 'dist': tx= self.__dict__['_%sObsTrackLB' % interpStr][:,2] elif d1.lower() == 'pmll': tx= self.__dict__['_%sObsTrackLB' % interpStr][:,4] elif d1.lower() == 'pmbb': tx= self.__dict__['_%sObsTrackLB' % interpStr][:,5] elif d1.lower() == 'vlos': tx= self.__dict__['_%sObsTrackLB' % interpStr][:,3] if phys and (d1.lower() == 'x' or d1.lower() == 'y' \ or d1.lower() == 'z' or d1.lower() == 'r'): tx= copy.copy(tx) tx*= self._Rnorm if phys and (d1.lower() == 'vx' or d1.lower() == 'vy' \ or d1.lower() == 'vz' or d1.lower() == 'vr' \ or d1.lower() == 'vt'): tx= copy.copy(tx) tx*= self._Vnorm return tx def _parse_progenitor_dim(self,d1,ts,ro=None,vo=None,obs=None, phys=False): """Parse the dimension to plot the progenitor orbit for""" if d1.lower() == 'x': tx= self._progenitor.x(ts,ro=ro,vo=vo,obs=obs,use_physical=False) elif d1.lower() == 'y': tx= self._progenitor.y(ts,ro=ro,vo=vo,obs=obs,use_physical=False) elif d1.lower() == 'z': tx= self._progenitor.z(ts,ro=ro,vo=vo,obs=obs,use_physical=False) elif d1.lower() == 'r': tx= self._progenitor.R(ts,ro=ro,vo=vo,obs=obs,use_physical=False) elif d1.lower() == 'phi': tx= self._progenitor.phi(ts,ro=ro,vo=vo,obs=obs) elif d1.lower() == 'vx': tx= self._progenitor.vx(ts,ro=ro,vo=vo,obs=obs,use_physical=False) elif d1.lower() == 'vy': tx= self._progenitor.vy(ts,ro=ro,vo=vo,obs=obs,use_physical=False) elif d1.lower() == 'vz': tx= self._progenitor.vz(ts,ro=ro,vo=vo,obs=obs,use_physical=False) elif d1.lower() == 'vr': tx= self._progenitor.vR(ts,ro=ro,vo=vo,obs=obs,use_physical=False) elif d1.lower() == 'vt': tx= self._progenitor.vT(ts,ro=ro,vo=vo,obs=obs,use_physical=False) elif d1.lower() == 'll': tx= self._progenitor.ll(ts,ro=ro,vo=vo,obs=obs) elif d1.lower() == 'bb': tx= self._progenitor.bb(ts,ro=ro,vo=vo,obs=obs) elif d1.lower() == 'dist': tx= self._progenitor.dist(ts,ro=ro,vo=vo,obs=obs) elif d1.lower() == 'pmll': tx= self._progenitor.pmll(ts,ro=ro,vo=vo,obs=obs) elif d1.lower() == 'pmbb': tx= self._progenitor.pmbb(ts,ro=ro,vo=vo,obs=obs) elif d1.lower() == 'vlos': tx= self._progenitor.vlos(ts,ro=ro,vo=vo,obs=obs) if phys and (d1.lower() == 'x' or d1.lower() == 'y' \ or d1.lower() == 'z' or d1.lower() == 'r'): tx= copy.copy(tx) tx*= self._Rnorm if phys and (d1.lower() == 'vx' or d1.lower() == 'vy' \ or d1.lower() == 'vz' or d1.lower() == 'vr' \ or d1.lower() == 'vt'): tx= copy.copy(tx) tx*= self._Vnorm return tx def _parse_track_spread(self,d1,d2,interp=True,phys=False, simple=_USESIMPLE): """Determine the spread around the track""" if not hasattr(self,'_allErrCovs'): self._determine_stream_spread(simple=simple) okaySpreadR= ['r','vr','vt','z','vz','phi'] okaySpreadXY= ['x','y','z','vx','vy','vz'] okaySpreadLB= ['ll','bb','dist','vlos','pmll','pmbb'] #Determine which coordinate system we're in coord= [False,False,False] #R, XY, LB if d1.lower() in okaySpreadR and d2.lower() in okaySpreadR: coord[0]= True elif d1.lower() in okaySpreadXY and d2.lower() in okaySpreadXY: coord[1]= True elif d1.lower() in okaySpreadLB and d2.lower() in okaySpreadLB: coord[2]= True else: raise NotImplementedError("plotting the spread for coordinates from different systems not implemented yet ...") #Get the right 2D Jacobian indxDict= {} indxDict['r']= 0 indxDict['vr']= 1 indxDict['vt']= 2 indxDict['z']= 3 indxDict['vz']= 4 indxDict['phi']= 5 indxDictXY= {} indxDictXY['x']= 0 indxDictXY['y']= 1 indxDictXY['z']= 2 indxDictXY['vx']= 3 indxDictXY['vy']= 4 indxDictXY['vz']= 5 indxDictLB= {} indxDictLB['ll']= 0 indxDictLB['bb']= 1 indxDictLB['dist']= 2 indxDictLB['vlos']= 3 indxDictLB['pmll']= 4 indxDictLB['pmbb']= 5 if coord[0]: relevantCov= self._allErrCovs relevantDict= indxDict if phys:#apply scale factors tcov= copy.copy(relevantCov) scaleFac= numpy.array([self._Rnorm,self._Vnorm,self._Vnorm, self._Rnorm,self._Vnorm,1.]) tcov*= numpy.tile(scaleFac,(6,1)) tcov*= numpy.tile(scaleFac,(6,1)).T relevantCov= tcov elif coord[1]: relevantCov= self._allErrCovsXY relevantDict= indxDictXY if phys:#apply scale factors tcov= copy.copy(relevantCov) scaleFac= numpy.array([self._Rnorm,self._Rnorm,self._Rnorm, self._Vnorm,self._Vnorm,self._Vnorm]) tcov*= numpy.tile(scaleFac,(6,1)) tcov*= numpy.tile(scaleFac,(6,1)).T relevantCov= tcov elif coord[2]: relevantCov= self._allErrCovsLBUnscaled relevantDict= indxDictLB indx0= numpy.array([[relevantDict[d1.lower()],relevantDict[d1.lower()]], [relevantDict[d2.lower()],relevantDict[d2.lower()]]]) indx1= numpy.array([[relevantDict[d1.lower()],relevantDict[d2.lower()]], [relevantDict[d1.lower()],relevantDict[d2.lower()]]]) cov= relevantCov[:,indx0,indx1] #cov contains all nTrackChunks covs if not interp: out= numpy.empty((self._nTrackChunks,2)) eigDir= numpy.array([1.,0.]) for ii in range(self._nTrackChunks): covEig= numpy.linalg.eig(cov[ii]) minIndx= numpy.argmin(covEig[0]) minEigvec= covEig[1][:,minIndx] #this is the direction of the transverse spread if numpy.sum(minEigvec*eigDir) < 0.: minEigvec*= -1. #Keep them pointing in the same direction out[ii]= minEigvec*numpy.sqrt(covEig[0][minIndx]) eigDir= minEigvec else: #We slerp the minor eigenvector and interpolate the eigenvalue #First store all of the eigenvectors on the track allEigval= numpy.empty(self._nTrackChunks) allEigvec= numpy.empty((self._nTrackChunks,2)) eigDir= numpy.array([1.,0.]) for ii in range(self._nTrackChunks): covEig= numpy.linalg.eig(cov[ii]) minIndx= numpy.argmin(covEig[0]) minEigvec= covEig[1][:,minIndx] #this is the direction of the transverse spread if numpy.sum(minEigvec*eigDir) < 0.: minEigvec*= -1. #Keep them pointing in the same direction allEigval[ii]= numpy.sqrt(covEig[0][minIndx]) allEigvec[ii]= minEigvec eigDir= minEigvec #Now interpolate where needed interpEigval=\ interpolate.InterpolatedUnivariateSpline(self._thetasTrack, allEigval,k=3) interpolatedEigval= interpEigval(self._interpolatedThetasTrack) #Interpolate in chunks interpolatedEigvec= numpy.empty((len(self._interpolatedThetasTrack), 2)) for ii in range(self._nTrackChunks-1): slerpOmega= numpy.arccos(numpy.sum(allEigvec[ii]*allEigvec[ii+1])) slerpts= (self._interpolatedThetasTrack-self._thetasTrack[ii])/\ (self._thetasTrack[ii+1]-self._thetasTrack[ii]) slerpIndx= (slerpts >= 0.)*(slerpts <= 1.) for jj in range(2): interpolatedEigvec[slerpIndx,jj]=\ (numpy.sin((1-slerpts[slerpIndx])*slerpOmega)*allEigvec[ii,jj] +numpy.sin(slerpts[slerpIndx]*slerpOmega)*allEigvec[ii+1,jj])/numpy.sin(slerpOmega) out= numpy.tile(interpolatedEigval.T,(2,1)).T*interpolatedEigvec if coord[2]: #if LB, undo rescalings that were applied before out[:,0]*= self._ErrCovsLBScale[relevantDict[d1.lower()]] out[:,1]*= self._ErrCovsLBScale[relevantDict[d2.lower()]] return (out[:,0],out[:,1]) def plotCompareTrackAAModel(self,**kwargs): """ NAME: plotCompareTrackAAModel PURPOSE: plot the comparison between the underlying model's dOmega_perp vs. dangle_r (line) and the track in (x,v)'s dOmega_perp vs. dangle_r (dots; explicitly calculating the track's action-angle coordinates) INPUT: bovy_plot.bovy_plot kwargs OUTPUT: plot HISTORY: 2014-08-27 - Written - Bovy (IAS) """ #First calculate the model model_adiff= (self._ObsTrackAA[:,3:]-self._progenitor_angle)[:,0]\ *self._sigMeanSign model_operp= numpy.dot(self._ObsTrackAA[:,:3]-self._progenitor_Omega, self._dsigomeanProgDirection)\ *self._sigMeanSign #Then calculate the track's frequency-angle coordinates if self._multi is None: aatrack= numpy.empty((self._nTrackChunks,6)) for ii in range(self._nTrackChunks): aatrack[ii]= self._aA.actionsFreqsAngles(Orbit(self._ObsTrack[ii,:]), maxn=3)[3:] else: aatrack= numpy.reshape(\ multi.parallel_map( (lambda x: self._aA.actionsFreqsAngles(Orbit(self._ObsTrack[x,:]), maxn=3)[3:]), range(self._nTrackChunks), numcores=numpy.amin([self._nTrackChunks, multiprocessing.cpu_count(), self._multi])),(self._nTrackChunks,6)) track_adiff= (aatrack[:,3:]-self._progenitor_angle)[:,0]\ *self._sigMeanSign track_operp= numpy.dot(aatrack[:,:3]-self._progenitor_Omega, self._dsigomeanProgDirection)\ *self._sigMeanSign overplot= kwargs.pop('overplot',False) yrange= kwargs.pop('yrange', [0.,numpy.amax(numpy.hstack((model_operp,track_operp)))*1.1]) xlabel= kwargs.pop('xlabel',r'$\Delta \theta_R$') ylabel= kwargs.pop('ylabel',r'$\Delta \Omega_\parallel$') bovy_plot.bovy_plot(model_adiff,model_operp,'k-',overplot=overplot, xlabel=xlabel,ylabel=ylabel,yrange=yrange,**kwargs) bovy_plot.bovy_plot(track_adiff,track_operp,'ko',overplot=True, **kwargs) return None def _determine_nTrackIterations(self,nTrackIterations): """Determine a good value for nTrackIterations based on the misalignment between stream and orbit; just based on some rough experience for now""" if not nTrackIterations is None: self.nTrackIterations= nTrackIterations return None if numpy.fabs(self.misalignment()) < 1.: self.nTrackIterations= 0 elif numpy.fabs(self.misalignment()) >= 1. \ and numpy.fabs(self.misalignment()) < 3.: self.nTrackIterations= 1 elif numpy.fabs(self.misalignment()) >= 3.: self.nTrackIterations= 2 return None def _determine_stream_track(self,nTrackChunks): """Determine the track of the stream in real space""" #Determine how much orbital time is necessary for the progenitor's orbit to cover the stream if nTrackChunks is None: #default is floor(self._deltaAngleTrack/0.15)+1 self._nTrackChunks= int(numpy.floor(self._deltaAngleTrack/0.15))+1 else: self._nTrackChunks= nTrackChunks dt= self._deltaAngleTrack\ /self._progenitor_Omega_along_dOmega self._trackts= numpy.linspace(0.,2*dt,2*self._nTrackChunks-1) #to be sure that we cover it #Instantiate an auxiliaryTrack, which is an Orbit instance at the mean frequency of the stream, and zero angle separation wrt the progenitor; prog_stream_offset is the offset between this track and the progenitor at zero angle prog_stream_offset=\ _determine_stream_track_single(self._aA, self._progenitor, 0., #time = 0 self._progenitor_angle, self._sigMeanSign, self._dsigomeanProgDirection, self.meanOmega, 0.) #angle = 0 auxiliaryTrack= Orbit(prog_stream_offset[3]) if dt < 0.: self._trackts= numpy.linspace(0.,-2.*dt,2.*self._nTrackChunks-1) #Flip velocities before integrating auxiliaryTrack= auxiliaryTrack.flip() auxiliaryTrack.integrate(self._trackts,self._pot) if dt < 0.: #Flip velocities again auxiliaryTrack._orb.orbit[:,1]= -auxiliaryTrack._orb.orbit[:,1] auxiliaryTrack._orb.orbit[:,2]= -auxiliaryTrack._orb.orbit[:,2] auxiliaryTrack._orb.orbit[:,4]= -auxiliaryTrack._orb.orbit[:,4] #Calculate the actions, frequencies, and angle for this auxiliary orbit acfs= self._aA.actionsFreqs(auxiliaryTrack(0.),maxn=3) auxiliary_Omega= numpy.array([acfs[3],acfs[4],acfs[5]]).reshape(3\ ) auxiliary_Omega_along_dOmega= \ numpy.dot(auxiliary_Omega,self._dsigomeanProgDirection) #Now calculate the actions, frequencies, and angles + Jacobian for each chunk allAcfsTrack= numpy.empty((self._nTrackChunks,9)) alljacsTrack= numpy.empty((self._nTrackChunks,6,6)) allinvjacsTrack= numpy.empty((self._nTrackChunks,6,6)) thetasTrack= numpy.linspace(0.,self._deltaAngleTrack, self._nTrackChunks) ObsTrack= numpy.empty((self._nTrackChunks,6)) ObsTrackAA= numpy.empty((self._nTrackChunks,6)) detdOdJps= numpy.empty((self._nTrackChunks)) if self._multi is None: for ii in range(self._nTrackChunks): multiOut= _determine_stream_track_single(self._aA, auxiliaryTrack, self._trackts[ii]*numpy.fabs(self._progenitor_Omega_along_dOmega/auxiliary_Omega_along_dOmega), #this factor accounts for the difference in frequency between the progenitor and the auxiliary track self._progenitor_angle, self._sigMeanSign, self._dsigomeanProgDirection, self.meanOmega, thetasTrack[ii]) allAcfsTrack[ii,:]= multiOut[0] alljacsTrack[ii,:,:]= multiOut[1] allinvjacsTrack[ii,:,:]= multiOut[2] ObsTrack[ii,:]= multiOut[3] ObsTrackAA[ii,:]= multiOut[4] detdOdJps[ii]= multiOut[5] else: multiOut= multi.parallel_map(\ (lambda x: _determine_stream_track_single(self._aA,auxiliaryTrack, self._trackts[x]*numpy.fabs(self._progenitor_Omega_along_dOmega/auxiliary_Omega_along_dOmega), self._progenitor_angle, self._sigMeanSign, self._dsigomeanProgDirection, self.meanOmega, thetasTrack[x])), range(self._nTrackChunks), numcores=numpy.amin([self._nTrackChunks, multiprocessing.cpu_count(), self._multi])) for ii in range(self._nTrackChunks): allAcfsTrack[ii,:]= multiOut[ii][0] alljacsTrack[ii,:,:]= multiOut[ii][1] allinvjacsTrack[ii,:,:]= multiOut[ii][2] ObsTrack[ii,:]= multiOut[ii][3] ObsTrackAA[ii,:]= multiOut[ii][4] detdOdJps[ii]= multiOut[ii][5] #Repeat the track calculation using the previous track, to get closer to it for nn in range(self.nTrackIterations): if self._multi is None: for ii in range(self._nTrackChunks): multiOut= _determine_stream_track_single(self._aA, Orbit(ObsTrack[ii,:]), 0., self._progenitor_angle, self._sigMeanSign, self._dsigomeanProgDirection, self.meanOmega, thetasTrack[ii]) allAcfsTrack[ii,:]= multiOut[0] alljacsTrack[ii,:,:]= multiOut[1] allinvjacsTrack[ii,:,:]= multiOut[2] ObsTrack[ii,:]= multiOut[3] ObsTrackAA[ii,:]= multiOut[4] detdOdJps[ii]= multiOut[5] else: multiOut= multi.parallel_map(\ (lambda x: _determine_stream_track_single(self._aA,Orbit(ObsTrack[x,:]),0., self._progenitor_angle, self._sigMeanSign, self._dsigomeanProgDirection, self.meanOmega, thetasTrack[x])), range(self._nTrackChunks), numcores=numpy.amin([self._nTrackChunks, multiprocessing.cpu_count(), self._multi])) for ii in range(self._nTrackChunks): allAcfsTrack[ii,:]= multiOut[ii][0] alljacsTrack[ii,:,:]= multiOut[ii][1] allinvjacsTrack[ii,:,:]= multiOut[ii][2] ObsTrack[ii,:]= multiOut[ii][3] ObsTrackAA[ii,:]= multiOut[ii][4] detdOdJps[ii]= multiOut[ii][5] #Store the track self._thetasTrack= thetasTrack self._ObsTrack= ObsTrack self._ObsTrackAA= ObsTrackAA self._allAcfsTrack= allAcfsTrack self._alljacsTrack= alljacsTrack self._allinvjacsTrack= allinvjacsTrack self._detdOdJps= detdOdJps self._meandetdOdJp= numpy.mean(self._detdOdJps) self._logmeandetdOdJp= numpy.log(self._meandetdOdJp) #Also calculate _ObsTrackXY in XYZ,vXYZ coordinates self._ObsTrackXY= numpy.empty_like(self._ObsTrack) TrackX= self._ObsTrack[:,0]*numpy.cos(self._ObsTrack[:,5]) TrackY= self._ObsTrack[:,0]*numpy.sin(self._ObsTrack[:,5]) TrackZ= self._ObsTrack[:,3] TrackvX, TrackvY, TrackvZ=\ bovy_coords.cyl_to_rect_vec(self._ObsTrack[:,1], self._ObsTrack[:,2], self._ObsTrack[:,4], self._ObsTrack[:,5]) self._ObsTrackXY[:,0]= TrackX self._ObsTrackXY[:,1]= TrackY self._ObsTrackXY[:,2]= TrackZ self._ObsTrackXY[:,3]= TrackvX self._ObsTrackXY[:,4]= TrackvY self._ObsTrackXY[:,5]= TrackvZ return None def _determine_stream_spread(self,simple=_USESIMPLE): """Determine the spread around the stream track, just sets matrices that describe the covariances""" allErrCovs= numpy.empty((self._nTrackChunks,6,6)) if self._multi is None: for ii in range(self._nTrackChunks): allErrCovs[ii]= _determine_stream_spread_single(self._sigomatrixEig, self._thetasTrack[ii], self.sigOmega, lambda y: self.sigangledAngle(y,simple=simple), self._allinvjacsTrack[ii]) else: multiOut= multi.parallel_map(\ (lambda x: _determine_stream_spread_single(self._sigomatrixEig, self._thetasTrack[x], self.sigOmega, lambda y: self.sigangledAngle(y,simple=simple), self._allinvjacsTrack[x])), range(self._nTrackChunks), numcores=numpy.amin([self._nTrackChunks, multiprocessing.cpu_count(), self._multi])) for ii in range(self._nTrackChunks): allErrCovs[ii]= multiOut[ii] self._allErrCovs= allErrCovs #Also propagate to XYZ coordinates allErrCovsXY= numpy.empty_like(self._allErrCovs) allErrCovsEigvalXY= numpy.empty((len(self._thetasTrack),6)) allErrCovsEigvecXY= numpy.empty_like(self._allErrCovs) eigDir= numpy.array([numpy.array([1.,0.,0.,0.,0.,0.]) for ii in range(6)]) for ii in range(self._nTrackChunks): tjac= bovy_coords.cyl_to_rect_jac(*self._ObsTrack[ii]) allErrCovsXY[ii]=\ numpy.dot(tjac,numpy.dot(self._allErrCovs[ii],tjac.T)) #Eigen decomposition for interpolation teig= numpy.linalg.eig(allErrCovsXY[ii]) #Sort them to match them up later sortIndx= numpy.argsort(teig[0]) allErrCovsEigvalXY[ii]= teig[0][sortIndx] #Make sure the eigenvectors point in the same direction for jj in range(6): if numpy.sum(eigDir[jj]*teig[1][:,sortIndx[jj]]) < 0.: teig[1][:,sortIndx[jj]]*= -1. eigDir[jj]= teig[1][:,sortIndx[jj]] allErrCovsEigvecXY[ii]= teig[1][:,sortIndx] self._allErrCovsXY= allErrCovsXY #Interpolate the allErrCovsXY covariance matrices along the interpolated track #Interpolate the eigenvalues interpAllErrCovsEigvalXY=\ [interpolate.InterpolatedUnivariateSpline(self._thetasTrack, allErrCovsEigvalXY[:,ii], k=3) for ii in range(6)] #Now build the interpolated allErrCovsXY using slerp interpolatedAllErrCovsXY= numpy.empty((len(self._interpolatedThetasTrack), 6,6)) interpolatedEigval=\ numpy.array([interpAllErrCovsEigvalXY[ii](self._interpolatedThetasTrack) for ii in range(6)]) #6,ninterp #Interpolate in chunks interpolatedEigvec= numpy.empty((len(self._interpolatedThetasTrack), 6,6)) for ii in range(self._nTrackChunks-1): slerpOmegas=\ [numpy.arccos(numpy.sum(allErrCovsEigvecXY[ii,:,jj]*allErrCovsEigvecXY[ii+1,:,jj])) for jj in range(6)] slerpts= (self._interpolatedThetasTrack-self._thetasTrack[ii])/\ (self._thetasTrack[ii+1]-self._thetasTrack[ii]) slerpIndx= (slerpts >= 0.)*(slerpts <= 1.) for jj in range(6): for kk in range(6): interpolatedEigvec[slerpIndx,kk,jj]=\ (numpy.sin((1-slerpts[slerpIndx])*slerpOmegas[jj])*allErrCovsEigvecXY[ii,kk,jj] +numpy.sin(slerpts[slerpIndx]*slerpOmegas[jj])*allErrCovsEigvecXY[ii+1,kk,jj])/numpy.sin(slerpOmegas[jj]) for ii in range(len(self._interpolatedThetasTrack)): interpolatedAllErrCovsXY[ii]=\ numpy.dot(interpolatedEigvec[ii], numpy.dot(numpy.diag(interpolatedEigval[:,ii]), interpolatedEigvec[ii].T)) self._interpolatedAllErrCovsXY= interpolatedAllErrCovsXY #Also interpolate in l and b coordinates self._determine_stream_spreadLB(simple=simple) return None def _determine_stream_spreadLB(self,simple=_USESIMPLE, Rnorm=None,Vnorm=None, R0=None,Zsun=None,vsun=None): """Determine the spread in the stream in observable coordinates""" if not hasattr(self,'_allErrCovs'): self._determine_stream_spread(simple=simple) if Rnorm is None: Rnorm= self._Rnorm if Vnorm is None: Vnorm= self._Vnorm if R0 is None: R0= self._R0 if Zsun is None: Zsun= self._Zsun if vsun is None: vsun= self._vsun allErrCovsLB= numpy.empty_like(self._allErrCovs) obs= [R0,0.,Zsun] obs.extend(vsun) obskwargs= {} obskwargs['ro']= Rnorm obskwargs['vo']= Vnorm obskwargs['obs']= obs self._ErrCovsLBScale= [180.,90., self._progenitor.dist(**obskwargs), numpy.fabs(self._progenitor.vlos(**obskwargs)), numpy.sqrt(self._progenitor.pmll(**obskwargs)**2. +self._progenitor.pmbb(**obskwargs)**2.), numpy.sqrt(self._progenitor.pmll(**obskwargs)**2. +self._progenitor.pmbb(**obskwargs)**2.)] allErrCovsEigvalLB= numpy.empty((len(self._thetasTrack),6)) allErrCovsEigvecLB= numpy.empty_like(self._allErrCovs) eigDir= numpy.array([numpy.array([1.,0.,0.,0.,0.,0.]) for ii in range(6)]) for ii in range(self._nTrackChunks): tjacXY= bovy_coords.galcenrect_to_XYZ_jac(*self._ObsTrackXY[ii]) tjacLB= bovy_coords.lbd_to_XYZ_jac(*self._ObsTrackLB[ii], degree=True) tjacLB[:3,:]/= Rnorm tjacLB[3:,:]/= Vnorm for jj in range(6): tjacLB[:,jj]*= self._ErrCovsLBScale[jj] tjac= numpy.dot(numpy.linalg.inv(tjacLB),tjacXY) allErrCovsLB[ii]=\ numpy.dot(tjac,numpy.dot(self._allErrCovsXY[ii],tjac.T)) #Eigen decomposition for interpolation teig= numpy.linalg.eig(allErrCovsLB[ii]) #Sort them to match them up later sortIndx= numpy.argsort(teig[0]) allErrCovsEigvalLB[ii]= teig[0][sortIndx] #Make sure the eigenvectors point in the same direction for jj in range(6): if numpy.sum(eigDir[jj]*teig[1][:,sortIndx[jj]]) < 0.: teig[1][:,sortIndx[jj]]*= -1. eigDir[jj]= teig[1][:,sortIndx[jj]] allErrCovsEigvecLB[ii]= teig[1][:,sortIndx] self._allErrCovsLBUnscaled= allErrCovsLB #Interpolate the allErrCovsLB covariance matrices along the interpolated track #Interpolate the eigenvalues interpAllErrCovsEigvalLB=\ [interpolate.InterpolatedUnivariateSpline(self._thetasTrack, allErrCovsEigvalLB[:,ii], k=3) for ii in range(6)] #Now build the interpolated allErrCovsXY using slerp interpolatedAllErrCovsLB= numpy.empty((len(self._interpolatedThetasTrack), 6,6)) interpolatedEigval=\ numpy.array([interpAllErrCovsEigvalLB[ii](self._interpolatedThetasTrack) for ii in range(6)]) #6,ninterp #Interpolate in chunks interpolatedEigvec= numpy.empty((len(self._interpolatedThetasTrack), 6,6)) for ii in range(self._nTrackChunks-1): slerpOmegas=\ [numpy.arccos(numpy.sum(allErrCovsEigvecLB[ii,:,jj]*allErrCovsEigvecLB[ii+1,:,jj])) for jj in range(6)] slerpts= (self._interpolatedThetasTrack-self._thetasTrack[ii])/\ (self._thetasTrack[ii+1]-self._thetasTrack[ii]) slerpIndx= (slerpts >= 0.)*(slerpts <= 1.) for jj in range(6): for kk in range(6): interpolatedEigvec[slerpIndx,kk,jj]=\ (numpy.sin((1-slerpts[slerpIndx])*slerpOmegas[jj])*allErrCovsEigvecLB[ii,kk,jj] +numpy.sin(slerpts[slerpIndx]*slerpOmegas[jj])*allErrCovsEigvecLB[ii+1,kk,jj])/numpy.sin(slerpOmegas[jj]) for ii in range(len(self._interpolatedThetasTrack)): interpolatedAllErrCovsLB[ii]=\ numpy.dot(interpolatedEigvec[ii], numpy.dot(numpy.diag(interpolatedEigval[:,ii]), interpolatedEigvec[ii].T)) self._interpolatedAllErrCovsLBUnscaled= interpolatedAllErrCovsLB #Also calculate the (l,b,..) -> (X,Y,..) Jacobian at all of the interpolated and not interpolated points trackLogDetJacLB= numpy.empty_like(self._thetasTrack) interpolatedTrackLogDetJacLB=\ numpy.empty_like(self._interpolatedThetasTrack) for ii in range(self._nTrackChunks): tjacLB= bovy_coords.lbd_to_XYZ_jac(*self._ObsTrackLB[ii], degree=True) trackLogDetJacLB[ii]= numpy.log(numpy.linalg.det(tjacLB)) self._trackLogDetJacLB= trackLogDetJacLB for ii in range(len(self._interpolatedThetasTrack)): tjacLB=\ bovy_coords.lbd_to_XYZ_jac(*self._interpolatedObsTrackLB[ii], degree=True) interpolatedTrackLogDetJacLB[ii]=\ numpy.log(numpy.linalg.det(tjacLB)) self._interpolatedTrackLogDetJacLB= interpolatedTrackLogDetJacLB return None def _interpolate_stream_track(self): """Build interpolations of the stream track""" if hasattr(self,'_interpolatedThetasTrack'): return None #Already did this TrackX= self._ObsTrack[:,0]*numpy.cos(self._ObsTrack[:,5]) TrackY= self._ObsTrack[:,0]*numpy.sin(self._ObsTrack[:,5]) TrackZ= self._ObsTrack[:,3] TrackvX, TrackvY, TrackvZ=\ bovy_coords.cyl_to_rect_vec(self._ObsTrack[:,1], self._ObsTrack[:,2], self._ObsTrack[:,4], self._ObsTrack[:,5]) #Interpolate self._interpTrackX=\ interpolate.InterpolatedUnivariateSpline(self._thetasTrack, TrackX,k=3) self._interpTrackY=\ interpolate.InterpolatedUnivariateSpline(self._thetasTrack, TrackY,k=3) self._interpTrackZ=\ interpolate.InterpolatedUnivariateSpline(self._thetasTrack, TrackZ,k=3) self._interpTrackvX=\ interpolate.InterpolatedUnivariateSpline(self._thetasTrack, TrackvX,k=3) self._interpTrackvY=\ interpolate.InterpolatedUnivariateSpline(self._thetasTrack, TrackvY,k=3) self._interpTrackvZ=\ interpolate.InterpolatedUnivariateSpline(self._thetasTrack, TrackvZ,k=3) #Now store an interpolated version of the stream track self._interpolatedThetasTrack=\ numpy.linspace(0.,self._deltaAngleTrack,1001) self._interpolatedObsTrackXY= numpy.empty((len(self._interpolatedThetasTrack),6)) self._interpolatedObsTrackXY[:,0]=\ self._interpTrackX(self._interpolatedThetasTrack) self._interpolatedObsTrackXY[:,1]=\ self._interpTrackY(self._interpolatedThetasTrack) self._interpolatedObsTrackXY[:,2]=\ self._interpTrackZ(self._interpolatedThetasTrack) self._interpolatedObsTrackXY[:,3]=\ self._interpTrackvX(self._interpolatedThetasTrack) self._interpolatedObsTrackXY[:,4]=\ self._interpTrackvY(self._interpolatedThetasTrack) self._interpolatedObsTrackXY[:,5]=\ self._interpTrackvZ(self._interpolatedThetasTrack) #Also in cylindrical coordinates self._interpolatedObsTrack= \ numpy.empty((len(self._interpolatedThetasTrack),6)) tR,tphi,tZ= bovy_coords.rect_to_cyl(self._interpolatedObsTrackXY[:,0], self._interpolatedObsTrackXY[:,1], self._interpolatedObsTrackXY[:,2]) tvR,tvT,tvZ=\ bovy_coords.rect_to_cyl_vec(self._interpolatedObsTrackXY[:,3], self._interpolatedObsTrackXY[:,4], self._interpolatedObsTrackXY[:,5], tR,tphi,tZ,cyl=True) self._interpolatedObsTrack[:,0]= tR self._interpolatedObsTrack[:,1]= tvR self._interpolatedObsTrack[:,2]= tvT self._interpolatedObsTrack[:,3]= tZ self._interpolatedObsTrack[:,4]= tvZ self._interpolatedObsTrack[:,5]= tphi return None def _interpolate_stream_track_aA(self): """Build interpolations of the stream track in action-angle coordinates""" if hasattr(self,'_interpolatedObsTrackAA'): return None #Already did this #Calculate 1D meanOmega on a fine grid in angle and interpolate if not hasattr(self,'_interpolatedThetasTrack'): self._interpolate_stream_track() dmOs= numpy.array([self.meanOmega(da,oned=True) for da in self._interpolatedThetasTrack]) self._interpTrackAAdmeanOmegaOneD=\ interpolate.InterpolatedUnivariateSpline(\ self._interpolatedThetasTrack,dmOs,k=3) #Build the interpolated AA self._interpolatedObsTrackAA=\ numpy.empty((len(self._interpolatedThetasTrack),6)) for ii in range(len(self._interpolatedThetasTrack)): self._interpolatedObsTrackAA[ii,:3]=\ self._progenitor_Omega+dmOs[ii]*self._dsigomeanProgDirection\ *self._sigMeanSign self._interpolatedObsTrackAA[ii,3:]=\ self._progenitor_angle+self._interpolatedThetasTrack[ii]\ *self._dsigomeanProgDirection*self._sigMeanSign self._interpolatedObsTrackAA[ii,3:]=\ numpy.mod(self._interpolatedObsTrackAA[ii,3:],2.*numpy.pi) return None def calc_stream_lb(self, Vnorm=None,Rnorm=None, R0=None,Zsun=None,vsun=None): """ NAME: calc_stream_lb PURPOSE: convert the stream track to observational coordinates and store INPUT: Coordinate transformation inputs (all default to the instance-wide values): Vnorm= circular velocity to normalize velocities with Rnorm= Galactocentric radius to normalize positions with R0= Galactocentric radius of the Sun (kpc) Zsun= Sun's height above the plane (kpc) vsun= Sun's motion in cylindrical coordinates (vR positive away from center) OUTPUT: (none) HISTORY: 2013-12-02 - Written - Bovy (IAS) """ if Vnorm is None: Vnorm= self._Vnorm if Rnorm is None: Rnorm= self._Rnorm if R0 is None: R0= self._R0 if Zsun is None: Zsun= self._Zsun if vsun is None: vsun= self._vsun self._ObsTrackLB= numpy.empty_like(self._ObsTrack) XYZ= bovy_coords.galcencyl_to_XYZ(self._ObsTrack[:,0]*Rnorm, self._ObsTrack[:,5], self._ObsTrack[:,3]*Rnorm, Xsun=R0,Zsun=Zsun) vXYZ= bovy_coords.galcencyl_to_vxvyvz(self._ObsTrack[:,1]*Vnorm, self._ObsTrack[:,2]*Vnorm, self._ObsTrack[:,4]*Vnorm, self._ObsTrack[:,5], vsun=vsun) slbd=bovy_coords.XYZ_to_lbd(XYZ[0],XYZ[1],XYZ[2], degree=True) svlbd= bovy_coords.vxvyvz_to_vrpmllpmbb(vXYZ[0],vXYZ[1],vXYZ[2], slbd[:,0],slbd[:,1],slbd[:,2], degree=True) self._ObsTrackLB[:,0]= slbd[:,0] self._ObsTrackLB[:,1]= slbd[:,1] self._ObsTrackLB[:,2]= slbd[:,2] self._ObsTrackLB[:,3]= svlbd[:,0] self._ObsTrackLB[:,4]= svlbd[:,1] self._ObsTrackLB[:,5]= svlbd[:,2] if hasattr(self,'_interpolatedObsTrackXY'): #Do the same for the interpolated track self._interpolatedObsTrackLB=\ numpy.empty_like(self._interpolatedObsTrackXY) XYZ=\ bovy_coords.galcenrect_to_XYZ(\ self._interpolatedObsTrackXY[:,0]*Rnorm, self._interpolatedObsTrackXY[:,1]*Rnorm, self._interpolatedObsTrackXY[:,2]*Rnorm, Xsun=R0,Zsun=Zsun) vXYZ=\ bovy_coords.galcenrect_to_vxvyvz(\ self._interpolatedObsTrackXY[:,3]*Vnorm, self._interpolatedObsTrackXY[:,4]*Vnorm, self._interpolatedObsTrackXY[:,5]*Vnorm, vsun=vsun) slbd=bovy_coords.XYZ_to_lbd(XYZ[0],XYZ[1],XYZ[2], degree=True) svlbd= bovy_coords.vxvyvz_to_vrpmllpmbb(vXYZ[0],vXYZ[1],vXYZ[2], slbd[:,0],slbd[:,1], slbd[:,2], degree=True) self._interpolatedObsTrackLB[:,0]= slbd[:,0] self._interpolatedObsTrackLB[:,1]= slbd[:,1] self._interpolatedObsTrackLB[:,2]= slbd[:,2] self._interpolatedObsTrackLB[:,3]= svlbd[:,0] self._interpolatedObsTrackLB[:,4]= svlbd[:,1] self._interpolatedObsTrackLB[:,5]= svlbd[:,2] if hasattr(self,'_allErrCovsLBUnscaled'): #Re-calculate this self._determine_stream_spreadLB(simple=_USESIMPLE, Vnorm=Vnorm,Rnorm=Rnorm, R0=R0,Zsun=Zsun,vsun=vsun) return None def _find_closest_trackpoint(self,R,vR,vT,z,vz,phi,interp=True,xy=False, usev=False): """For backward compatibility""" return self.find_closest_trackpoint(R,vR,vT,z,vz,phi, interp=interp,xy=xy, usev=usev) def find_closest_trackpoint(self,R,vR,vT,z,vz,phi,interp=True,xy=False, usev=False): """ NAME: find_closest_trackpoint PURPOSE: find the closest point on the stream track to a given point INPUT: R,vR,vT,z,vz,phi - phase-space coordinates of the given point interp= (True), if True, return the index of the interpolated track xy= (False) if True, input is X,Y,Z,vX,vY,vZ in Galactocentric rectangular coordinates; if xy, some coordinates may be missing (given as None) and they will not be used usev= (False) if True, also use velocities to find the closest point OUTPUT: index into the track of the closest track point HISTORY: 2013-12-04 - Written - Bovy (IAS) """ if xy: X= R Y= vR Z= vT else: X= R*numpy.cos(phi) Y= R*numpy.sin(phi) Z= z if xy and usev: vX= z vY= vz vZ= phi elif usev: vX= vR*numpy.cos(phi)-vT*numpy.sin(phi) vY= vR*numpy.sin(phi)+vT*numpy.cos(phi) vZ= vz present= [not X is None,not Y is None,not Z is None] if usev: present.extend([not vX is None,not vY is None,not vZ is None]) present= numpy.array(present,dtype='float') if X is None: X= 0. if Y is None: Y= 0. if Z is None: Z= 0. if usev and vX is None: vX= 0. if usev and vY is None: vY= 0. if usev and vZ is None: vZ= 0. if interp: dist2= present[0]*(X-self._interpolatedObsTrackXY[:,0])**2.\ +present[1]*(Y-self._interpolatedObsTrackXY[:,1])**2.\ +present[2]*(Z-self._interpolatedObsTrackXY[:,2])**2. if usev: dist2+= present[3]*(vX-self._interpolatedObsTrackXY[:,3])**2.\ +present[4]*(vY-self._interpolatedObsTrackXY[:,4])**2.\ +present[5]*(vZ-self._interpolatedObsTrackXY[:,5])**2. else: dist2= present[0]*(X-self._ObsTrackXY[:,0])**2.\ +present[1]*(Y-self._ObsTrackXY[:,1])**2.\ +present[2]*(Z-self._ObsTrackXY[:,2])**2. if usev: dist2+= present[3]*(vX-self._ObsTrackXY[:,3])**2.\ +present[4]*(vY-self._ObsTrackXY[:,4])**2.\ +present[5]*(vZ-self._ObsTrackXY[:,5])**2. return numpy.argmin(dist2) def _find_closest_trackpointLB(self,l,b,D,vlos,pmll,pmbb,interp=True, usev=False): return self.find_closest_trackpointLB(l,b,D,vlos,pmll,pmbb, interp=interp, usev=usev) def find_closest_trackpointLB(self,l,b,D,vlos,pmll,pmbb,interp=True, usev=False): """ NAME: find_closest_trackpointLB PURPOSE: find the closest point on the stream track to a given point in (l,b,...) coordinates INPUT: l,b,D,vlos,pmll,pmbb- coordinates in (deg,deg,kpc,km/s,mas/yr,mas/yr) interp= (True) if True, return the closest index on the interpolated track usev= (False) if True, also use the velocity components (default is to only use the positions) OUTPUT: index of closest track point on the interpolated or not-interpolated track HISTORY: 2013-12-17- Written - Bovy (IAS) """ if interp: nTrackPoints= len(self._interpolatedThetasTrack) else: nTrackPoints= len(self._thetasTrack) if l is None: l= 0. trackL= numpy.zeros(nTrackPoints) elif interp: trackL= self._interpolatedObsTrackLB[:,0] else: trackL= self._ObsTrackLB[:,0] if b is None: b= 0. trackB= numpy.zeros(nTrackPoints) elif interp: trackB= self._interpolatedObsTrackLB[:,1] else: trackB= self._ObsTrackLB[:,1] if D is None: D= 1. trackD= numpy.ones(nTrackPoints) elif interp: trackD= self._interpolatedObsTrackLB[:,2] else: trackD= self._ObsTrackLB[:,2] if usev: if vlos is None: vlos= 0. trackVlos= numpy.zeros(nTrackPoints) elif interp: trackVlos= self._interpolatedObsTrackLB[:,3] else: trackVlos= self._ObsTrackLB[:,3] if pmll is None: pmll= 0. trackPmll= numpy.zeros(nTrackPoints) elif interp: trackPmll= self._interpolatedObsTrackLB[:,4] else: trackPmll= self._ObsTrackLB[:,4] if pmbb is None: pmbb= 0. trackPmbb= numpy.zeros(nTrackPoints) elif interp: trackPmbb= self._interpolatedObsTrackLB[:,5] else: trackPmbb= self._ObsTrackLB[:,5] #Calculate rectangular coordinates XYZ= bovy_coords.lbd_to_XYZ(l,b,D,degree=True) trackXYZ= bovy_coords.lbd_to_XYZ(trackL,trackB,trackD,degree=True) if usev: vxvyvz= bovy_coords.vrpmllpmbb_to_vxvyvz(vlos,pmll,pmbb, XYZ[0],XYZ[1],XYZ[2], XYZ=True) trackvxvyvz= bovy_coords.vrpmllpmbb_to_vxvyvz(trackVlos,trackPmll, trackPmbb, trackXYZ[:,0], trackXYZ[:,1], trackXYZ[:,2], XYZ=True) #Calculate distance dist2= (XYZ[0]-trackXYZ[:,0])**2.\ +(XYZ[1]-trackXYZ[:,1])**2.\ +(XYZ[2]-trackXYZ[:,2])**2. if usev: dist2+= (vxvyvz[0]-trackvxvyvz[:,0])**2.\ +(vxvyvz[1]-trackvxvyvz[:,1])**2.\ +(vxvyvz[2]-trackvxvyvz[:,2])**2. return numpy.argmin(dist2) def _find_closest_trackpointaA(self,Or,Op,Oz,ar,ap,az,interp=True): """ NAME: _find_closest_trackpointaA PURPOSE: find the closest point on the stream track to a given point in frequency-angle coordinates INPUT: Or,Op,Oz,ar,ap,az - phase-space coordinates of the given point interp= (True), if True, return the index of the interpolated track OUTPUT: index into the track of the closest track point HISTORY: 2013-12-22 - Written - Bovy (IAS) """ #Calculate angle offset along the stream parallel to the stream track angle= numpy.hstack((ar,ap,az)) da= angle-self._progenitor_angle dapar= self._sigMeanSign*numpy.sum(da*self._dsigomeanProgDirection) if interp: dist= numpy.fabs(dapar-self._interpolatedThetasTrack) else: dist= numpy.fabs(dapar-self._thetasTrack) return numpy.argmin(dist) #########DISTRIBUTION AS A FUNCTION OF ANGLE ALONG THE STREAM################## def meanOmega(self,dangle,oned=False): """ NAME: meanOmega PURPOSE: calculate the mean frequency as a function of angle, assuming a uniform time distribution up to a maximum time INPUT: dangle - angle offset oned= (False) if True, return the 1D offset from the progenitor (along the direction of disruption) OUTPUT: mean Omega HISTORY: 2013-12-01 - Written - Bovy (IAS) """ dOmin= dangle/self._tdisrupt meandO= self._meandO dO1D= ((numpy.sqrt(2./numpy.pi)*numpy.sqrt(self._sortedSigOEig[2])\ *numpy.exp(-0.5*(meandO-dOmin)**2.\ /self._sortedSigOEig[2])/ (1.+special.erf((meandO-dOmin)\ /numpy.sqrt(2.*self._sortedSigOEig[2]))))\ +meandO) if oned: return dO1D else: return self._progenitor_Omega+dO1D*self._dsigomeanProgDirection\ *self._sigMeanSign def sigOmega(self,dangle): """ NAME: sigmaOmega PURPOSE: calculate the 1D sigma in frequency as a function of angle, assuming a uniform time distribution up to a maximum time INPUT: dangle - angle offset OUTPUT: sigma Omega HISTORY: 2013-12-05 - Written - Bovy (IAS) """ dOmin= dangle/self._tdisrupt meandO= self._meandO sO1D2= ((numpy.sqrt(2./numpy.pi)*numpy.sqrt(self._sortedSigOEig[2])\ *(meandO+dOmin)\ *numpy.exp(-0.5*(meandO-dOmin)**2.\ /self._sortedSigOEig[2])/ (1.+special.erf((meandO-dOmin)\ /numpy.sqrt(2.*self._sortedSigOEig[2]))))\ +meandO**2.+self._sortedSigOEig[2]) mO= self.meanOmega(dangle,oned=True) return numpy.sqrt(sO1D2-mO**2.) def ptdAngle(self,t,dangle): """ NAME: ptdangle PURPOSE: return the probability of a given stripping time at a given angle along the stream INPUT: t - stripping time dangle - angle offset along the stream OUTPUT: p(td|dangle) HISTORY: 2013-12-05 - Written - Bovy (IAS) """ if isinstance(t,(int,float,numpy.float32,numpy.float64)): t= numpy.array([t]) out= numpy.zeros(len(t)) if t > 0.: dO= dangle/t[t < self._tdisrupt] else: return 0. #p(t|a) = \int dO p(O,t|a) = \int dO p(t|O,a) p(O|a) = \int dO delta (t-a/O)p(O|a) = O*2/a p(O|a); p(O|a) = \int dt p(a|O,t) p(O)p(t) = 1/O p(O) out[t < self._tdisrupt]=\ dO**2./dangle*numpy.exp(-0.5*(dO-self._meandO)**2.\ /self._sortedSigOEig[2])/\ numpy.sqrt(self._sortedSigOEig[2]) return out def meantdAngle(self,dangle): """ NAME: meantdAngle PURPOSE: calculate the mean stripping time at a given angle INPUT: dangle - angle offset along the stream OUTPUT: mean stripping time at this dangle HISTORY: 2013-12-05 - Written - Bovy (IAS) """ Tlow= dangle/(self._meandO+3.*numpy.sqrt(self._sortedSigOEig[2])) Thigh= dangle/(self._meandO-3.*numpy.sqrt(self._sortedSigOEig[2])) num= integrate.quad(lambda x: x*self.ptdAngle(x,dangle), Tlow,Thigh)[0] denom= integrate.quad(self.ptdAngle,Tlow,Thigh,(dangle,))[0] if denom == 0.: return self._tdisrupt elif numpy.isnan(denom): return 0. else: return num/denom def sigtdAngle(self,dangle): """ NAME: sigtdAngle PURPOSE: calculate the dispersion in the stripping times at a given angle INPUT: dangle - angle offset along the stream OUTPUT: dispersion in the stripping times at this angle HISTORY: 2013-12-05 - Written - Bovy (IAS) """ Tlow= dangle/(self._meandO+3.*numpy.sqrt(self._sortedSigOEig[2])) Thigh= dangle/(self._meandO-3.*numpy.sqrt(self._sortedSigOEig[2])) numsig2= integrate.quad(lambda x: x**2.*self.ptdAngle(x,dangle), Tlow,Thigh)[0] nummean= integrate.quad(lambda x: x*self.ptdAngle(x,dangle), Tlow,Thigh)[0] denom= integrate.quad(self.ptdAngle,Tlow,Thigh,(dangle,))[0] if denom == 0.: return numpy.nan else: return numpy.sqrt(numsig2/denom-(nummean/denom)**2.) def pangledAngle(self,angleperp,dangle,smallest=False): """ NAME: pangledAngle PURPOSE: return the probability of a given perpendicular angle at a given angle along the stream INPUT: angleperp - perpendicular angle dangle - angle offset along the stream smallest= (False) calculate for smallest eigenvalue direction rather than for middle OUTPUT: p(angle_perp|dangle) HISTORY: 2013-12-06 - Written - Bovy (IAS) """ if isinstance(angleperp,(int,float,numpy.float32,numpy.float64)): angleperp= numpy.array([angleperp]) out= numpy.zeros(len(angleperp)) out= numpy.array([\ integrate.quad(self._pangledAnglet,0.,self._tdisrupt, (ap,dangle,smallest))[0] for ap in angleperp]) return out def meanangledAngle(self,dangle,smallest=False): """ NAME: meanangledAngle PURPOSE: calculate the mean perpendicular angle at a given angle INPUT: dangle - angle offset along the stream smallest= (False) calculate for smallest eigenvalue direction rather than for middle OUTPUT: mean perpendicular angle HISTORY: 2013-12-06 - Written - Bovy (IAS) """ if smallest: eigIndx= 0 else: eigIndx= 1 aplow= numpy.amax([numpy.sqrt(self._sortedSigOEig[eigIndx])\ *self._tdisrupt*5., self._sigangle]) num= integrate.quad(lambda x: x*self.pangledAngle(x,dangle,smallest), aplow,-aplow)[0] denom= integrate.quad(self.pangledAngle,aplow,-aplow, (dangle,smallest))[0] if denom == 0.: return numpy.nan else: return num/denom def sigangledAngle(self,dangle,assumeZeroMean=True,smallest=False, simple=False): """ NAME: sigangledAngle PURPOSE: calculate the dispersion in the perpendicular angle at a given angle INPUT: dangle - angle offset along the stream assumeZeroMean= (True) if True, assume that the mean is zero (should be) smallest= (False) calculate for smallest eigenvalue direction rather than for middle simple= (False), if True, return an even simpler estimate OUTPUT: dispersion in the perpendicular angle at this angle HISTORY: 2013-12-06 - Written - Bovy (IAS) """ if smallest: eigIndx= 0 else: eigIndx= 1 if simple: dt= self.meantdAngle(dangle) return numpy.sqrt(self._sigangle2 +self._sortedSigOEig[eigIndx]*dt**2.) aplow= numpy.amax([numpy.sqrt(self._sortedSigOEig[eigIndx])*self._tdisrupt*5., self._sigangle]) numsig2= integrate.quad(lambda x: x**2.*self.pangledAngle(x,dangle), aplow,-aplow)[0] if not assumeZeroMean: nummean= integrate.quad(lambda x: x*self.pangledAngle(x,dangle), aplow,-aplow)[0] else: nummean= 0. denom= integrate.quad(self.pangledAngle,aplow,-aplow,(dangle,))[0] if denom == 0.: return numpy.nan else: return numpy.sqrt(numsig2/denom-(nummean/denom)**2.) def _pangledAnglet(self,t,angleperp,dangle,smallest): """p(angle_perp|angle_par,time)""" if smallest: eigIndx= 0 else: eigIndx= 1 if isinstance(angleperp,(int,float,numpy.float32,numpy.float64)): angleperp= numpy.array([angleperp]) t= numpy.array([t]) out= numpy.zeros_like(angleperp) tindx= t < self._tdisrupt out[tindx]=\ numpy.exp(-0.5*angleperp[tindx]**2.\ /(t[tindx]**2.*self._sortedSigOEig[eigIndx]+self._sigangle2))/\ numpy.sqrt(t[tindx]**2.*self._sortedSigOEig[eigIndx]+self._sigangle2)\ *self.ptdAngle(t[t < self._tdisrupt],dangle) return out ################APPROXIMATE FREQUENCY-ANGLE TRANSFORMATION##################### def _approxaA(self,R,vR,vT,z,vz,phi,interp=True): """ NAME: _approxaA PURPOSE: return action-angle coordinates for a point based on the linear approximation around the stream track INPUT: R,vR,vT,z,vz,phi - phase-space coordinates of the given point interp= (True), if True, use the interpolated track OUTPUT: (Or,Op,Oz,ar,ap,az) HISTORY: 2013-12-03 - Written - Bovy (IAS) """ if isinstance(R,(int,float,numpy.float32,numpy.float64)): #Scalar input R= numpy.array([R]) vR= numpy.array([vR]) vT= numpy.array([vT]) z= numpy.array([z]) vz= numpy.array([vz]) phi= numpy.array([phi]) closestIndx= [self._find_closest_trackpoint(R[ii],vR[ii],vT[ii], z[ii],vz[ii],phi[ii], interp=interp, xy=False) for ii in range(len(R))] out= numpy.empty((6,len(R))) for ii in range(len(R)): dxv= numpy.empty(6) if interp: dxv[0]= R[ii]-self._interpolatedObsTrack[closestIndx[ii],0] dxv[1]= vR[ii]-self._interpolatedObsTrack[closestIndx[ii],1] dxv[2]= vT[ii]-self._interpolatedObsTrack[closestIndx[ii],2] dxv[3]= z[ii]-self._interpolatedObsTrack[closestIndx[ii],3] dxv[4]= vz[ii]-self._interpolatedObsTrack[closestIndx[ii],4] dxv[5]= phi[ii]-self._interpolatedObsTrack[closestIndx[ii],5] jacIndx= self._find_closest_trackpoint(R[ii],vR[ii],vT[ii], z[ii],vz[ii],phi[ii], interp=False, xy=False) else: dxv[0]= R[ii]-self._ObsTrack[closestIndx[ii],0] dxv[1]= vR[ii]-self._ObsTrack[closestIndx[ii],1] dxv[2]= vT[ii]-self._ObsTrack[closestIndx[ii],2] dxv[3]= z[ii]-self._ObsTrack[closestIndx[ii],3] dxv[4]= vz[ii]-self._ObsTrack[closestIndx[ii],4] dxv[5]= phi[ii]-self._ObsTrack[closestIndx[ii],5] jacIndx= closestIndx[ii] #Make sure phi hasn't wrapped around if dxv[5] > numpy.pi: dxv[5]-= 2.*numpy.pi elif dxv[5] < -numpy.pi: dxv[5]+= 2.*numpy.pi #Apply closest jacobian out[:,ii]= numpy.dot(self._alljacsTrack[jacIndx,:,:], dxv) if interp: out[:,ii]+= self._interpolatedObsTrackAA[closestIndx[ii]] else: out[:,ii]+= self._ObsTrackAA[closestIndx[ii]] return out def _approxaAInv(self,Or,Op,Oz,ar,ap,az,interp=True): """ NAME: _approxaAInv PURPOSE: return R,vR,... coordinates for a point based on the linear approximation around the stream track INPUT: Or,Op,Oz,ar,ap,az - phase space coordinates in frequency-angle space interp= (True), if True, use the interpolated track OUTPUT: (R,vR,vT,z,vz,phi) HISTORY: 2013-12-22 - Written - Bovy (IAS) """ if isinstance(Or,(int,float,numpy.float32,numpy.float64)): #Scalar input Or= numpy.array([Or]) Op= numpy.array([Op]) Oz= numpy.array([Oz]) ar= numpy.array([ar]) ap= numpy.array([ap]) az= numpy.array([az]) #Calculate apar, angle offset along the stream closestIndx= [self._find_closest_trackpointaA(Or[ii],Op[ii],Oz[ii], ar[ii],ap[ii],az[ii], interp=interp)\ for ii in range(len(Or))] out= numpy.empty((6,len(Or))) for ii in range(len(Or)): dOa= numpy.empty(6) if interp: dOa[0]= Or[ii]-self._interpolatedObsTrackAA[closestIndx[ii],0] dOa[1]= Op[ii]-self._interpolatedObsTrackAA[closestIndx[ii],1] dOa[2]= Oz[ii]-self._interpolatedObsTrackAA[closestIndx[ii],2] dOa[3]= ar[ii]-self._interpolatedObsTrackAA[closestIndx[ii],3] dOa[4]= ap[ii]-self._interpolatedObsTrackAA[closestIndx[ii],4] dOa[5]= az[ii]-self._interpolatedObsTrackAA[closestIndx[ii],5] jacIndx= self._find_closest_trackpointaA(Or[ii],Op[ii],Oz[ii], ar[ii],ap[ii],az[ii], interp=False) else: dOa[0]= Or[ii]-self._ObsTrackAA[closestIndx[ii],0] dOa[1]= Op[ii]-self._ObsTrackAA[closestIndx[ii],1] dOa[2]= Oz[ii]-self._ObsTrackAA[closestIndx[ii],2] dOa[3]= ar[ii]-self._ObsTrackAA[closestIndx[ii],3] dOa[4]= ap[ii]-self._ObsTrackAA[closestIndx[ii],4] dOa[5]= az[ii]-self._ObsTrackAA[closestIndx[ii],5] jacIndx= closestIndx[ii] #Make sure the angles haven't wrapped around if dOa[3] > numpy.pi: dOa[3]-= 2.*numpy.pi elif dOa[3] < -numpy.pi: dOa[3]+= 2.*numpy.pi if dOa[4] > numpy.pi: dOa[4]-= 2.*numpy.pi elif dOa[4] < -numpy.pi: dOa[4]+= 2.*numpy.pi if dOa[5] > numpy.pi: dOa[5]-= 2.*numpy.pi elif dOa[5] < -numpy.pi: dOa[5]+= 2.*numpy.pi #Apply closest jacobian out[:,ii]= numpy.dot(self._allinvjacsTrack[jacIndx,:,:], dOa) if interp: out[:,ii]+= self._interpolatedObsTrack[closestIndx[ii]] else: out[:,ii]+= self._ObsTrack[closestIndx[ii]] return out ################################EVALUATE THE DF################################ def __call__(self,*args,**kwargs): """ NAME: __call__ PURPOSE: evaluate the DF INPUT: Either: a) R,vR,vT,z,vz,phi ndarray [nobjects] b) (Omegar,Omegaphi,Omegaz,angler,anglephi,anglez) tuple if aAInput where: Omegar - radial frequency Omegaphi - azimuthal frequency Omegaz - vertical frequency angler - radial angle anglephi - azimuthal angle anglez - vertical angle c) Orbit instance or list thereof log= if True, return the natural log aaInput= (False) if True, option b above OUTPUT: value of DF HISTORY: 2013-12-03 - Written - Bovy (IAS) """ #First parse log log= kwargs.pop('log',True) dOmega, dangle= self.prepData4Call(*args,**kwargs) #Omega part dOmega4dfOmega= dOmega\ -numpy.tile(self._dsigomeanProg.T,(dOmega.shape[1],1)).T logdfOmega= -0.5*numpy.sum(dOmega4dfOmega* numpy.dot(self._sigomatrixinv, dOmega4dfOmega), axis=0)-0.5*self._sigomatrixLogdet\ +numpy.log(numpy.fabs(numpy.dot(self._dsigomeanProgDirection,dOmega))) #Angle part dangle2= numpy.sum(dangle**2.,axis=0) dOmega2= numpy.sum(dOmega**2.,axis=0) dOmegaAngle= numpy.sum(dOmega*dangle,axis=0) logdfA= -0.5/self._sigangle2*(dangle2-dOmegaAngle**2./dOmega2)\ -2.*self._lnsigangle-0.5*numpy.log(dOmega2) #Finite stripping part a0= dOmegaAngle/numpy.sqrt(2.)/self._sigangle/numpy.sqrt(dOmega2) ad= numpy.sqrt(dOmega2)/numpy.sqrt(2.)/self._sigangle\ *(self._tdisrupt-dOmegaAngle/dOmega2) loga= numpy.log((special.erf(a0)+special.erf(ad))/2.) #divided by 2 st 0 for well-within the stream out= logdfA+logdfOmega+loga+self._logmeandetdOdJp if log: return out else: return numpy.exp(out) def prepData4Call(self,*args,**kwargs): """ NAME: prepData4Call PURPOSE: prepare stream data for the __call__ method INPUT: __call__ inputs OUTPUT: (dOmega,dangle); wrt the progenitor; each [3,nobj] HISTORY: 2013-12-04 - Written - Bovy (IAS) """ #First calculate the actionAngle coordinates if they're not given #as such freqsAngles= self._parse_call_args(*args,**kwargs) dOmega= freqsAngles[:3,:]\ -numpy.tile(self._progenitor_Omega.T,(freqsAngles.shape[1],1)).T dangle= freqsAngles[3:,:]\ -numpy.tile(self._progenitor_angle.T,(freqsAngles.shape[1],1)).T #Assuming single wrap, resolve large angle differences (wraps should be marginalized over) dangle[(dangle < -4.)]+= 2.*numpy.pi dangle[(dangle > 4.)]-= 2.*numpy.pi return (dOmega,dangle) def _parse_call_args(self,*args,**kwargs): """Helper function to parse the arguments to the __call__ and related functions, return [6,nobj] array of frequencies (:3) and angles (3:)""" interp= kwargs.get('interp',self._useInterp) if len(args) == 5: raise IOError("Must specify phi for streamdf") elif len(args) == 6: if kwargs.get('aAInput',False): if isinstance(args[0],(int,float,numpy.float32,numpy.float64)): out= numpy.empty((6,1)) else: out= numpy.empty((6,len(args[0]))) for ii in range(6): out[ii,:]= args[ii] return out else: return self._approxaA(*args,interp=interp) elif isinstance(args[0],Orbit): o= args[0] return self._approxaA(o.R(),o.vR(),o.vT(),o.z(),o.vz(),o.phi(), interp=interp) elif isinstance(args[0],list) and isinstance(args[0][0],Orbit): R, vR, vT, z, vz, phi= [], [], [], [], [], [] for o in args[0]: R.append(o.R()) vR.append(o.vR()) vT.append(o.vT()) z.append(o.z()) vz.append(o.vz()) phi.append(o.phi()) return self._approxaA(numpy.array(R),numpy.array(vR), numpy.array(vT),numpy.array(z), numpy.array(vz),numpy.array(phi), interp=interp) def callMarg(self,xy,**kwargs): """ NAME: callMarg PURPOSE: evaluate the DF, marginalizing over some directions, in Galactocentric rectangular coordinates (or in observed l,b,D,vlos,pmll,pmbb) coordinates) INPUT: xy - phase-space point [X,Y,Z,vX,vY,vZ]; the distribution of the dimensions set to None is returned interp= (object-wide interp default) if True, use the interpolated stream track cindx= index of the closest point on the (interpolated) stream track if not given, determined from the dimensions given nsigma= (3) number of sigma to marginalize the DF over (approximate sigma) ngl= (5) order of Gauss-Legendre integration lb= (False) if True, xy contains [l,b,D,vlos,pmll,pmbb] in [deg,deg,kpc,km/s,mas/yr,mas/yr] and the marginalized PDF in these coordinates is returned Vnorm= (220) circular velocity to normalize with when lb=True Rnorm= (8) Galactocentric radius to normalize with when lb=True R0= (8) Galactocentric radius of the Sun (kpc) Zsun= (0.025) Sun's height above the plane (kpc) vsun= ([-11.1,241.92,7.25]) Sun's motion in cylindrical coordinates (vR positive away from center) OUTPUT: p(xy) marginalized over missing directions in xy HISTORY: 2013-12-16 - Written - Bovy (IAS) """ coordGiven= numpy.array([not x is None for x in xy],dtype='bool') if numpy.sum(coordGiven) == 6: raise NotImplementedError("When specifying all coordinates, please use __call__ instead of callMarg") #First construct the Gaussian approximation at this xy gaussmean, gaussvar= self.gaussApprox(xy,**kwargs) cholvar, chollower= stable_cho_factor(gaussvar) #Now Gauss-legendre integrate over missing directions ngl= kwargs.get('ngl',5) nsigma= kwargs.get('nsigma',3) glx, glw= numpy.polynomial.legendre.leggauss(ngl) coordEval= [] weightEval= [] jj= 0 baseX= (glx+1)/2. baseX= list(baseX) baseX.extend(-(glx+1)/2.) baseX= numpy.array(baseX) baseW= glw baseW= list(baseW) baseW.extend(glw) baseW= numpy.array(baseW) for ii in range(6): if not coordGiven[ii]: coordEval.append(nsigma*baseX) weightEval.append(baseW) jj+= 1 else: coordEval.append(xy[ii]*numpy.ones(1)) weightEval.append(numpy.ones(1)) mgrid= numpy.meshgrid(*coordEval,indexing='ij') mgridNotGiven= numpy.array([mgrid[ii].flatten() for ii in range(6) if not coordGiven[ii]]) mgridNotGiven= numpy.dot(cholvar,mgridNotGiven) jj= 0 if coordGiven[0]: iX= mgrid[0] else: iX= mgridNotGiven[jj]+gaussmean[jj] jj+= 1 if coordGiven[1]: iY= mgrid[1] else: iY= mgridNotGiven[jj]+gaussmean[jj] jj+= 1 if coordGiven[2]: iZ= mgrid[2] else: iZ= mgridNotGiven[jj]+gaussmean[jj] jj+= 1 if coordGiven[3]: ivX= mgrid[3] else: ivX= mgridNotGiven[jj]+gaussmean[jj] jj+= 1 if coordGiven[4]: ivY= mgrid[4] else: ivY= mgridNotGiven[jj]+gaussmean[jj] jj+= 1 if coordGiven[5]: ivZ= mgrid[5] else: ivZ= mgridNotGiven[jj]+gaussmean[jj] jj+= 1 iXw, iYw, iZw, ivXw, ivYw, ivZw=\ numpy.meshgrid(*weightEval,indexing='ij') if kwargs.get('lb',False): #Convert to Galactocentric cylindrical coordinates #Setup coordinate transformation kwargs Vnorm= kwargs.get('Vnorm',self._Vnorm) Rnorm= kwargs.get('Rnorm',self._Rnorm) R0= kwargs.get('R0',self._R0) Zsun= kwargs.get('Zsun',self._Zsun) vsun= kwargs.get('vsun',self._vsun) tXYZ= bovy_coords.lbd_to_XYZ(iX.flatten(),iY.flatten(), iZ.flatten(), degree=True) iR,iphi,iZ= bovy_coords.XYZ_to_galcencyl(tXYZ[:,0],tXYZ[:,1], tXYZ[:,2], Xsun=R0,Ysun=0.,Zsun=Zsun) tvxvyvz= bovy_coords.vrpmllpmbb_to_vxvyvz(ivX.flatten(), ivY.flatten(), ivZ.flatten(), tXYZ[:,0],tXYZ[:,1], tXYZ[:,2],XYZ=True) ivR,ivT,ivZ= bovy_coords.vxvyvz_to_galcencyl(tvxvyvz[:,0], tvxvyvz[:,1], tvxvyvz[:,2], iR,iphi,iZ, galcen=True, vsun=vsun) iR/= Rnorm iZ/= Rnorm ivR/= Vnorm ivT/= Vnorm ivZ/= Vnorm else: #Convert to cylindrical coordinates iR,iphi,iZ=\ bovy_coords.rect_to_cyl(iX.flatten(),iY.flatten(),iZ.flatten()) ivR,ivT,ivZ=\ bovy_coords.rect_to_cyl_vec(ivX.flatten(),ivY.flatten(), ivZ.flatten(), iR,iphi,iZ,cyl=True) #Add the additional Jacobian dXdY/dldb... if necessary if kwargs.get('lb',False): #Find the nearest track point interp= kwargs.get('interp',self._useInterp) if not 'cindx' in kwargs: cindx= self._find_closest_trackpointLB(*xy,interp=interp, usev=True) else: cindx= kwargs['cindx'] #Only l,b,d,... to Galactic X,Y,Z,... is necessary because going #from Galactic to Galactocentric has Jacobian determinant 1 if interp: addLogDet= self._interpolatedTrackLogDetJacLB[cindx] else: addLogDet= self._trackLogDetJacLB[cindx] else: addLogDet= 0. logdf= self(iR,ivR,ivT,iZ,ivZ,iphi,log=True) return logsumexp(logdf +numpy.log(iXw.flatten()) +numpy.log(iYw.flatten()) +numpy.log(iZw.flatten()) +numpy.log(ivXw.flatten()) +numpy.log(ivYw.flatten()) +numpy.log(ivZw.flatten()))\ +0.5*numpy.log(numpy.linalg.det(gaussvar))\ +addLogDet def gaussApprox(self,xy,**kwargs): """ NAME: gaussApprox PURPOSE: return the mean and variance of a Gaussian approximation to the stream DF at a given phase-space point in Galactocentric rectangular coordinates (distribution is over missing directions) INPUT: xy - phase-space point [X,Y,Z,vX,vY,vZ]; the distribution of the dimensions set to None is returned interp= (object-wide interp default) if True, use the interpolated stream track cindx= index of the closest point on the (interpolated) stream track if not given, determined from the dimensions given lb= (False) if True, xy contains [l,b,D,vlos,pmll,pmbb] in [deg,deg,kpc,km/s,mas/yr,mas/yr] and the Gaussian approximation in these coordinates is returned OUTPUT: (mean,variance) of the approximate Gaussian DF for the missing directions in xy HISTORY: 2013-12-12 - Written - Bovy (IAS) """ interp= kwargs.get('interp',self._useInterp) lb= kwargs.get('lb',False) #What are we looking for coordGiven= numpy.array([not x is None for x in xy],dtype='bool') nGiven= numpy.sum(coordGiven) #First find the nearest track point if not 'cindx' in kwargs and lb: cindx= self._find_closest_trackpointLB(*xy,interp=interp, usev=True) elif not 'cindx' in kwargs and not lb: cindx= self._find_closest_trackpoint(*xy,xy=True,interp=interp, usev=True) else: cindx= kwargs['cindx'] #Get the covariance matrix if interp and lb: tcov= self._interpolatedAllErrCovsLBUnscaled[cindx] tmean= self._interpolatedObsTrackLB[cindx] elif interp and not lb: tcov= self._interpolatedAllErrCovsXY[cindx] tmean= self._interpolatedObsTrackXY[cindx] elif not interp and lb: tcov= self._allErrCovsLBUnscaled[cindx] tmean= self._ObsTrackLB[cindx] elif not interp and not lb: tcov= self._allErrCovsXY[cindx] tmean= self._ObsTrackXY[cindx] if lb:#Apply scale factors tcov= copy.copy(tcov) tcov*= numpy.tile(self._ErrCovsLBScale,(6,1)) tcov*= numpy.tile(self._ErrCovsLBScale,(6,1)).T #Fancy indexing to recover V22, V11, and V12; V22, V11, V12 as in Appendix B of 0905.2979v1 V11indx0= numpy.array([[ii for jj in range(6-nGiven)] for ii in range(6) if not coordGiven[ii]]) V11indx1= numpy.array([[ii for ii in range(6) if not coordGiven[ii]] for jj in range(6-nGiven)]) V11= tcov[V11indx0,V11indx1] V22indx0= numpy.array([[ii for jj in range(nGiven)] for ii in range(6) if coordGiven[ii]]) V22indx1= numpy.array([[ii for ii in range(6) if coordGiven[ii]] for jj in range(nGiven)]) V22= tcov[V22indx0,V22indx1] V12indx0= numpy.array([[ii for jj in range(nGiven)] for ii in range(6) if not coordGiven[ii]]) V12indx1= numpy.array([[ii for ii in range(6) if coordGiven[ii]] for jj in range(6-nGiven)]) V12= tcov[V12indx0,V12indx1] #Also get m1 and m2, again following Appendix B of 0905.2979v1 m1= tmean[True-coordGiven] m2= tmean[coordGiven] #conditional mean and variance V22inv= numpy.linalg.inv(V22) v2= numpy.array([xy[ii] for ii in range(6) if coordGiven[ii]]) condMean= m1+numpy.dot(V12,numpy.dot(V22inv,v2-m2)) condVar= V11-numpy.dot(V12,numpy.dot(V22inv,V12.T)) return (condMean,condVar) ################################SAMPLE THE DF################################## def sample(self,n,returnaAdt=False,returndt=False,interp=None, xy=False,lb=False, Vnorm=None,Rnorm=None, R0=None,Zsun=None,vsun=None): """ NAME: sample PURPOSE: sample from the DF INPUT: n - number of points to return returnaAdt= (False) if True, return (Omega,angle,dt) returndT= (False) if True, also return the time since the star was stripped interp= (object-wide default) use interpolation of the stream track xy= (False) if True, return Galactocentric rectangular coordinates lb= (False) if True, return Galactic l,b,d,vlos,pmll,pmbb coordinates +Coordinate transformation inputs (all default to the instance-wide values): Vnorm= circular velocity to normalize velocities with Rnorm= Galactocentric radius to normalize positions with R0= Galactocentric radius of the Sun (kpc) Zsun= Sun's height above the plane (kpc) vsun= Sun's motion in cylindrical coordinates (vR positive away from center) OUTPUT: (R,vR,vT,z,vz,phi) of points on the stream in 6,N array HISTORY: 2013-12-22 - Written - Bovy (IAS) """ if interp is None: interp= self._useInterp #First sample frequencies #Sample frequency along largest eigenvalue using ARS dO1s=\ bovy_ars.bovy_ars([0.,0.],[True,False], [self._meandO-numpy.sqrt(self._sortedSigOEig[2]), self._meandO+numpy.sqrt(self._sortedSigOEig[2])], _h_ars,_hp_ars,nsamples=n, hxparams=(self._meandO,self._sortedSigOEig[2]), maxn=100) dO1s= numpy.array(dO1s)*self._sigMeanSign dO2s= numpy.random.normal(size=n)*numpy.sqrt(self._sortedSigOEig[1]) dO3s= numpy.random.normal(size=n)*numpy.sqrt(self._sortedSigOEig[0]) #Rotate into dOs in R,phi,z coordinates dO= numpy.vstack((dO3s,dO2s,dO1s)) dO= numpy.dot(self._sigomatrixEig[1][:,self._sigomatrixEigsortIndx], dO) Om= dO+numpy.tile(self._progenitor_Omega.T,(n,1)).T #Also generate angles da= numpy.random.normal(size=(3,n))*self._sigangle #And a random time dt= numpy.random.uniform(size=n)*self._tdisrupt #Integrate the orbits relative to the progenitor da+= dO*numpy.tile(dt,(3,1)) angle= da+numpy.tile(self._progenitor_angle.T,(n,1)).T if returnaAdt: return (Om,angle,dt) #Propagate to R,vR,etc. RvR= self._approxaAInv(Om[0,:],Om[1,:],Om[2,:], angle[0,:],angle[1,:],angle[2,:], interp=interp) if returndt and not xy and not lb: return (RvR,dt) elif not xy and not lb: return RvR if xy: sX= RvR[0]*numpy.cos(RvR[5]) sY= RvR[0]*numpy.sin(RvR[5]) sZ= RvR[3] svX, svY, svZ=\ bovy_coords.cyl_to_rect_vec(RvR[1], RvR[2], RvR[4], RvR[5]) out= numpy.empty((6,n)) out[0]= sX out[1]= sY out[2]= sZ out[3]= svX out[4]= svY out[5]= svZ if returndt: return (out,dt) else: return out if lb: if Vnorm is None: Vnorm= self._Vnorm if Rnorm is None: Rnorm= self._Rnorm if R0 is None: R0= self._R0 if Zsun is None: Zsun= self._Zsun if vsun is None: vsun= self._vsun XYZ= bovy_coords.galcencyl_to_XYZ(RvR[0]*Rnorm, RvR[5], RvR[3]*Rnorm, Xsun=R0,Zsun=Zsun) vXYZ= bovy_coords.galcencyl_to_vxvyvz(RvR[1]*Vnorm, RvR[2]*Vnorm, RvR[4]*Vnorm, RvR[5], vsun=vsun) slbd=bovy_coords.XYZ_to_lbd(XYZ[0],XYZ[1],XYZ[2], degree=True) svlbd= bovy_coords.vxvyvz_to_vrpmllpmbb(vXYZ[0],vXYZ[1],vXYZ[2], slbd[:,0],slbd[:,1], slbd[:,2], degree=True) out= numpy.empty((6,n)) out[0]= slbd[:,0] out[1]= slbd[:,1] out[2]= slbd[:,2] out[3]= svlbd[:,0] out[4]= svlbd[:,1] out[5]= svlbd[:,2] if returndt: return (out,dt) else: return out def _h_ars(x,params): """ln p(Omega) for ARS""" mO, sO2= params return -0.5*(x-mO)**2./sO2+numpy.log(x) def _hp_ars(x,params): """d ln p(Omega) / d Omega for ARS""" mO, sO2= params return -(x-mO)/sO2+1./x def _determine_stream_track_single(aA,progenitorTrack,trackt, progenitor_angle,sigMeanSign, dsigomeanProgDirection,meanOmega, thetasTrack): #Setup output allAcfsTrack= numpy.empty((9)) alljacsTrack= numpy.empty((6,6)) allinvjacsTrack= numpy.empty((6,6)) ObsTrack= numpy.empty((6)) ObsTrackAA= numpy.empty((6)) detdOdJ= numpy.empty(6) #Calculate tacfs= aA.actionsFreqsAngles(progenitorTrack(trackt), maxn=3) allAcfsTrack[0]= tacfs[0][0] allAcfsTrack[1]= tacfs[1][0] allAcfsTrack[2]= tacfs[2][0] for jj in range(3,9): allAcfsTrack[jj]= tacfs[jj] tjac= calcaAJac(progenitorTrack(trackt)._orb.vxvv, aA, dxv=None,actionsFreqsAngles=True, lb=False, _initacfs=tacfs) alljacsTrack[:,:]= tjac[3:,:] tinvjac= numpy.linalg.inv(tjac[3:,:]) allinvjacsTrack[:,:]= tinvjac #Also store detdOdJ jindx= numpy.array([True,True,True,False,False,False,True,True,True], dtype='bool') dOdJ= numpy.dot(tjac[3:,:],numpy.linalg.inv(tjac[jindx,:]))[0:3,0:3] detdOdJ= numpy.linalg.det(dOdJ) theseAngles= numpy.mod(progenitor_angle\ +thetasTrack\ *sigMeanSign\ *dsigomeanProgDirection, 2.*numpy.pi) ObsTrackAA[3:]= theseAngles diffAngles= theseAngles-allAcfsTrack[6:] diffAngles[(diffAngles > numpy.pi)]= diffAngles[(diffAngles > numpy.pi)]-2.*numpy.pi diffAngles[(diffAngles < -numpy.pi)]= diffAngles[(diffAngles < -numpy.pi)]+2.*numpy.pi thisFreq= meanOmega(thetasTrack) ObsTrackAA[:3]= thisFreq diffFreqs= thisFreq-allAcfsTrack[3:6] ObsTrack[:]= numpy.dot(tinvjac, numpy.hstack((diffFreqs,diffAngles))) ObsTrack[0]+= \ progenitorTrack(trackt).R() ObsTrack[1]+= \ progenitorTrack(trackt).vR() ObsTrack[2]+= \ progenitorTrack(trackt).vT() ObsTrack[3]+= \ progenitorTrack(trackt).z() ObsTrack[4]+= \ progenitorTrack(trackt).vz() ObsTrack[5]+= \ progenitorTrack(trackt).phi() return [allAcfsTrack,alljacsTrack,allinvjacsTrack,ObsTrack,ObsTrackAA, detdOdJ] def _determine_stream_spread_single(sigomatrixEig, thetasTrack, sigOmega, sigAngle, allinvjacsTrack): """sigAngle input may either be a function that returns the dispersion in perpendicular angle as a function of parallel angle, or a value""" #Estimate the spread in all frequencies and angles sigObig2= sigOmega(thetasTrack)**2. tsigOdiag= copy.copy(sigomatrixEig[0]) tsigOdiag[numpy.argmax(tsigOdiag)]= sigObig2 tsigO= numpy.dot(sigomatrixEig[1], numpy.dot(numpy.diag(tsigOdiag), numpy.linalg.inv(sigomatrixEig[1]))) #angles if hasattr(sigAngle,'__call__'): sigangle2= sigAngle(thetasTrack)**2. else: sigangle2= sigAngle**2. tsigadiag= numpy.ones(3)*sigangle2 tsigadiag[numpy.argmax(tsigOdiag)]= 1. tsiga= numpy.dot(sigomatrixEig[1], numpy.dot(numpy.diag(tsigadiag), numpy.linalg.inv(sigomatrixEig[1]))) #correlations, assume half correlated for now (can be calculated) correlations= numpy.diag(0.5*numpy.ones(3))*numpy.sqrt(tsigOdiag*tsigadiag) correlations[numpy.argmax(tsigOdiag),numpy.argmax(tsigOdiag)]= 0. correlations= numpy.dot(sigomatrixEig[1], numpy.dot(correlations, numpy.linalg.inv(sigomatrixEig[1]))) #Now convert fullMatrix= numpy.empty((6,6)) fullMatrix[:3,:3]= tsigO fullMatrix[3:,3:]= tsiga fullMatrix[3:,:3]= correlations fullMatrix[:3,3:]= correlations.T return numpy.dot(allinvjacsTrack,numpy.dot(fullMatrix,allinvjacsTrack.T)) def calcaAJac(xv,aA,dxv=None,freqs=False,dOdJ=False,actionsFreqsAngles=False, lb=False,coordFunc=None, Vnorm=220.,Rnorm=8.,R0=8.,Zsun=0.025,vsun=[-11.1,8.*30.24,7.25], _initacfs=None): """ NAME: calcaAJac PURPOSE: calculate the Jacobian d(J,theta)/d(x,v) INPUT: xv - phase-space point: Either 1) [R,vR,vT,z,vz,phi] 2) [l,b,D,vlos,pmll,pmbb] (if lb=True, see below) 3) list/array of 6 numbers that can be transformed into (normalized) R,vR,vT,z,vz,phi using coordFunc aA - actionAngle instance dxv - infinitesimal to use (rescaled for lb, so think fractionally)) freqs= (False) if True, go to frequencies rather than actions dOdJ= (False), actually calculate d Frequency / d action actionsFreqsAngles= (False) if True, calculate d(action,freq.,angle)/d (xv) lb= (False) if True, start with (l,b,D,vlos,pmll,pmbb) in (deg,deg,kpc,km/s,mas/yr,mas/yr) Vnorm= (220) circular velocity to normalize with when lb=True Rnorm= (8) Galactocentric radius to normalize with when lb=True R0= (8) Galactocentric radius of the Sun (kpc) Zsun= (0.025) Sun's height above the plane (kpc) vsun= ([-11.1,241.92,7.25]) Sun's motion in cylindrical coordinates (vR positive away from center) coordFunc= (None) if set, this is a function that takes xv and returns R,vR,vT,z,vz,phi in normalized units (units where vc=1 at r=1 if the potential is normalized that way, for example) OUTPUT: Jacobian matrix HISTORY: 2013-11-25 - Written - Bovy (IAS) """ if lb: coordFunc= lambda x: lbCoordFunc(xv,Vnorm,Rnorm,R0,Zsun,vsun) if not coordFunc is None: R, vR, vT, z, vz, phi= coordFunc(xv) else: R, vR, vT, z, vz, phi= xv[0],xv[1],xv[2],xv[3],xv[4],xv[5] if dxv is None: dxv= 10.**-8.*numpy.ones(6) if lb: #Re-scale some of the differences, to be more natural dxv[0]*= 180./numpy.pi dxv[1]*= 180./numpy.pi dxv[2]*= Rnorm dxv[3]*= Vnorm dxv[4]*= Vnorm/4.74047/xv[2] dxv[5]*= Vnorm/4.74047/xv[2] if actionsFreqsAngles: jac= numpy.zeros((9,6)) else: jac= numpy.zeros((6,6)) if dOdJ: jac2= numpy.zeros((6,6)) if _initacfs is None: jr,lz,jz,Or,Ophi,Oz,ar,aphi,az\ = aA.actionsFreqsAngles(R,vR,vT,z,vz,phi,maxn=3) else: jr,lz,jz,Or,Ophi,Oz,ar,aphi,az\ = _initacfs for ii in range(6): temp= xv[ii]+dxv[ii] #Trick to make sure dxv is representable dxv[ii]= temp-xv[ii] xv[ii]+= dxv[ii] if not coordFunc is None: tR, tvR, tvT, tz, tvz, tphi= coordFunc(xv) else: tR, tvR, tvT, tz, tvz, tphi= xv[0],xv[1],xv[2],xv[3],xv[4],xv[5] tjr,tlz,tjz,tOr,tOphi,tOz,tar,taphi,taz\ = aA.actionsFreqsAngles(tR,tvR,tvT,tz,tvz,tphi,maxn=3) xv[ii]-= dxv[ii] angleIndx= 3 if actionsFreqsAngles: jac[0,ii]= (tjr-jr)/dxv[ii] jac[1,ii]= (tlz-lz)/dxv[ii] jac[2,ii]= (tjz-jz)/dxv[ii] jac[3,ii]= (tOr-Or)/dxv[ii] jac[4,ii]= (tOphi-Ophi)/dxv[ii] jac[5,ii]= (tOz-Oz)/dxv[ii] angleIndx= 6 elif freqs: jac[0,ii]= (tOr-Or)/dxv[ii] jac[1,ii]= (tOphi-Ophi)/dxv[ii] jac[2,ii]= (tOz-Oz)/dxv[ii] else: jac[0,ii]= (tjr-jr)/dxv[ii] jac[1,ii]= (tlz-lz)/dxv[ii] jac[2,ii]= (tjz-jz)/dxv[ii] if dOdJ: jac2[0,ii]= (tOr-Or)/dxv[ii] jac2[1,ii]= (tOphi-Ophi)/dxv[ii] jac2[2,ii]= (tOz-Oz)/dxv[ii] #For the angles, make sure we do not hit a turning point if tar-ar > numpy.pi: jac[angleIndx,ii]= (tar-ar-2.*numpy.pi)/dxv[ii] elif tar-ar < -numpy.pi: jac[angleIndx,ii]= (tar-ar+2.*numpy.pi)/dxv[ii] else: jac[angleIndx,ii]= (tar-ar)/dxv[ii] if taphi-aphi > numpy.pi: jac[angleIndx+1,ii]= (taphi-aphi-2.*numpy.pi)/dxv[ii] elif taphi-aphi < -numpy.pi: jac[angleIndx+1,ii]= (taphi-aphi+2.*numpy.pi)/dxv[ii] else: jac[angleIndx+1,ii]= (taphi-aphi)/dxv[ii] if taz-az > numpy.pi: jac[angleIndx+2,ii]= (taz-az-2.*numpy.pi)/dxv[ii] if taz-az < -numpy.pi: jac[angleIndx+2,ii]= (taz-az+2.*numpy.pi)/dxv[ii] else: jac[angleIndx+2,ii]= (taz-az)/dxv[ii] if dOdJ: jac2[3,:]= jac[3,:] jac2[4,:]= jac[4,:] jac2[5,:]= jac[5,:] jac= numpy.dot(jac2,numpy.linalg.inv(jac))[0:3,0:3] return jac def lbCoordFunc(xv,Vnorm,Rnorm,R0,Zsun,vsun): #Input is (l,b,D,vlos,pmll,pmbb) in (deg,deg,kpc,km/s,mas/yr,mas/yr) X,Y,Z= bovy_coords.lbd_to_XYZ(xv[0],xv[1],xv[2],degree=True) R,phi,Z= bovy_coords.XYZ_to_galcencyl(X,Y,Z, Xsun=R0,Ysun=0.,Zsun=Zsun) vx,vy,vz= bovy_coords.vrpmllpmbb_to_vxvyvz(xv[3],xv[4],xv[5], X,Y,Z,XYZ=True) vR,vT,vZ= bovy_coords.vxvyvz_to_galcencyl(vx,vy,vz,R,phi,Z,galcen=True, vsun=vsun) R/= Rnorm Z/= Rnorm vR/= Vnorm vT/= Vnorm vZ/= Vnorm return (R,vR,vT,Z,vZ,phi)
followthesheep/galpy
galpy/df_src/streamdf.py
Python
bsd-3-clause
117,381
package org.scalameta.data import scala.language.experimental.macros import scala.annotation.StaticAnnotation import scala.reflect.macros.whitebox.Context import scala.collection.mutable.ListBuffer import org.scalameta.internal.MacroHelpers // Virtually the same as the `case' modifier: // can be used on both classes and objects with very similar effect. // // The main different is customizability - we can stuff any extensions we want into @data. // Currently it's just two things: // 1) Support for lazy parameters (implemented via a @byNeed marker annotation), // as in e.g.: `@leaf class Nonrecursive(tpe: Type.Arg @byNeed) extends Typing`. // NOTE: @byNeed isn't defined anywhere - it's just a syntactic marker. // 2) Support for on-demand member generation via named parameters to @data, // as in e.g. `@data(toString = false) class ...`. // // Performance of pattern matching may be subpar until SI-9029 is fixed, // as well as some minor semantic details may differ. class data extends StaticAnnotation { def macroTransform(annottees: Any*): Any = macro DataMacros.data } class none extends StaticAnnotation { def macroTransform(annottees: Any*): Any = macro DataMacros.none } class DataMacros(val c: Context) extends MacroHelpers { import c.universe._ import Flag._ def data(annottees: Tree*): Tree = annottees.transformAnnottees(new ImplTransformer { override def transformClass(cdef: ClassDef, mdef: ModuleDef): List[ImplDef] = { val q"$mods class $name[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self => ..$stats }" = cdef val q"$mmods object $mname extends { ..$mearlydefns } with ..$mparents { $mself => ..$mstats }" = mdef val parents1 = ListBuffer[Tree]() ++ parents val stats1 = ListBuffer[Tree]() ++ stats val anns1 = ListBuffer[Tree]() ++ mods.annotations def mods1 = mods.mapAnnotations(_ => anns1.toList) val manns1 = ListBuffer[Tree]() ++ mmods.annotations def mmods1 = mmods.mapAnnotations(_ => manns1.toList) val mstats1 = ListBuffer[Tree]() ++ mstats implicit class XtensionDataModifiers(mods: Modifiers) { def mkByneed = Modifiers(mods.flags, mods.privateWithin, mods.annotations :+ q"new $AdtMetadataModule.byNeedField") } def needs(name: Name, companion: Boolean, duplicate: Boolean) = { val q"new $_(...$argss).macroTransform(..$_)" = c.macroApplication val banIndicator = argss.flatten.find { case AssignOrNamedArg(Ident(TermName(param)), Literal(Constant(false))) => param == name.toString case _ => false } val ban = banIndicator.map(_ => true).getOrElse(false) val presenceIndicator = { val where = if (companion) mstats else stats where.collectFirst { case mdef: MemberDef if mdef.name == name => mdef } } val present = presenceIndicator.map(_ => true).getOrElse(false) !ban && (duplicate || !present) } object VanillaParam { def unapply(tree: ValDef): Option[(Modifiers, TermName, Tree, Tree)] = tree match { case ByNeedParam(_, _, _, _) => None case VarargParam(_, _, _, _) => None case _ => Some((tree.mods, tree.name, tree.tpt, tree.rhs)) } } object VarargParam { def unapply(tree: ValDef): Option[(Modifiers, TermName, Tree, Tree)] = tree.tpt match { case Vararg(_) => Some((tree.mods, tree.name, tree.tpt, tree.rhs)) case _ => None } } object ByNeedParam { def unapply(tree: ValDef): Option[(Modifiers, TermName, Tree, Tree)] = tree.tpt match { case Annotated(Apply(Select(New(Ident(TypeName("byNeed"))), termNames.CONSTRUCTOR), List()), tpt) => if (Vararg.unapply(tree.tpt).nonEmpty) c.abort(cdef.pos, "vararg parameters cannot be by-need") else Some((tree.mods, tree.name, tpt, tree.rhs)) case _ => None } } def unByNeed(tree: ValDef): ValDef = tree match { case ByNeedParam(mods, name, tpt, default) => ValDef(mods, name, tpt, default) case _ => tree.duplicate } def byNameTpt(tpt: Tree): Tree = { val DefDef(_, _, _, List(List(ValDef(_, _, byNameTpt, _))), _, _) = q"def dummy(dummy: => $tpt) = ???" byNameTpt } object Vararg { def unapply(tpt: Tree): Option[Tree] = tpt match { case Annotated(_, arg) => unapply(arg) case AppliedTypeTree(Select(Select(Ident(root), scala), repeated), List(arg)) if root == termNames.ROOTPKG && scala == TermName("scala") && repeated == definitions.RepeatedParamClass.name.decodedName => Some(arg) case _ => None } } val isVararg = paramss.flatten.lastOption.flatMap(p => Vararg.unapply(p.tpt)).nonEmpty val itparams = tparams.map{ case q"$mods type $name[..$tparams] >: $low <: $high" => q"${mods.unVariant} type $name[..$tparams] >: $low <: $high" } val tparamrefs = tparams.map(tparam => Ident(tparam.name)) // step 1: validate the shape of the class if (mods.hasFlag(SEALED)) c.abort(cdef.pos, "sealed is redundant for @data classes") if (mods.hasFlag(FINAL)) c.abort(cdef.pos, "final is redundant for @data classes") if (mods.hasFlag(CASE)) c.abort(cdef.pos, "case is redundant for @data classes") if (mods.hasFlag(ABSTRACT)) c.abort(cdef.pos, "@data classes cannot be abstract") if (paramss.length == 0) c.abort(cdef.pos, "@data classes must define a non-empty parameter list") // step 2: create parameters, generate getters and validation checks val paramss1 = paramss.map(_.map{ case VanillaParam(mods, name, tpt, default) => stats1 += q"$DataTyperMacrosModule.nullCheck(this.$name)" stats1 += q"$DataTyperMacrosModule.emptyCheck(this.$name)" q"${mods.unPrivate} val $name: $tpt = $default" case VarargParam(mods, name, tpt, default) => stats1 += q"$DataTyperMacrosModule.nullCheck(this.$name)" stats1 += q"$DataTyperMacrosModule.emptyCheck(this.$name)" q"${mods.unPrivate} val $name: $tpt = $default" case ByNeedParam(mods, name, tpt, default) => val flagName = TermName(name + "Flag") val statusName = TermName("is" + name.toString.capitalize + "Loaded") val valueName = TermName(name + "Value") val storageName = TermName(name + "Storage") val getterName = name val paramName = TermName("_" + name) val paramTpt = tq"_root_.scala.Function0[$tpt]" stats1 += q"@$AdtMetadataModule.byNeedField private[this] var $flagName: _root_.scala.Boolean = false" stats1 += q"def $statusName: _root_.scala.Boolean = this.$flagName" stats1 += q"@$AdtMetadataModule.byNeedField private[this] var $storageName: $tpt = _" stats1 += q""" def $getterName = { if (!this.$flagName) { val $valueName = this.$paramName() $DataTyperMacrosModule.nullCheck($valueName) $DataTyperMacrosModule.emptyCheck($valueName) this.$paramName = null this.$storageName = $valueName this.$flagName = true } this.$storageName } """ q"${mods.mkPrivate.mkByneed.mkMutable} val $paramName: $paramTpt = $default" }) // step 3: implement Object if (needs(TermName("toString"), companion = false, duplicate = false)) { stats1 += q"override def toString: _root_.scala.Predef.String = _root_.scala.runtime.ScalaRunTime._toString(this)" } if (needs(TermName("hashCode"), companion = false, duplicate = false)) { stats1 += q"override def hashCode: _root_.scala.Int = _root_.scala.runtime.ScalaRunTime._hashCode(this)" } if (needs(TermName("equals"), companion = false, duplicate = false)) { stats1 += q"override def canEqual(other: _root_.scala.Any): _root_.scala.Boolean = other.isInstanceOf[$name[..$tparamrefs]]" stats1 += q""" override def equals(other: _root_.scala.Any): _root_.scala.Boolean = ( this.canEqual(other) && (other match { case other: Product if this.productArity == other.productArity => this.productIterator sameElements other.productIterator case _ => false }) ) """ } // step 4: implement Product parents1 += tq"_root_.scala.Product" if (needs(TermName("product"), companion = false, duplicate = false)) { val productParamss = paramss.map(_.map(_.duplicate)) stats1 += q"override def productPrefix: _root_.scala.Predef.String = ${name.toString}" stats1 += q"override def productArity: _root_.scala.Int = ${paramss.head.length}" val pelClauses = ListBuffer[Tree]() pelClauses ++= 0.to(productParamss.head.length - 1).map(i => cq"$i => this.${productParamss.head(i).name}") pelClauses += cq"_ => throw new _root_.scala.IndexOutOfBoundsException(n.toString)" stats1 += q"override def productElement(n: _root_.scala.Int): Any = n match { case ..$pelClauses }" stats1 += q"override def productIterator: _root_.scala.Iterator[_root_.scala.Any] = _root_.scala.runtime.ScalaRunTime.typedProductIterator(this)" } // step 5: generate copy if (needs(TermName("copy"), companion = false, duplicate = false) && !isVararg) { val copyParamss = paramss.map(_.map({ case VanillaParam(mods, name, tpt, default) => q"$mods val $name: $tpt = this.$name" case VarargParam(mods, name, tpt, default) => q"$mods val $name: $tpt = this.$name" // TODO: This doesn't compile, producing nonsensical errors // about incompatibility between the default value and the type of the parameter // e.g. "expected: => T, actual: T" // Therefore, I'm making the parameter of copy eager, even though I'd like it to be lazy. // case ByNeedParam(mods, name, tpt, default) => q"$mods val $name: ${byNameTpt(tpt)} = this.$name" case ByNeedParam(mods, name, tpt, default) => q"$mods val $name: $tpt = this.$name" })) val copyArgss = paramss.map(_.map({ case VanillaParam(mods, name, tpt, default) => q"$name" case VarargParam(mods, name, tpt, default) => q"$name: _*" case ByNeedParam(mods, name, tpt, default) => q"(() => $name)" })) stats1 += q"def copy[..$itparams](...$copyParamss): $name[..$tparamrefs] = new $name[..$tparamrefs](...$copyArgss)" } // step 6: generate Companion.apply // TODO: try change this to duplicate=true and see what happens if (needs(TermName("apply"), companion = true, duplicate = false)) { val applyParamss = paramss.map(_.map({ case VanillaParam(mods, name, tpt, default) => q"$mods val $name: $tpt = $default" case VarargParam(mods, name, tpt, default) => q"$mods val $name: $tpt = $default" case ByNeedParam(mods, name, tpt, default) => q"$mods val $name: ${byNameTpt(tpt)} = $default" })) val applyArgss = paramss.map(_.map({ case VanillaParam(mods, name, tpt, default) => q"$name" case VarargParam(mods, name, tpt, default) => q"$name: _*" case ByNeedParam(mods, name, tpt, default) => q"(() => $name)" })) mstats1 += q"def apply[..$itparams](...$applyParamss): $name[..$tparamrefs] = new $name[..$tparamrefs](...$applyArgss)" } // step 7: generate Companion.unapply // TODO: go for name-based pattern matching once blocking bugs (e.g. SI-9029) are fixed val unapplyName = if (isVararg) TermName("unapplySeq") else TermName("unapply") if (needs(TermName("unapply"), companion = true, duplicate = false) && needs(TermName("unapplySeq"), companion = true, duplicate = false)) { val unapplyParamss = paramss.map(_.map(unByNeed)) val unapplyParams = unapplyParamss.head if (unapplyParams.length != 0) { val successTargs = unapplyParams.map({ case VanillaParam(mods, name, tpt, default) => tpt case VarargParam(mods, name, Vararg(tpt), default) => tq"_root_.scala.Seq[$tpt]" case ByNeedParam(mods, name, tpt, default) => tpt }) val successTpe = tq"(..$successTargs)" val successArgs = q"(..${unapplyParams.map(p => q"x.${p.name}")})" mstats1 += q""" def $unapplyName[..$itparams](x: $name[..$tparamrefs]): Option[$successTpe] = { if (x == null) _root_.scala.None else _root_.scala.Some($successArgs) } """ } else { mstats1 += q"def $unapplyName(x: $name): Boolean = true" } } val cdef1 = q"${mods1.mkFinal} class $name[..$tparams] $ctorMods(...$paramss1) extends { ..$earlydefns } with ..$parents1 { $self => ..$stats1 }" val mdef1 = q"$mmods1 object $mname extends { ..$mearlydefns } with ..$mparents { $mself => ..$mstats1 }" List(cdef1, mdef1) } override def transformModule(mdef: ModuleDef): ModuleDef = { val q"$mmods object $mname extends { ..$mearlydefns } with ..$mparents { $mself => ..$mstats }" = mdef // step 1: validate the shape of the module if (mmods.hasFlag(FINAL)) c.abort(mdef.pos, "final is redundant for @data objects") if (mmods.hasFlag(CASE)) c.abort(mdef.pos, "case is redundant for @data objects") // TODO: later on we could migrate data modules to hand-rolled codegen, much like data classes. // However, for now it's quite fine to implement them as case objects. q"${mmods.mkCase} object $mname extends { ..$mearlydefns } with ..$mparents { $mself => ..$mstats }" } }) def none(annottees: Tree*): Tree = annottees.transformAnnottees(new ImplTransformer { override def transformModule(mdef: ModuleDef): ModuleDef = { val q"new $_(...$argss).macroTransform(..$_)" = c.macroApplication val q"$mmods object $mname extends { ..$mearlydefns } with ..$mparents { $mself => ..$mstats }" = mdef val manns1 = ListBuffer[Tree]() ++ mmods.annotations def mmods1 = mmods.mapAnnotations(_ => manns1.toList) val mstats1 = ListBuffer[Tree]() ++ mstats manns1 += q"new $DataAnnotation" mstats1 += q"override def isEmpty: $BooleanClass = true" q"$mmods1 object $mname extends { ..$mearlydefns } with ..$mparents { $mself => ..$mstats1 }" } }) }
Dveim/scalameta
scalameta/common/src/main/scala/org/scalameta/data/data.scala
Scala
bsd-3-clause
14,726
/* * * Copyright 2015, Google Inc. * 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 name of Google Inc. 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. * */ #include <grpc/support/port_platform.h> #include "src/core/lib/security/credentials/credentials.h" #include <openssl/rsa.h> #include <stdlib.h> #include <string.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/string_util.h> #include <grpc/support/time.h> #include "src/core/lib/http/httpcli.h" #include "src/core/lib/security/credentials/composite/composite_credentials.h" #include "src/core/lib/security/credentials/google_default/google_default_credentials.h" #include "src/core/lib/security/credentials/jwt/jwt_credentials.h" #include "src/core/lib/security/credentials/oauth2/oauth2_credentials.h" #include "src/core/lib/support/env.h" #include "src/core/lib/support/string.h" #include "src/core/lib/support/tmpfile.h" #include "test/core/util/test_config.h" /* -- Mock channel credentials. -- */ static grpc_channel_credentials *grpc_mock_channel_credentials_create( const grpc_channel_credentials_vtable *vtable) { grpc_channel_credentials *c = gpr_malloc(sizeof(*c)); memset(c, 0, sizeof(*c)); c->type = "mock"; c->vtable = vtable; gpr_ref_init(&c->refcount, 1); return c; } /* -- Constants. -- */ static const char test_google_iam_authorization_token[] = "blahblahblhahb"; static const char test_google_iam_authority_selector[] = "respectmyauthoritah"; static const char test_oauth2_bearer_token[] = "Bearer blaaslkdjfaslkdfasdsfasf"; /* This JSON key was generated with the GCE console and revoked immediately. The identifiers have been changed as well. Maximum size for a string literal is 509 chars in C89, yay! */ static const char test_json_key_str_part1[] = "{ \"private_key\": \"-----BEGIN PRIVATE KEY-----" "\\nMIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAOEvJsnoHnyHkXcp\\n7mJE" "qg" "WGjiw71NfXByguekSKho65FxaGbsnSM9SMQAqVk7Q2rG+I0OpsT0LrWQtZ\\nyjSeg/" "rWBQvS4hle4LfijkP3J5BG+" "IXDMP8RfziNRQsenAXDNPkY4kJCvKux2xdD\\nOnVF6N7dL3nTYZg+" "uQrNsMTz9UxVAgMBAAECgYEAzbLewe1xe9vy+2GoSsfib+28\\nDZgSE6Bu/" "zuFoPrRc6qL9p2SsnV7txrunTyJkkOnPLND9ABAXybRTlcVKP/sGgza\\n/" "8HpCqFYM9V8f34SBWfD4fRFT+n/" "73cfRUtGXdXpseva2lh8RilIQfPhNZAncenU\\ngqXjDvpkypEusgXAykECQQD+"; static const char test_json_key_str_part2[] = "53XxNVnxBHsYb+AYEfklR96yVi8HywjVHP34+OQZ\\nCslxoHQM8s+" "dBnjfScLu22JqkPv04xyxmt0QAKm9+vTdAkEA4ib7YvEAn2jXzcCI\\nEkoy2L/" "XydR1GCHoacdfdAwiL2npOdnbvi4ZmdYRPY1LSTO058tQHKVXV7NLeCa3\\nAARh2QJBAMKeDA" "G" "W303SQv2cZTdbeaLKJbB5drz3eo3j7dDKjrTD9JupixFbzcGw\\n8FZi5c8idxiwC36kbAL6Hz" "A" "ZoX+ofI0CQE6KCzPJTtYNqyShgKAZdJ8hwOcvCZtf\\n6z8RJm0+" "6YBd38lfh5j8mZd7aHFf6I17j5AQY7oPEc47TjJj/" "5nZ68ECQQDvYuI3\\nLyK5fS8g0SYbmPOL9TlcHDOqwG0mrX9qpg5DC2fniXNSrrZ64GTDKdzZ" "Y" "Ap6LI9W\\nIqv4vr6y38N79TTC\\n-----END PRIVATE KEY-----\\n\", "; static const char test_json_key_str_part3[] = "\"private_key_id\": \"e6b5137873db8d2ef81e06a47289e6434ec8a165\", " "\"client_email\": " "\"777-abaslkan11hlb6nmim3bpspl31ud@developer.gserviceaccount." "com\", \"client_id\": " "\"777-abaslkan11hlb6nmim3bpspl31ud.apps.googleusercontent." "com\", \"type\": \"service_account\" }"; /* Test refresh token. */ static const char test_refresh_token_str[] = "{ \"client_id\": \"32555999999.apps.googleusercontent.com\"," " \"client_secret\": \"EmssLNjJy1332hD4KFsecret\"," " \"refresh_token\": \"1/Blahblasj424jladJDSGNf-u4Sua3HDA2ngjd42\"," " \"type\": \"authorized_user\"}"; static const char valid_oauth2_json_response[] = "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\"," " \"expires_in\":3599, " " \"token_type\":\"Bearer\"}"; static const char test_user_data[] = "user data"; static const char test_scope[] = "perm1 perm2"; static const char test_signed_jwt[] = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImY0OTRkN2M1YWU2MGRmOTcyNmM4YW" "U0MDcyZTViYTdmZDkwODg2YzcifQ"; static const char test_service_url[] = "https://foo.com/foo.v1"; static const char other_test_service_url[] = "https://bar.com/bar.v1"; static const char test_method[] = "ThisIsNotAMethod"; /* -- Utils. -- */ static char *test_json_key_str(void) { size_t result_len = strlen(test_json_key_str_part1) + strlen(test_json_key_str_part2) + strlen(test_json_key_str_part3); char *result = gpr_malloc(result_len + 1); char *current = result; strcpy(result, test_json_key_str_part1); current += strlen(test_json_key_str_part1); strcpy(current, test_json_key_str_part2); current += strlen(test_json_key_str_part2); strcpy(current, test_json_key_str_part3); return result; } typedef struct { const char *key; const char *value; } expected_md; static grpc_httpcli_response http_response(int status, const char *body) { grpc_httpcli_response response; memset(&response, 0, sizeof(grpc_httpcli_response)); response.status = status; response.body = (char *)body; response.body_length = strlen(body); return response; } /* -- Tests. -- */ static void test_empty_md_store(void) { grpc_credentials_md_store *store = grpc_credentials_md_store_create(0); GPR_ASSERT(store->num_entries == 0); GPR_ASSERT(store->allocated == 0); grpc_credentials_md_store_unref(store); } static void test_ref_unref_empty_md_store(void) { grpc_credentials_md_store *store = grpc_credentials_md_store_create(0); grpc_credentials_md_store_ref(store); grpc_credentials_md_store_ref(store); GPR_ASSERT(store->num_entries == 0); GPR_ASSERT(store->allocated == 0); grpc_credentials_md_store_unref(store); grpc_credentials_md_store_unref(store); grpc_credentials_md_store_unref(store); } static void test_add_to_empty_md_store(void) { grpc_credentials_md_store *store = grpc_credentials_md_store_create(0); const char *key_str = "hello"; const char *value_str = "there blah blah blah blah blah blah blah"; gpr_slice key = gpr_slice_from_copied_string(key_str); gpr_slice value = gpr_slice_from_copied_string(value_str); grpc_credentials_md_store_add(store, key, value); GPR_ASSERT(store->num_entries == 1); GPR_ASSERT(gpr_slice_cmp(key, store->entries[0].key) == 0); GPR_ASSERT(gpr_slice_cmp(value, store->entries[0].value) == 0); gpr_slice_unref(key); gpr_slice_unref(value); grpc_credentials_md_store_unref(store); } static void test_add_cstrings_to_empty_md_store(void) { grpc_credentials_md_store *store = grpc_credentials_md_store_create(0); const char *key_str = "hello"; const char *value_str = "there blah blah blah blah blah blah blah"; grpc_credentials_md_store_add_cstrings(store, key_str, value_str); GPR_ASSERT(store->num_entries == 1); GPR_ASSERT(gpr_slice_str_cmp(store->entries[0].key, key_str) == 0); GPR_ASSERT(gpr_slice_str_cmp(store->entries[0].value, value_str) == 0); grpc_credentials_md_store_unref(store); } static void test_empty_preallocated_md_store(void) { grpc_credentials_md_store *store = grpc_credentials_md_store_create(4); GPR_ASSERT(store->num_entries == 0); GPR_ASSERT(store->allocated == 4); GPR_ASSERT(store->entries != NULL); grpc_credentials_md_store_unref(store); } static void test_add_abunch_to_md_store(void) { grpc_credentials_md_store *store = grpc_credentials_md_store_create(4); size_t num_entries = 1000; const char *key_str = "hello"; const char *value_str = "there blah blah blah blah blah blah blah"; size_t i; for (i = 0; i < num_entries; i++) { grpc_credentials_md_store_add_cstrings(store, key_str, value_str); } for (i = 0; i < num_entries; i++) { GPR_ASSERT(gpr_slice_str_cmp(store->entries[i].key, key_str) == 0); GPR_ASSERT(gpr_slice_str_cmp(store->entries[i].value, value_str) == 0); } grpc_credentials_md_store_unref(store); } static void test_oauth2_token_fetcher_creds_parsing_ok(void) { grpc_credentials_md_store *token_md = NULL; gpr_timespec token_lifetime; grpc_httpcli_response response = http_response(200, valid_oauth2_json_response); GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response( &response, &token_md, &token_lifetime) == GRPC_CREDENTIALS_OK); GPR_ASSERT(token_lifetime.tv_sec == 3599); GPR_ASSERT(token_lifetime.tv_nsec == 0); GPR_ASSERT(token_md->num_entries == 1); GPR_ASSERT(gpr_slice_str_cmp(token_md->entries[0].key, "authorization") == 0); GPR_ASSERT(gpr_slice_str_cmp(token_md->entries[0].value, "Bearer ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_") == 0); grpc_credentials_md_store_unref(token_md); } static void test_oauth2_token_fetcher_creds_parsing_bad_http_status(void) { grpc_credentials_md_store *token_md = NULL; gpr_timespec token_lifetime; grpc_httpcli_response response = http_response(401, valid_oauth2_json_response); GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response( &response, &token_md, &token_lifetime) == GRPC_CREDENTIALS_ERROR); } static void test_oauth2_token_fetcher_creds_parsing_empty_http_body(void) { grpc_credentials_md_store *token_md = NULL; gpr_timespec token_lifetime; grpc_httpcli_response response = http_response(200, ""); GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response( &response, &token_md, &token_lifetime) == GRPC_CREDENTIALS_ERROR); } static void test_oauth2_token_fetcher_creds_parsing_invalid_json(void) { grpc_credentials_md_store *token_md = NULL; gpr_timespec token_lifetime; grpc_httpcli_response response = http_response(200, "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\"," " \"expires_in\":3599, " " \"token_type\":\"Bearer\""); GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response( &response, &token_md, &token_lifetime) == GRPC_CREDENTIALS_ERROR); } static void test_oauth2_token_fetcher_creds_parsing_missing_token(void) { grpc_credentials_md_store *token_md = NULL; gpr_timespec token_lifetime; grpc_httpcli_response response = http_response(200, "{" " \"expires_in\":3599, " " \"token_type\":\"Bearer\"}"); GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response( &response, &token_md, &token_lifetime) == GRPC_CREDENTIALS_ERROR); } static void test_oauth2_token_fetcher_creds_parsing_missing_token_type(void) { grpc_credentials_md_store *token_md = NULL; gpr_timespec token_lifetime; grpc_httpcli_response response = http_response(200, "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\"," " \"expires_in\":3599, " "}"); GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response( &response, &token_md, &token_lifetime) == GRPC_CREDENTIALS_ERROR); } static void test_oauth2_token_fetcher_creds_parsing_missing_token_lifetime( void) { grpc_credentials_md_store *token_md = NULL; gpr_timespec token_lifetime; grpc_httpcli_response response = http_response(200, "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\"," " \"token_type\":\"Bearer\"}"); GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response( &response, &token_md, &token_lifetime) == GRPC_CREDENTIALS_ERROR); } static void check_metadata(expected_md *expected, grpc_credentials_md *md_elems, size_t num_md) { size_t i; for (i = 0; i < num_md; i++) { size_t j; for (j = 0; j < num_md; j++) { if (0 == gpr_slice_str_cmp(md_elems[j].key, expected[i].key)) { GPR_ASSERT(gpr_slice_str_cmp(md_elems[j].value, expected[i].value) == 0); break; } } if (j == num_md) { gpr_log(GPR_ERROR, "key %s not found", expected[i].key); GPR_ASSERT(0); } } } static void check_google_iam_metadata(grpc_exec_ctx *exec_ctx, void *user_data, grpc_credentials_md *md_elems, size_t num_md, grpc_credentials_status status) { grpc_call_credentials *c = (grpc_call_credentials *)user_data; expected_md emd[] = {{GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY, test_google_iam_authorization_token}, {GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY, test_google_iam_authority_selector}}; GPR_ASSERT(status == GRPC_CREDENTIALS_OK); GPR_ASSERT(num_md == 2); check_metadata(emd, md_elems, num_md); grpc_call_credentials_unref(c); } static void test_google_iam_creds(void) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_call_credentials *creds = grpc_google_iam_credentials_create( test_google_iam_authorization_token, test_google_iam_authority_selector, NULL); grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL, NULL}; grpc_call_credentials_get_request_metadata( &exec_ctx, creds, NULL, auth_md_ctx, check_google_iam_metadata, creds); grpc_exec_ctx_finish(&exec_ctx); } static void check_access_token_metadata(grpc_exec_ctx *exec_ctx, void *user_data, grpc_credentials_md *md_elems, size_t num_md, grpc_credentials_status status) { grpc_call_credentials *c = (grpc_call_credentials *)user_data; expected_md emd[] = {{GRPC_AUTHORIZATION_METADATA_KEY, "Bearer blah"}}; GPR_ASSERT(status == GRPC_CREDENTIALS_OK); GPR_ASSERT(num_md == 1); check_metadata(emd, md_elems, num_md); grpc_call_credentials_unref(c); } static void test_access_token_creds(void) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_call_credentials *creds = grpc_access_token_credentials_create("blah", NULL); grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL, NULL}; GPR_ASSERT(strcmp(creds->type, GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) == 0); grpc_call_credentials_get_request_metadata( &exec_ctx, creds, NULL, auth_md_ctx, check_access_token_metadata, creds); grpc_exec_ctx_finish(&exec_ctx); } static grpc_security_status check_channel_oauth2_create_security_connector( grpc_channel_credentials *c, grpc_call_credentials *call_creds, const char *target, const grpc_channel_args *args, grpc_channel_security_connector **sc, grpc_channel_args **new_args) { GPR_ASSERT(strcmp(c->type, "mock") == 0); GPR_ASSERT(call_creds != NULL); GPR_ASSERT(strcmp(call_creds->type, GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) == 0); return GRPC_SECURITY_OK; } static void test_channel_oauth2_composite_creds(void) { grpc_channel_args *new_args; grpc_channel_credentials_vtable vtable = { NULL, check_channel_oauth2_create_security_connector}; grpc_channel_credentials *channel_creds = grpc_mock_channel_credentials_create(&vtable); grpc_call_credentials *oauth2_creds = grpc_access_token_credentials_create("blah", NULL); grpc_channel_credentials *channel_oauth2_creds = grpc_composite_channel_credentials_create(channel_creds, oauth2_creds, NULL); grpc_channel_credentials_release(channel_creds); grpc_call_credentials_release(oauth2_creds); GPR_ASSERT(grpc_channel_credentials_create_security_connector( channel_oauth2_creds, NULL, NULL, NULL, &new_args) == GRPC_SECURITY_OK); grpc_channel_credentials_release(channel_oauth2_creds); } static void check_oauth2_google_iam_composite_metadata( grpc_exec_ctx *exec_ctx, void *user_data, grpc_credentials_md *md_elems, size_t num_md, grpc_credentials_status status) { grpc_call_credentials *c = (grpc_call_credentials *)user_data; expected_md emd[] = { {GRPC_AUTHORIZATION_METADATA_KEY, test_oauth2_bearer_token}, {GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY, test_google_iam_authorization_token}, {GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY, test_google_iam_authority_selector}}; GPR_ASSERT(status == GRPC_CREDENTIALS_OK); GPR_ASSERT(num_md == 3); check_metadata(emd, md_elems, num_md); grpc_call_credentials_unref(c); } static void test_oauth2_google_iam_composite_creds(void) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; const grpc_call_credentials_array *creds_array; grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL, NULL}; grpc_call_credentials *oauth2_creds = grpc_md_only_test_credentials_create( "authorization", test_oauth2_bearer_token, 0); grpc_call_credentials *google_iam_creds = grpc_google_iam_credentials_create( test_google_iam_authorization_token, test_google_iam_authority_selector, NULL); grpc_call_credentials *composite_creds = grpc_composite_call_credentials_create(oauth2_creds, google_iam_creds, NULL); grpc_call_credentials_unref(oauth2_creds); grpc_call_credentials_unref(google_iam_creds); GPR_ASSERT( strcmp(composite_creds->type, GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE) == 0); creds_array = grpc_composite_call_credentials_get_credentials(composite_creds); GPR_ASSERT(creds_array->num_creds == 2); GPR_ASSERT(strcmp(creds_array->creds_array[0]->type, GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) == 0); GPR_ASSERT(strcmp(creds_array->creds_array[1]->type, GRPC_CALL_CREDENTIALS_TYPE_IAM) == 0); grpc_call_credentials_get_request_metadata( &exec_ctx, composite_creds, NULL, auth_md_ctx, check_oauth2_google_iam_composite_metadata, composite_creds); grpc_exec_ctx_finish(&exec_ctx); } static grpc_security_status check_channel_oauth2_google_iam_create_security_connector( grpc_channel_credentials *c, grpc_call_credentials *call_creds, const char *target, const grpc_channel_args *args, grpc_channel_security_connector **sc, grpc_channel_args **new_args) { const grpc_call_credentials_array *creds_array; GPR_ASSERT(strcmp(c->type, "mock") == 0); GPR_ASSERT(call_creds != NULL); GPR_ASSERT(strcmp(call_creds->type, GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE) == 0); creds_array = grpc_composite_call_credentials_get_credentials(call_creds); GPR_ASSERT(strcmp(creds_array->creds_array[0]->type, GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) == 0); GPR_ASSERT(strcmp(creds_array->creds_array[1]->type, GRPC_CALL_CREDENTIALS_TYPE_IAM) == 0); return GRPC_SECURITY_OK; } static void test_channel_oauth2_google_iam_composite_creds(void) { grpc_channel_args *new_args; grpc_channel_credentials_vtable vtable = { NULL, check_channel_oauth2_google_iam_create_security_connector}; grpc_channel_credentials *channel_creds = grpc_mock_channel_credentials_create(&vtable); grpc_call_credentials *oauth2_creds = grpc_access_token_credentials_create("blah", NULL); grpc_channel_credentials *channel_oauth2_creds = grpc_composite_channel_credentials_create(channel_creds, oauth2_creds, NULL); grpc_call_credentials *google_iam_creds = grpc_google_iam_credentials_create( test_google_iam_authorization_token, test_google_iam_authority_selector, NULL); grpc_channel_credentials *channel_oauth2_iam_creds = grpc_composite_channel_credentials_create(channel_oauth2_creds, google_iam_creds, NULL); grpc_channel_credentials_release(channel_creds); grpc_call_credentials_release(oauth2_creds); grpc_channel_credentials_release(channel_oauth2_creds); grpc_call_credentials_release(google_iam_creds); GPR_ASSERT(grpc_channel_credentials_create_security_connector( channel_oauth2_iam_creds, NULL, NULL, NULL, &new_args) == GRPC_SECURITY_OK); grpc_channel_credentials_release(channel_oauth2_iam_creds); } static void on_oauth2_creds_get_metadata_success( grpc_exec_ctx *exec_ctx, void *user_data, grpc_credentials_md *md_elems, size_t num_md, grpc_credentials_status status) { GPR_ASSERT(status == GRPC_CREDENTIALS_OK); GPR_ASSERT(num_md == 1); GPR_ASSERT(gpr_slice_str_cmp(md_elems[0].key, "authorization") == 0); GPR_ASSERT(gpr_slice_str_cmp(md_elems[0].value, "Bearer ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_") == 0); GPR_ASSERT(user_data != NULL); GPR_ASSERT(strcmp((const char *)user_data, test_user_data) == 0); } static void on_oauth2_creds_get_metadata_failure( grpc_exec_ctx *exec_ctx, void *user_data, grpc_credentials_md *md_elems, size_t num_md, grpc_credentials_status status) { GPR_ASSERT(status == GRPC_CREDENTIALS_ERROR); GPR_ASSERT(num_md == 0); GPR_ASSERT(user_data != NULL); GPR_ASSERT(strcmp((const char *)user_data, test_user_data) == 0); } static void validate_compute_engine_http_request( const grpc_httpcli_request *request) { GPR_ASSERT(request->handshaker != &grpc_httpcli_ssl); GPR_ASSERT(strcmp(request->host, "metadata") == 0); GPR_ASSERT( strcmp(request->http.path, "/computeMetadata/v1/instance/service-accounts/default/token") == 0); GPR_ASSERT(request->http.hdr_count == 1); GPR_ASSERT(strcmp(request->http.hdrs[0].key, "Metadata-Flavor") == 0); GPR_ASSERT(strcmp(request->http.hdrs[0].value, "Google") == 0); } static int compute_engine_httpcli_get_success_override( grpc_exec_ctx *exec_ctx, const grpc_httpcli_request *request, gpr_timespec deadline, grpc_httpcli_response_cb on_response, void *user_data) { grpc_httpcli_response response = http_response(200, valid_oauth2_json_response); validate_compute_engine_http_request(request); on_response(exec_ctx, user_data, &response); return 1; } static int compute_engine_httpcli_get_failure_override( grpc_exec_ctx *exec_ctx, const grpc_httpcli_request *request, gpr_timespec deadline, grpc_httpcli_response_cb on_response, void *user_data) { grpc_httpcli_response response = http_response(403, "Not Authorized."); validate_compute_engine_http_request(request); on_response(exec_ctx, user_data, &response); return 1; } static int httpcli_post_should_not_be_called( grpc_exec_ctx *exec_ctx, const grpc_httpcli_request *request, const char *body_bytes, size_t body_size, gpr_timespec deadline, grpc_httpcli_response_cb on_response, void *user_data) { GPR_ASSERT("HTTP POST should not be called" == NULL); return 1; } static int httpcli_get_should_not_be_called( grpc_exec_ctx *exec_ctx, const grpc_httpcli_request *request, gpr_timespec deadline, grpc_httpcli_response_cb on_response, void *user_data) { GPR_ASSERT("HTTP GET should not be called" == NULL); return 1; } static void test_compute_engine_creds_success(void) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_call_credentials *compute_engine_creds = grpc_google_compute_engine_credentials_create(NULL); grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL, NULL}; /* First request: http get should be called. */ grpc_httpcli_set_override(compute_engine_httpcli_get_success_override, httpcli_post_should_not_be_called); grpc_call_credentials_get_request_metadata( &exec_ctx, compute_engine_creds, NULL, auth_md_ctx, on_oauth2_creds_get_metadata_success, (void *)test_user_data); grpc_exec_ctx_flush(&exec_ctx); /* Second request: the cached token should be served directly. */ grpc_httpcli_set_override(httpcli_get_should_not_be_called, httpcli_post_should_not_be_called); grpc_call_credentials_get_request_metadata( &exec_ctx, compute_engine_creds, NULL, auth_md_ctx, on_oauth2_creds_get_metadata_success, (void *)test_user_data); grpc_exec_ctx_finish(&exec_ctx); grpc_call_credentials_unref(compute_engine_creds); grpc_httpcli_set_override(NULL, NULL); } static void test_compute_engine_creds_failure(void) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL, NULL}; grpc_call_credentials *compute_engine_creds = grpc_google_compute_engine_credentials_create(NULL); grpc_httpcli_set_override(compute_engine_httpcli_get_failure_override, httpcli_post_should_not_be_called); grpc_call_credentials_get_request_metadata( &exec_ctx, compute_engine_creds, NULL, auth_md_ctx, on_oauth2_creds_get_metadata_failure, (void *)test_user_data); grpc_call_credentials_unref(compute_engine_creds); grpc_httpcli_set_override(NULL, NULL); grpc_exec_ctx_finish(&exec_ctx); } static void validate_refresh_token_http_request( const grpc_httpcli_request *request, const char *body, size_t body_size) { /* The content of the assertion is tested extensively in json_token_test. */ char *expected_body = NULL; GPR_ASSERT(body != NULL); GPR_ASSERT(body_size != 0); gpr_asprintf(&expected_body, GRPC_REFRESH_TOKEN_POST_BODY_FORMAT_STRING, "32555999999.apps.googleusercontent.com", "EmssLNjJy1332hD4KFsecret", "1/Blahblasj424jladJDSGNf-u4Sua3HDA2ngjd42"); GPR_ASSERT(strlen(expected_body) == body_size); GPR_ASSERT(memcmp(expected_body, body, body_size) == 0); gpr_free(expected_body); GPR_ASSERT(request->handshaker == &grpc_httpcli_ssl); GPR_ASSERT(strcmp(request->host, GRPC_GOOGLE_OAUTH2_SERVICE_HOST) == 0); GPR_ASSERT( strcmp(request->http.path, GRPC_GOOGLE_OAUTH2_SERVICE_TOKEN_PATH) == 0); GPR_ASSERT(request->http.hdr_count == 1); GPR_ASSERT(strcmp(request->http.hdrs[0].key, "Content-Type") == 0); GPR_ASSERT(strcmp(request->http.hdrs[0].value, "application/x-www-form-urlencoded") == 0); } static int refresh_token_httpcli_post_success( grpc_exec_ctx *exec_ctx, const grpc_httpcli_request *request, const char *body, size_t body_size, gpr_timespec deadline, grpc_httpcli_response_cb on_response, void *user_data) { grpc_httpcli_response response = http_response(200, valid_oauth2_json_response); validate_refresh_token_http_request(request, body, body_size); on_response(exec_ctx, user_data, &response); return 1; } static int refresh_token_httpcli_post_failure( grpc_exec_ctx *exec_ctx, const grpc_httpcli_request *request, const char *body, size_t body_size, gpr_timespec deadline, grpc_httpcli_response_cb on_response, void *user_data) { grpc_httpcli_response response = http_response(403, "Not Authorized."); validate_refresh_token_http_request(request, body, body_size); on_response(exec_ctx, user_data, &response); return 1; } static void test_refresh_token_creds_success(void) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL, NULL}; grpc_call_credentials *refresh_token_creds = grpc_google_refresh_token_credentials_create(test_refresh_token_str, NULL); /* First request: http get should be called. */ grpc_httpcli_set_override(httpcli_get_should_not_be_called, refresh_token_httpcli_post_success); grpc_call_credentials_get_request_metadata( &exec_ctx, refresh_token_creds, NULL, auth_md_ctx, on_oauth2_creds_get_metadata_success, (void *)test_user_data); grpc_exec_ctx_flush(&exec_ctx); /* Second request: the cached token should be served directly. */ grpc_httpcli_set_override(httpcli_get_should_not_be_called, httpcli_post_should_not_be_called); grpc_call_credentials_get_request_metadata( &exec_ctx, refresh_token_creds, NULL, auth_md_ctx, on_oauth2_creds_get_metadata_success, (void *)test_user_data); grpc_exec_ctx_flush(&exec_ctx); grpc_call_credentials_unref(refresh_token_creds); grpc_httpcli_set_override(NULL, NULL); grpc_exec_ctx_finish(&exec_ctx); } static void test_refresh_token_creds_failure(void) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL, NULL}; grpc_call_credentials *refresh_token_creds = grpc_google_refresh_token_credentials_create(test_refresh_token_str, NULL); grpc_httpcli_set_override(httpcli_get_should_not_be_called, refresh_token_httpcli_post_failure); grpc_call_credentials_get_request_metadata( &exec_ctx, refresh_token_creds, NULL, auth_md_ctx, on_oauth2_creds_get_metadata_failure, (void *)test_user_data); grpc_call_credentials_unref(refresh_token_creds); grpc_httpcli_set_override(NULL, NULL); grpc_exec_ctx_finish(&exec_ctx); } static void validate_jwt_encode_and_sign_params( const grpc_auth_json_key *json_key, const char *scope, gpr_timespec token_lifetime) { GPR_ASSERT(grpc_auth_json_key_is_valid(json_key)); GPR_ASSERT(json_key->private_key != NULL); GPR_ASSERT(RSA_check_key(json_key->private_key)); GPR_ASSERT(json_key->type != NULL && strcmp(json_key->type, "service_account") == 0); GPR_ASSERT(json_key->private_key_id != NULL && strcmp(json_key->private_key_id, "e6b5137873db8d2ef81e06a47289e6434ec8a165") == 0); GPR_ASSERT(json_key->client_id != NULL && strcmp(json_key->client_id, "777-abaslkan11hlb6nmim3bpspl31ud.apps." "googleusercontent.com") == 0); GPR_ASSERT(json_key->client_email != NULL && strcmp(json_key->client_email, "777-abaslkan11hlb6nmim3bpspl31ud@developer." "gserviceaccount.com") == 0); if (scope != NULL) GPR_ASSERT(strcmp(scope, test_scope) == 0); GPR_ASSERT(!gpr_time_cmp(token_lifetime, grpc_max_auth_token_lifetime())); } static char *encode_and_sign_jwt_success(const grpc_auth_json_key *json_key, const char *audience, gpr_timespec token_lifetime, const char *scope) { validate_jwt_encode_and_sign_params(json_key, scope, token_lifetime); return gpr_strdup(test_signed_jwt); } static char *encode_and_sign_jwt_failure(const grpc_auth_json_key *json_key, const char *audience, gpr_timespec token_lifetime, const char *scope) { validate_jwt_encode_and_sign_params(json_key, scope, token_lifetime); return NULL; } static char *encode_and_sign_jwt_should_not_be_called( const grpc_auth_json_key *json_key, const char *audience, gpr_timespec token_lifetime, const char *scope) { GPR_ASSERT("grpc_jwt_encode_and_sign should not be called" == NULL); return NULL; } static void on_jwt_creds_get_metadata_success(grpc_exec_ctx *exec_ctx, void *user_data, grpc_credentials_md *md_elems, size_t num_md, grpc_credentials_status status) { char *expected_md_value; gpr_asprintf(&expected_md_value, "Bearer %s", test_signed_jwt); GPR_ASSERT(status == GRPC_CREDENTIALS_OK); GPR_ASSERT(num_md == 1); GPR_ASSERT(gpr_slice_str_cmp(md_elems[0].key, "authorization") == 0); GPR_ASSERT(gpr_slice_str_cmp(md_elems[0].value, expected_md_value) == 0); GPR_ASSERT(user_data != NULL); GPR_ASSERT(strcmp((const char *)user_data, test_user_data) == 0); gpr_free(expected_md_value); } static void on_jwt_creds_get_metadata_failure(grpc_exec_ctx *exec_ctx, void *user_data, grpc_credentials_md *md_elems, size_t num_md, grpc_credentials_status status) { GPR_ASSERT(status == GRPC_CREDENTIALS_ERROR); GPR_ASSERT(num_md == 0); GPR_ASSERT(user_data != NULL); GPR_ASSERT(strcmp((const char *)user_data, test_user_data) == 0); } static void test_jwt_creds_success(void) { char *json_key_string = test_json_key_str(); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL, NULL}; grpc_call_credentials *jwt_creds = grpc_service_account_jwt_access_credentials_create( json_key_string, grpc_max_auth_token_lifetime(), NULL); /* First request: jwt_encode_and_sign should be called. */ grpc_jwt_encode_and_sign_set_override(encode_and_sign_jwt_success); grpc_call_credentials_get_request_metadata( &exec_ctx, jwt_creds, NULL, auth_md_ctx, on_jwt_creds_get_metadata_success, (void *)test_user_data); grpc_exec_ctx_flush(&exec_ctx); /* Second request: the cached token should be served directly. */ grpc_jwt_encode_and_sign_set_override( encode_and_sign_jwt_should_not_be_called); grpc_call_credentials_get_request_metadata( &exec_ctx, jwt_creds, NULL, auth_md_ctx, on_jwt_creds_get_metadata_success, (void *)test_user_data); grpc_exec_ctx_flush(&exec_ctx); /* Third request: Different service url so jwt_encode_and_sign should be called again (no caching). */ auth_md_ctx.service_url = other_test_service_url; grpc_jwt_encode_and_sign_set_override(encode_and_sign_jwt_success); grpc_call_credentials_get_request_metadata( &exec_ctx, jwt_creds, NULL, auth_md_ctx, on_jwt_creds_get_metadata_success, (void *)test_user_data); grpc_exec_ctx_flush(&exec_ctx); gpr_free(json_key_string); grpc_call_credentials_unref(jwt_creds); grpc_jwt_encode_and_sign_set_override(NULL); } static void test_jwt_creds_signing_failure(void) { char *json_key_string = test_json_key_str(); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL, NULL}; grpc_call_credentials *jwt_creds = grpc_service_account_jwt_access_credentials_create( json_key_string, grpc_max_auth_token_lifetime(), NULL); grpc_jwt_encode_and_sign_set_override(encode_and_sign_jwt_failure); grpc_call_credentials_get_request_metadata( &exec_ctx, jwt_creds, NULL, auth_md_ctx, on_jwt_creds_get_metadata_failure, (void *)test_user_data); gpr_free(json_key_string); grpc_call_credentials_unref(jwt_creds); grpc_jwt_encode_and_sign_set_override(NULL); grpc_exec_ctx_finish(&exec_ctx); } static void set_google_default_creds_env_var_with_file_contents( const char *file_prefix, const char *contents) { size_t contents_len = strlen(contents); char *creds_file_name; FILE *creds_file = gpr_tmpfile(file_prefix, &creds_file_name); GPR_ASSERT(creds_file_name != NULL); GPR_ASSERT(creds_file != NULL); GPR_ASSERT(fwrite(contents, 1, contents_len, creds_file) == contents_len); fclose(creds_file); gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, creds_file_name); gpr_free(creds_file_name); } static void test_google_default_creds_auth_key(void) { grpc_service_account_jwt_access_credentials *jwt; grpc_composite_channel_credentials *creds; char *json_key = test_json_key_str(); grpc_flush_cached_google_default_credentials(); set_google_default_creds_env_var_with_file_contents( "json_key_google_default_creds", json_key); gpr_free(json_key); creds = (grpc_composite_channel_credentials *) grpc_google_default_credentials_create(); GPR_ASSERT(creds != NULL); jwt = (grpc_service_account_jwt_access_credentials *)creds->call_creds; GPR_ASSERT( strcmp(jwt->key.client_id, "777-abaslkan11hlb6nmim3bpspl31ud.apps.googleusercontent.com") == 0); grpc_channel_credentials_unref(&creds->base); gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); /* Reset. */ } static void test_google_default_creds_refresh_token(void) { grpc_google_refresh_token_credentials *refresh; grpc_composite_channel_credentials *creds; grpc_flush_cached_google_default_credentials(); set_google_default_creds_env_var_with_file_contents( "refresh_token_google_default_creds", test_refresh_token_str); creds = (grpc_composite_channel_credentials *) grpc_google_default_credentials_create(); GPR_ASSERT(creds != NULL); refresh = (grpc_google_refresh_token_credentials *)creds->call_creds; GPR_ASSERT(strcmp(refresh->refresh_token.client_id, "32555999999.apps.googleusercontent.com") == 0); grpc_channel_credentials_unref(&creds->base); gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); /* Reset. */ } static int default_creds_gce_detection_httpcli_get_success_override( grpc_exec_ctx *exec_ctx, const grpc_httpcli_request *request, gpr_timespec deadline, grpc_httpcli_response_cb on_response, void *user_data) { grpc_httpcli_response response = http_response(200, ""); grpc_http_header header; header.key = "Metadata-Flavor"; header.value = "Google"; response.hdr_count = 1; response.hdrs = &header; GPR_ASSERT(strcmp(request->http.path, "/") == 0); GPR_ASSERT(strcmp(request->host, "metadata.google.internal") == 0); on_response(exec_ctx, user_data, &response); return 1; } static char *null_well_known_creds_path_getter(void) { return NULL; } static void test_google_default_creds_gce(void) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_composite_channel_credentials *creds; grpc_channel_credentials *cached_creds; grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL, NULL}; grpc_flush_cached_google_default_credentials(); gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); /* Reset. */ grpc_override_well_known_credentials_path_getter( null_well_known_creds_path_getter); /* Simulate a successful detection of GCE. */ grpc_httpcli_set_override( default_creds_gce_detection_httpcli_get_success_override, httpcli_post_should_not_be_called); creds = (grpc_composite_channel_credentials *) grpc_google_default_credentials_create(); /* Verify that the default creds actually embeds a GCE creds. */ GPR_ASSERT(creds != NULL); GPR_ASSERT(creds->call_creds != NULL); grpc_httpcli_set_override(compute_engine_httpcli_get_success_override, httpcli_post_should_not_be_called); grpc_call_credentials_get_request_metadata( &exec_ctx, creds->call_creds, NULL, auth_md_ctx, on_oauth2_creds_get_metadata_success, (void *)test_user_data); grpc_exec_ctx_flush(&exec_ctx); grpc_exec_ctx_finish(&exec_ctx); /* Check that we get a cached creds if we call grpc_google_default_credentials_create again. GCE detection should not occur anymore either. */ grpc_httpcli_set_override(httpcli_get_should_not_be_called, httpcli_post_should_not_be_called); cached_creds = grpc_google_default_credentials_create(); GPR_ASSERT(cached_creds == &creds->base); /* Cleanup. */ grpc_channel_credentials_release(cached_creds); grpc_channel_credentials_release(&creds->base); grpc_httpcli_set_override(NULL, NULL); grpc_override_well_known_credentials_path_getter(NULL); } static int default_creds_gce_detection_httpcli_get_failure_override( grpc_exec_ctx *exec_ctx, const grpc_httpcli_request *request, gpr_timespec deadline, grpc_httpcli_response_cb on_response, void *user_data) { /* No magic header. */ grpc_httpcli_response response = http_response(200, ""); GPR_ASSERT(strcmp(request->http.path, "/") == 0); GPR_ASSERT(strcmp(request->host, "metadata.google.internal") == 0); on_response(exec_ctx, user_data, &response); return 1; } static void test_no_google_default_creds(void) { grpc_flush_cached_google_default_credentials(); gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); /* Reset. */ grpc_override_well_known_credentials_path_getter( null_well_known_creds_path_getter); /* Simulate a successful detection of GCE. */ grpc_httpcli_set_override( default_creds_gce_detection_httpcli_get_failure_override, httpcli_post_should_not_be_called); GPR_ASSERT(grpc_google_default_credentials_create() == NULL); /* Try a cached one. GCE detection should not occur anymore. */ grpc_httpcli_set_override(httpcli_get_should_not_be_called, httpcli_post_should_not_be_called); GPR_ASSERT(grpc_google_default_credentials_create() == NULL); /* Cleanup. */ grpc_httpcli_set_override(NULL, NULL); grpc_override_well_known_credentials_path_getter(NULL); } typedef enum { PLUGIN_INITIAL_STATE, PLUGIN_GET_METADATA_CALLED_STATE, PLUGIN_DESTROY_CALLED_STATE } plugin_state; typedef struct { const char *key; const char *value; } plugin_metadata; static const plugin_metadata plugin_md[] = {{"foo", "bar"}, {"hi", "there"}}; static void plugin_get_metadata_success(void *state, grpc_auth_metadata_context context, grpc_credentials_plugin_metadata_cb cb, void *user_data) { size_t i; grpc_metadata md[GPR_ARRAY_SIZE(plugin_md)]; plugin_state *s = (plugin_state *)state; GPR_ASSERT(strcmp(context.service_url, test_service_url) == 0); GPR_ASSERT(strcmp(context.method_name, test_method) == 0); GPR_ASSERT(context.channel_auth_context == NULL); GPR_ASSERT(context.reserved == NULL); *s = PLUGIN_GET_METADATA_CALLED_STATE; for (i = 0; i < GPR_ARRAY_SIZE(plugin_md); i++) { memset(&md[i], 0, sizeof(grpc_metadata)); md[i].key = plugin_md[i].key; md[i].value = plugin_md[i].value; md[i].value_length = strlen(plugin_md[i].value); } cb(user_data, md, GPR_ARRAY_SIZE(md), GRPC_STATUS_OK, NULL); } static void plugin_get_metadata_failure(void *state, grpc_auth_metadata_context context, grpc_credentials_plugin_metadata_cb cb, void *user_data) { plugin_state *s = (plugin_state *)state; GPR_ASSERT(strcmp(context.service_url, test_service_url) == 0); GPR_ASSERT(strcmp(context.method_name, test_method) == 0); GPR_ASSERT(context.channel_auth_context == NULL); GPR_ASSERT(context.reserved == NULL); *s = PLUGIN_GET_METADATA_CALLED_STATE; cb(user_data, NULL, 0, GRPC_STATUS_UNAUTHENTICATED, "Could not get metadata for plugin."); } static void on_plugin_metadata_received_success( grpc_exec_ctx *exec_ctx, void *user_data, grpc_credentials_md *md_elems, size_t num_md, grpc_credentials_status status) { size_t i = 0; GPR_ASSERT(user_data == NULL); GPR_ASSERT(md_elems != NULL); GPR_ASSERT(num_md == GPR_ARRAY_SIZE(plugin_md)); for (i = 0; i < num_md; i++) { GPR_ASSERT(gpr_slice_str_cmp(md_elems[i].key, plugin_md[i].key) == 0); GPR_ASSERT(gpr_slice_str_cmp(md_elems[i].value, plugin_md[i].value) == 0); } } static void on_plugin_metadata_received_failure( grpc_exec_ctx *exec_ctx, void *user_data, grpc_credentials_md *md_elems, size_t num_md, grpc_credentials_status status) { GPR_ASSERT(user_data == NULL); GPR_ASSERT(md_elems == NULL); GPR_ASSERT(num_md == 0); GPR_ASSERT(status == GRPC_CREDENTIALS_ERROR); } static void plugin_destroy(void *state) { plugin_state *s = (plugin_state *)state; *s = PLUGIN_DESTROY_CALLED_STATE; } static void test_metadata_plugin_success(void) { grpc_call_credentials *creds; plugin_state state = PLUGIN_INITIAL_STATE; grpc_metadata_credentials_plugin plugin; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL, NULL}; plugin.state = &state; plugin.get_metadata = plugin_get_metadata_success; plugin.destroy = plugin_destroy; creds = grpc_metadata_credentials_create_from_plugin(plugin, NULL); GPR_ASSERT(state == PLUGIN_INITIAL_STATE); grpc_call_credentials_get_request_metadata( &exec_ctx, creds, NULL, auth_md_ctx, on_plugin_metadata_received_success, NULL); GPR_ASSERT(state == PLUGIN_GET_METADATA_CALLED_STATE); grpc_call_credentials_release(creds); GPR_ASSERT(state == PLUGIN_DESTROY_CALLED_STATE); grpc_exec_ctx_finish(&exec_ctx); } static void test_metadata_plugin_failure(void) { grpc_call_credentials *creds; plugin_state state = PLUGIN_INITIAL_STATE; grpc_metadata_credentials_plugin plugin; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL, NULL}; plugin.state = &state; plugin.get_metadata = plugin_get_metadata_failure; plugin.destroy = plugin_destroy; creds = grpc_metadata_credentials_create_from_plugin(plugin, NULL); GPR_ASSERT(state == PLUGIN_INITIAL_STATE); grpc_call_credentials_get_request_metadata( &exec_ctx, creds, NULL, auth_md_ctx, on_plugin_metadata_received_failure, NULL); GPR_ASSERT(state == PLUGIN_GET_METADATA_CALLED_STATE); grpc_call_credentials_release(creds); GPR_ASSERT(state == PLUGIN_DESTROY_CALLED_STATE); grpc_exec_ctx_finish(&exec_ctx); } static void test_get_well_known_google_credentials_file_path(void) { #ifdef GPR_POSIX_FILE char *path; char *old_home = gpr_getenv("HOME"); gpr_setenv("HOME", "/tmp"); path = grpc_get_well_known_google_credentials_file_path(); GPR_ASSERT(path != NULL); GPR_ASSERT(0 == strcmp("/tmp/.config/" GRPC_GOOGLE_CLOUD_SDK_CONFIG_DIRECTORY "/" GRPC_GOOGLE_WELL_KNOWN_CREDENTIALS_FILE, path)); gpr_free(path); #if defined(GPR_POSIX_ENV) || defined(GPR_LINUX_ENV) unsetenv("HOME"); path = grpc_get_well_known_google_credentials_file_path(); GPR_ASSERT(path == NULL); #endif /* GPR_POSIX_ENV || GPR_LINUX_ENV */ gpr_setenv("HOME", old_home); gpr_free(old_home); #else /* GPR_POSIX_FILE */ char *path = grpc_get_well_known_google_credentials_file_path(); GPR_ASSERT(path != NULL); gpr_free(path); #endif } int main(int argc, char **argv) { grpc_test_init(argc, argv); grpc_init(); test_empty_md_store(); test_ref_unref_empty_md_store(); test_add_to_empty_md_store(); test_add_cstrings_to_empty_md_store(); test_empty_preallocated_md_store(); test_add_abunch_to_md_store(); test_oauth2_token_fetcher_creds_parsing_ok(); test_oauth2_token_fetcher_creds_parsing_bad_http_status(); test_oauth2_token_fetcher_creds_parsing_empty_http_body(); test_oauth2_token_fetcher_creds_parsing_invalid_json(); test_oauth2_token_fetcher_creds_parsing_missing_token(); test_oauth2_token_fetcher_creds_parsing_missing_token_type(); test_oauth2_token_fetcher_creds_parsing_missing_token_lifetime(); test_google_iam_creds(); test_access_token_creds(); test_channel_oauth2_composite_creds(); test_oauth2_google_iam_composite_creds(); test_channel_oauth2_google_iam_composite_creds(); test_compute_engine_creds_success(); test_compute_engine_creds_failure(); test_refresh_token_creds_success(); test_refresh_token_creds_failure(); test_jwt_creds_success(); test_jwt_creds_signing_failure(); test_google_default_creds_auth_key(); test_google_default_creds_refresh_token(); test_google_default_creds_gce(); test_no_google_default_creds(); test_metadata_plugin_success(); test_metadata_plugin_failure(); test_get_well_known_google_credentials_file_path(); grpc_shutdown(); return 0; }
leifurhauks/grpc
test/core/security/credentials_test.c
C
bsd-3-clause
49,923
package edu.ucdenver.ccp.datasource.fileparsers.ebi.interpro; /* * #%L * Colorado Computational Pharmacology's common module * %% * Copyright (C) 2012 - 2015 Regents of the University of Colorado * %% * 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. Neither the name of the Regents of the University of Colorado 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 HOLDER 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. * #L% */ import edu.ucdenver.ccp.datasource.identifiers.DataSourceIdentifier; import edu.ucdenver.ccp.datasource.identifiers.UnknownDataSourceIdentifier; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.Gene3dID; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.HamapAnnotationRuleID; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.PantherID; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.PfamID; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.PirSfID; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.PrintsID; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.ProDomID; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.PrositeID; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.SmartID; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.SuperFamID; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.TigrFamsID; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.UncharacterizedPfamID; public class InterProExternalReferenceFactory { private static final String PFAM_PREFIX = "PF"; private static final String TIGRFAMS_PREFIX = "TIGR"; private static final String GENE3D_PREFIX = "G3DSA:"; private static final String SUPERFAM_PREFIX = "SSF"; private static final String PROSITE_PREFIX = "PS"; private static final String SMART_PREFIX = "SM"; private static final String PRINTS_PREFIX = "PR"; private static final String UPFAM_PREFIX = "UPF"; private static final String PANTHER_PREFIX = "PTHR"; private static final String PIR_PREFIX = "PIRSF"; private static final String HAMAP_PREFIX = "MF_"; private static final String PRODOM_PREFIX = "PD"; public static DataSourceIdentifier<String> parseExternalReference( String databaseReferenceID) { if (databaseReferenceID.startsWith(PFAM_PREFIX)) return new PfamID(databaseReferenceID); if (databaseReferenceID.startsWith(TIGRFAMS_PREFIX)) return new TigrFamsID(databaseReferenceID); if (databaseReferenceID.startsWith(GENE3D_PREFIX)) return new Gene3dID(databaseReferenceID); if (databaseReferenceID.startsWith(SUPERFAM_PREFIX)) return new SuperFamID(databaseReferenceID); if (databaseReferenceID.startsWith(PROSITE_PREFIX)) return new PrositeID(databaseReferenceID); if (databaseReferenceID.startsWith(SMART_PREFIX)) return new SmartID(databaseReferenceID); if (databaseReferenceID.startsWith(PRINTS_PREFIX)) return new PrintsID(databaseReferenceID); if (databaseReferenceID.startsWith(UPFAM_PREFIX)) return new UncharacterizedPfamID(databaseReferenceID); if (databaseReferenceID.startsWith(PANTHER_PREFIX)) return new PantherID(databaseReferenceID); if (databaseReferenceID.startsWith(PIR_PREFIX)) return new PirSfID(databaseReferenceID); if (databaseReferenceID.startsWith(HAMAP_PREFIX)) return new HamapAnnotationRuleID(databaseReferenceID); if (databaseReferenceID.startsWith(PRODOM_PREFIX)) return new ProDomID(databaseReferenceID); return new UnknownDataSourceIdentifier(databaseReferenceID); } }
UCDenver-ccp/datasource
datasource-fileparsers/src/main/java/edu/ucdenver/ccp/datasource/fileparsers/ebi/interpro/InterProExternalReferenceFactory.java
Java
bsd-3-clause
4,794
/* * Copyright (c) 1995 John Birrell <jb@cimlogic.com.au>. * Copyright (c) 1994 by Chris Provenzano, proven@mit.edu * All rights reserved. * * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by John Birrell * and Chris Provenzano. * 4. Neither the name of the author nor the names of any co-contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL 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 REGENTS 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. * * $FreeBSD$ */ #include <pthread.h> #include "libc_private.h" #include "thr_private.h" #undef errno extern int errno; int * __error(void) { struct pthread *curthread; if (_thr_initial != NULL) { curthread = _get_curthread(); if (curthread != NULL && curthread != _thr_initial) return (&curthread->error); } return (&errno); }
jhbsz/OSI-OS
Operating-System/Libraries/libthr/sys/thr_error.c
C
bsd-3-clause
2,190
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db import models class Location(models.Model): address = models.CharField(blank=True) latitude = models.DecimalField(max_digits=10, decimal_places=6) longitude = models.DecimalField(max_digits=10, decimal_places=6) created = models.DateTimeField(auto_add_now=True, editable=False) updated = models.DateTimeField(auto_add=True, editable=False) owner = models.ForeignKey(User) def get_absolute_url(self): return reverse('location-detail', args=[str(self.id)]) def __str__(self): return '{id: %d, latitude: %d, longitude: %d}' % ( self.id, self.latitude, self.longitude ) class Meta: app_label = 'locations' get_latest_by = 'updated' ordering = ['updated'] verbose_name = 'location' verbose_name_plural = 'Locations'
derrickyoo/serve-tucson
serve_tucson/locations/models.py
Python
bsd-3-clause
956
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WM_LOCK_ACTION_HANDLER_LAYOUT_MANAGER_H_ #define ASH_WM_LOCK_ACTION_HANDLER_LAYOUT_MANAGER_H_ #include "ash/ash_export.h" #include "ash/lock_screen_action/lock_screen_action_background_controller.h" #include "ash/lock_screen_action/lock_screen_action_background_observer.h" #include "ash/lock_screen_action/lock_screen_action_background_state.h" #include "ash/public/cpp/shelf_types.h" #include "ash/tray_action/tray_action.h" #include "ash/tray_action/tray_action_observer.h" #include "ash/wm/lock_layout_manager.h" #include "base/macros.h" #include "base/scoped_observation.h" namespace ash { class Shelf; // Window layout manager for windows intended to handle lock tray actions. // Since "new note" is currently the only supported action, the layout // manager uses new note tray action state to determine it state. // The layout is intended to be used for LockActionHandlerContainer. The // container state depends on the lock screen "new_note" action state: // * for active action state - the windows should be visible above the lock // screen // * for rest of the states - the windows should not be visible. // The layout manager will observe new note action state changes and update // the container's children state as needed. // The windows in this container will have be maximized, if possible. If they // are not resizable, they will be centered on the screen - similar to windows // in lock screen container. // Unlike lock layout manager, when maximizing windows, this layout manager will // ensure that the windows do not obscure the system shelf. class ASH_EXPORT LockActionHandlerLayoutManager : public LockLayoutManager, public TrayActionObserver, public LockScreenActionBackgroundObserver { public: LockActionHandlerLayoutManager( aura::Window* window, Shelf* shelf, LockScreenActionBackgroundController* action_background_controller); LockActionHandlerLayoutManager(const LockActionHandlerLayoutManager&) = delete; LockActionHandlerLayoutManager& operator=( const LockActionHandlerLayoutManager&) = delete; ~LockActionHandlerLayoutManager() override; // WmDefaultLayoutManager: void OnWindowAddedToLayout(aura::Window* child) override; void OnChildWindowVisibilityChanged(aura::Window* child, bool visibile) override; // TrayActionObserver: void OnLockScreenNoteStateChanged(mojom::TrayActionState state) override; // LockScreenActionBackgroundObserver: void OnLockScreenActionBackgroundStateChanged( LockScreenActionBackgroundState state) override; private: // Updates the child window visibility depending on lock screen note action // state and the lock screen action background state. void UpdateChildren(mojom::TrayActionState action_state, LockScreenActionBackgroundState background_state); LockScreenActionBackgroundController* action_background_controller_; base::ScopedObservation<TrayAction, TrayActionObserver> tray_action_observation_{this}; base::ScopedObservation<LockScreenActionBackgroundController, LockScreenActionBackgroundObserver> action_background_observation_{this}; }; } // namespace ash #endif // ASH_WM_LOCK_ACTION_HANDLER_LAYOUT_MANAGER_H_
nwjs/chromium.src
ash/wm/lock_action_handler_layout_manager.h
C
bsd-3-clause
3,475
""" Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import print_function, unicode_literals, absolute_import import json import pytest import requests import requests.exceptions from tests.constants import LOCALHOST_REGISTRY_HTTP, DOCKER0_REGISTRY_HTTP, MOCK, TEST_IMAGE from tests.util import uuid_value from osbs.utils import ImageName from atomic_reactor.core import ContainerTasker from atomic_reactor.constants import CONTAINER_DOCKERPY_BUILD_METHOD from atomic_reactor.inner import DockerBuildWorkflow from tests.constants import MOCK_SOURCE if MOCK: from tests.docker_mock import mock_docker @pytest.fixture() def temp_image_name(): return ImageName(repo=("atomic-reactor-tests-%s" % uuid_value())) @pytest.fixture() def is_registry_running(): """ is docker registry running (at {docker0,lo}:5000)? """ try: lo_response = requests.get(LOCALHOST_REGISTRY_HTTP) except requests.exceptions.ConnectionError: return False if not lo_response.ok: return False try: lo_response = requests.get(DOCKER0_REGISTRY_HTTP) # leap of faith except requests.exceptions.ConnectionError: return False if not lo_response.ok: return False return True @pytest.fixture(scope="module") def docker_tasker(): if MOCK: mock_docker() ct = ContainerTasker(retry_times=0) ct.build_method = CONTAINER_DOCKERPY_BUILD_METHOD return ct @pytest.fixture(params=[True, False]) def reactor_config_map(request): return request.param @pytest.fixture(params=[True, False]) def inspect_only(request): return request.param @pytest.fixture def user_params(monkeypatch): """ Setting default image_tag in the env var USER_PARAMS. Any tests requiring to create an instance of :class:`DockerBuildWorkflow` requires this fixture. """ monkeypatch.setenv('USER_PARAMS', json.dumps({'image_tag': TEST_IMAGE})) @pytest.fixture def workflow(user_params): return DockerBuildWorkflow(source=MOCK_SOURCE) @pytest.mark.optionalhook def pytest_html_results_table_row(report, cells): if report.passed or report.skipped: del cells[:]
projectatomic/atomic-reactor
tests/conftest.py
Python
bsd-3-clause
2,306
/* Copyright © 2016 Matthew Champion 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 name of mattunderscore.com 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 MATTHEW CHAMPION 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. */ package com.mattunderscore.specky.generator; import com.mattunderscore.specky.model.SpecDesc; import com.mattunderscore.specky.model.TypeDesc; import com.squareup.javapoet.TypeSpec; import static com.mattunderscore.specky.javapoet.javadoc.JavaDocBuilder.docType; import static com.squareup.javapoet.TypeSpec.interfaceBuilder; import static javax.lang.model.element.Modifier.PUBLIC; /** * {@link TypeInitialiser} for abstract types. * @author Matt Champion on 10/07/2016 */ public final class AbstractTypeInitialiser implements TypeInitialiser<TypeDesc> { /** * @return a type builder for abstract types */ public TypeSpec.Builder create(SpecDesc specDesc, TypeDesc typeDesc) { return interfaceBuilder(typeDesc.getName()) .addModifiers(PUBLIC) .addJavadoc( docType() .setDescription( typeDesc.getDescription() == null ? "View type $L.\n\nAuto-generated from specification." : typeDesc.getDescription()) .setAuthor(typeDesc.getAuthor()) .toJavaDoc(), typeDesc.getName()); } }
mattunderscorechampion/specky
code-generation/src/main/java/com/mattunderscore/specky/generator/AbstractTypeInitialiser.java
Java
bsd-3-clause
2,704
package org.scalaide.core.internal.project.scopes import scala.tools.nsc.Settings import org.eclipse.core.resources.IContainer import org.eclipse.core.resources.IFile import org.eclipse.core.resources.IMarker import org.eclipse.core.resources.IResource import org.eclipse.core.runtime.IProgressMonitor import org.eclipse.core.runtime.SubMonitor import org.eclipse.jdt.core.IJavaModelMarker import org.scalaide.core.IScalaProject import org.scalaide.core.SdtConstants import org.scalaide.core.internal.builder.BuildProblemMarker import org.scalaide.core.internal.builder.EclipseBuildManager import org.scalaide.core.internal.builder.zinc.EclipseSbtBuildManager import org.scalaide.core.internal.project.CompileScope import sbt.inc.Analysis import sbt.inc.IncOptions import java.io.File /** * Manages compilation of sources for given scope. * @see CompileScope scopes */ class BuildScopeUnit(val scope: CompileScope, val owningProject: IScalaProject, settings: Settings, val dependentUnitInstances: Seq[BuildScopeUnit] = Seq.empty) extends EclipseBuildManager { private val delegate = new EclipseSbtBuildManager(owningProject, settings, Some(owningProject.underlying.getFile(".cache-" + scope.name)), addThemToClasspath, srcOutputs) private val scopeFilesToCompile = ScopeFilesToCompile(toCompile, owningProject) private def managesSrcFolder(src: IContainer) = scope.isValidSourcePath(src.getProjectRelativePath) private def addThemToClasspath = owningProject.sourceOutputFolders.collect { case (src, out) if !managesSrcFolder(src) => out.getLocation } private def srcOutputs = owningProject.sourceOutputFolders.collect { case entry @ (src, out) if managesSrcFolder(src) => entry } def sources: Seq[IContainer] = srcOutputs.unzip._1 override def clean(implicit monitor: IProgressMonitor): Unit = delegate.clean override def build(addedOrUpdated: Set[IFile], removed: Set[IFile], monitor: SubMonitor): Unit = { hasInternalErrors = if (areDependedUnitsBuilt) { def javaHasErrors: Boolean = { val SeverityNotSet = -1 owningProject.underlying.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE).exists { marker => val severity = marker.getAttribute(IMarker.SEVERITY, SeverityNotSet) severity == IMarker.SEVERITY_ERROR && scope.isValidSourcePath(marker.getResource.getLocation) } } delegate.build(scopeFilesToCompile(addedOrUpdated), toCompile(removed), monitor) delegate.hasErrors || javaHasErrors } else { true } } private def areDependedUnitsBuilt = { val wrongScopes = dependentUnitInstances filter { _.hasErrors } map { _.scope } if (wrongScopes.nonEmpty) { BuildProblemMarker.create(owningProject.underlying, s"${owningProject.underlying.getName}'s ${scope.name} not built due to errors in dependent scope(s) ${wrongScopes.map(_.name).toSet.mkString(", ")}") false } else true } private def toCompile(sources: Set[IFile]) = (for { (src, _) <- srcOutputs source <- sources if src.getProjectRelativePath.isPrefixOf(source.getProjectRelativePath) } yield source).toSet override def canTrackDependencies: Boolean = delegate.canTrackDependencies override def invalidateAfterLoad: Boolean = delegate.invalidateAfterLoad override def latestAnalysis(incOptions: => IncOptions): Analysis = delegate.latestAnalysis(incOptions) override def buildManagerOf(outputFile: File): Option[EclipseBuildManager] = owningProject.sourceOutputFolders collectFirst { case (sourceFolder, outputFolder) if outputFolder.getLocation.toFile == outputFile && scope.isValidSourcePath(sourceFolder.getProjectRelativePath) => this } } private case class ScopeFilesToCompile(toCompile: Set[IFile] => Set[IFile], owningProject: IScalaProject) { private var run: Set[IFile] => Set[IFile] = once private def once(sources: Set[IFile]): Set[IFile] = { run = forever toCompile(owningProject.allSourceFiles) } private def forever(sources: Set[IFile]): Set[IFile] = toCompile(sources) ++ resetJavaMarkers(getValidJavaSourcesOfThisScope) def apply(sources: Set[IFile]): Set[IFile] = run(sources) private def getValidJavaSourcesOfThisScope: Set[IFile] = { val Dot = 1 toCompile(owningProject.allSourceFiles .filter { _.getLocation.getFileExtension == SdtConstants.JavaFileExtn.drop(Dot) }) } private def resetJavaMarkers(javaFiles: Set[IFile]): Set[IFile] = { javaFiles.foreach { _.deleteMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE) } javaFiles } }
Kwestor/scala-ide
org.scala-ide.sdt.core/src/org/scalaide/core/internal/project/scopes/BuildScopeUnit.scala
Scala
bsd-3-clause
4,660
--simple case: order by different data types: --smallint, varchar(n), time , set create table uoo( col1 smallint, col2 varchar(10), col3 time, col4 set ); insert into uoo values (1, 'fff', '10:30:42 am', {1,2,3}), (4, 'ccc', '4:31:12', {5,2,1}), (3, 'aaa', '20:12:41', {12,34,21}), (5, 'ddd', '2:24:39 pm', {4,4,4}), (2, 'bbb', '0:14:22', {67,11,22}); select * from uoo order by col1; update uoo set col1=col1+2 order by col1; select * from uoo order by col1; update uoo set col1=col1+2 order by col2; select * from uoo order by col1; update uoo set col1=col1+2 order by col3; select * from uoo order by col1; update uoo set col1=col1+2 order by col4; select * from uoo order by col1; drop table uoo;
CUBRID/cubrid-testcases
sql/_17_sql_extension2/_02_full_test/_02_update_order_by/cases/update_order_by_002.sql
SQL
bsd-3-clause
721
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #ifndef NATIVE_EXTENSION_VTK_VTKCENTEROFMASSWRAP_H #define NATIVE_EXTENSION_VTK_VTKCENTEROFMASSWRAP_H #include <nan.h> #include <vtkSmartPointer.h> #include <vtkCenterOfMass.h> #include "vtkPointSetAlgorithmWrap.h" #include "../../plus/plus.h" class VtkCenterOfMassWrap : public VtkPointSetAlgorithmWrap { public: using Nan::ObjectWrap::Wrap; static void Init(v8::Local<v8::Object> exports); static void InitPtpl(); static void ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info); VtkCenterOfMassWrap(vtkSmartPointer<vtkCenterOfMass>); VtkCenterOfMassWrap(); ~VtkCenterOfMassWrap( ); static Nan::Persistent<v8::FunctionTemplate> ptpl; private: static void New(const Nan::FunctionCallbackInfo<v8::Value>& info); static void ComputeCenterOfMass(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetCenter(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetUseScalarsAsWeights(const Nan::FunctionCallbackInfo<v8::Value>& info); static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetCenter(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetUseScalarsAsWeights(const Nan::FunctionCallbackInfo<v8::Value>& info); #ifdef VTK_NODE_PLUS_VTKCENTEROFMASSWRAP_CLASSDEF VTK_NODE_PLUS_VTKCENTEROFMASSWRAP_CLASSDEF #endif }; #endif
axkibe/node-vtk
wrappers/8.1.1/vtkCenterOfMassWrap.h
C
bsd-3-clause
1,568
import shutil import os import jinja2 import string import subprocess import re from xen.provisioning.HdManager import HdManager from settings.settingsLoader import OXA_XEN_SERVER_KERNEL,OXA_XEN_SERVER_INITRD,OXA_DEBIAN_INTERFACES_FILE_LOCATION,OXA_DEBIAN_UDEV_FILE_LOCATION, OXA_DEBIAN_HOSTNAME_FILE_LOCATION, OXA_DEBIAN_SECURITY_ACCESS_FILE_LOCATION from utils.Logger import Logger class OfeliaDebianVMConfigurator: logger = Logger.getLogger() ''' Private methods ''' @staticmethod def __configureInterfacesFile(vm,iFile): #Loopback iFile.write("auto lo\niface lo inet loopback\n\n") #Interfaces for inter in vm.xen_configuration.interfaces.interface : if inter.ismgmt: #is a mgmt interface interfaceString = "auto "+inter.name+"\n"+\ "iface "+inter.name+" inet static\n"+\ "\taddress "+inter.ip +"\n"+\ "\tnetmask "+inter.mask+"\n" if inter.gw != None and inter.gw != "": interfaceString +="\tgateway "+inter.gw+"\n" if inter.dns1 != None and inter.dns1 != "": interfaceString+="\tdns-nameservers "+inter.dns1 if inter.dns2 != None and inter.dns2 != "": interfaceString+=" "+inter.dns2 interfaceString +="\n\n" iFile.write(interfaceString) else: #is a data interface iFile.write("auto "+inter.name+"\n\n") @staticmethod def __configureUdevFile(vm,uFile): for inter in vm.xen_configuration.interfaces.interface: uFile.write('SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="'+inter.mac+'", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="'+inter.name+'"\n') @staticmethod def __configureHostname(vm,hFile): hFile.write(vm.name) @staticmethod def __createParavirtualizationFileHdConfigFile(vm,env): template_name = "paraVirtualizedFileHd.pt" template = env.get_template(template_name) #Set vars&render output = template.render( kernelImg=OXA_XEN_SERVER_KERNEL, initrdImg=OXA_XEN_SERVER_INITRD, hdFilePath=HdManager.getHdPath(vm), swapFilePath=HdManager.getSwapPath(vm), vm=vm) #write file cfile = open(HdManager.getConfigFilePath(vm),'w') cfile.write(output) cfile.close() ''' Public methods ''' @staticmethod def getIdentifier(): return OfeliaDebianVMConfigurator.__name__ @staticmethod def _configureNetworking(vm,path): #Configure interfaces and udev settings try: try: #Backup current files shutil.copy(path+OXA_DEBIAN_INTERFACES_FILE_LOCATION,path+OXA_DEBIAN_INTERFACES_FILE_LOCATION+".bak") shutil.copy(path+OXA_DEBIAN_UDEV_FILE_LOCATION,path+OXA_DEBIAN_UDEV_FILE_LOCATION+".bak") except Exception as e: pass with open(path+OXA_DEBIAN_INTERFACES_FILE_LOCATION,'w') as openif: OfeliaDebianVMConfigurator.__configureInterfacesFile(vm,openif) with open(path+OXA_DEBIAN_UDEV_FILE_LOCATION,'w') as openudev: OfeliaDebianVMConfigurator.__configureUdevFile(vm,openudev) except Exception as e: OfeliaDebianVMConfigurator.logger.error(str(e)) raise Exception("Could not configure interfaces or Udev file") @staticmethod def _configureLDAPSettings(vm,path): try: file = open(path+OXA_DEBIAN_SECURITY_ACCESS_FILE_LOCATION, "r") text = file.read() file.close() file = open(path+OXA_DEBIAN_SECURITY_ACCESS_FILE_LOCATION, "w") #Scape spaces and tabs projectName = string.replace(vm.project_name,' ','_') projectName = string.replace(projectName,'\t','__') file.write(text.replace("__projectId","@proj_"+vm.project_id+"_"+projectName)) file.close() except Exception as e: OfeliaDebianVMConfigurator.logger.error("Could not configure LDAP file!! - "+str(e)) @staticmethod def _configureHostName(vm,path): try: with open(path+OXA_DEBIAN_HOSTNAME_FILE_LOCATION,'w') as openhost: OfeliaDebianVMConfigurator.__configureHostname(vm, openhost) except Exception as e: OfeliaDebianVMConfigurator.logger.error("Could not configure hostname;skipping.. - "+str(e)) @staticmethod def _configureSSHServer(vm,path): try: OfeliaDebianVMConfigurator.logger.debug("Regenerating SSH keys...\n Deleting old keys...") subprocess.check_call("rm -f "+path+"/etc/ssh/ssh_host_*", shell=True, stdout=None) #subprocess.check_call("chroot "+path+" dpkg-reconfigure openssh-server ", shell=True, stdout=None) OfeliaDebianVMConfigurator.logger.debug("Creating SSH1 key; this may take some time...") subprocess.check_call("ssh-keygen -q -f "+path+"/etc/ssh/ssh_host_key -N '' -t rsa1", shell=True, stdout=None) OfeliaDebianVMConfigurator.logger.debug("Creating SSH2 RSA key; this may take some time...") subprocess.check_call("ssh-keygen -q -f "+path+"/etc/ssh/ssh_host_rsa_key -N '' -t rsa", shell=True, stdout=None) OfeliaDebianVMConfigurator.logger.debug("Creating SSH2 DSA key; this may take some time...") subprocess.check_call("ssh-keygen -q -f "+path+"/etc/ssh/ssh_host_dsa_key -N '' -t dsa", shell=True, stdout=None) except Exception as e: OfeliaDebianVMConfigurator.logger.error("Fatal error; could not regenerate SSH keys. Aborting to prevent VM to be unreachable..."+str(e)) raise e #Public methods @staticmethod def createVmConfigurationFile(vm): #get env template_dirs = [] template_dirs.append(os.path.join(os.path.dirname(__file__), 'templates/')) env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dirs)) if vm.xen_configuration.hd_setup_type == "file-image" and vm.xen_configuration.virtualization_setup_type == "paravirtualization" : OfeliaDebianVMConfigurator.__createParavirtualizationFileHdConfigFile(vm,env) else: raise Exception("type of file or type of virtualization not supported for the creation of xen vm configuration file") @staticmethod def configureVmDisk(vm, path): if not path or not re.match(r'[\s]*\/\w+\/\w+\/.*', path,re.IGNORECASE): #For security, should never happen anyway raise Exception("Incorrect vm path") #Configure networking OfeliaDebianVMConfigurator._configureNetworking(vm,path) OfeliaDebianVMConfigurator.logger.info("Network configured successfully...") #Configure LDAP settings OfeliaDebianVMConfigurator._configureLDAPSettings(vm,path) OfeliaDebianVMConfigurator.logger.info("Authentication configured successfully...") #Configure Hostname OfeliaDebianVMConfigurator._configureHostName(vm,path) OfeliaDebianVMConfigurator.logger.info("Hostname configured successfully...") #Regenerate SSH keys OfeliaDebianVMConfigurator._configureSSHServer(vm,path) OfeliaDebianVMConfigurator.logger.info("SSH have been keys regenerated...")
avlach/univbris-ocf
vt_manager/src/python/agent/xen/provisioning/configurators/ofelia/OfeliaDebianVMConfigurator.py
Python
bsd-3-clause
6,611
SirTrevor.Blocks.CmsBlock = SirTrevor.Blocks.Abstract.extend({ type: 'cms_block', title: 'Cms Block', header: '', blockHtml: _.template([ '<div class="row">', '<div class="col-md-12">', SpreeCmsForm.getSelectTemplate('block_id', 'CMS Block', availableCmsBlocks), '</div>', '<input class="js-state" type="hidden" name="state" value="<%- state || "" %>">', '</div>' ].join("\n")) });
praesensco/spree_cms
app/assets/javascripts/spree/backend/spree_cms/sir-trevor-js/custom-blocks/cms_block.js
JavaScript
bsd-3-clause
426
<!DOCTYPE html> <!-- | Generated by Apache Maven Doxia at 2014-11-25 | Rendered using Apache Maven Fluido Skin 1.3.0 --> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="Date-Revision-yyyymmdd" content="20141125" /> <meta http-equiv="Content-Language" content="en" /> <title>TrAP Networking: Sockets using NIO1 (Legacy) - Project Dependencies</title> <link rel="stylesheet" href="./css/apache-maven-fluido-1.3.0.min.css" /> <link rel="stylesheet" href="./css/site.css" /> <link rel="stylesheet" href="./css/print.css" media="print" /> <script type="text/javascript" src="./js/apache-maven-fluido-1.3.0.min.js"></script> </head> <body class="topBarDisabled"> <div class="container-fluid"> <div id="banner"> <div class="pull-left"> <div id="bannerLeft"> <h2>TrAP Networking: Sockets using NIO1 (Legacy)</h2> </div> </div> <div class="pull-right"> </div> <div class="clear"><hr/></div> </div> <div id="breadcrumbs"> <ul class="breadcrumb"> <li id="publishDate">Last Published: 2014-11-25</li> <li class="divider">|</li> <li id="projectVersion">Version: 1.3</li> <li class="divider">|</li> <li class=""> <a href="../index.html" title="Trap"> Trap</a> </li> <li class="divider ">/</li> <li class=""> <a href="./" title="TrAP Networking: Sockets using NIO1 (Legacy)"> TrAP Networking: Sockets using NIO1 (Legacy)</a> </li> <li class="divider ">/</li> <li class="">Project Dependencies</li> </ul> </div> <div class="row-fluid"> <div id="leftColumn" class="span3"> <div class="well sidebar-nav"> <ul class="nav nav-list"> <li class="nav-header">Trap 1.3</li> <li> <a href="../index.html" title="Introduction"> <i class="none"></i> Introduction</a> </li> <li> <a href="../trap-api/quickstart.html" title="Java Quickstart"> <i class="none"></i> Java Quickstart</a> </li> <li> <a href="../trap-js/index.html" title="JavaScript Quickstart"> <i class="none"></i> JavaScript Quickstart</a> </li> <li> <a href="../channels.html" title="Channels"> <i class="none"></i> Channels</a> </li> <li> <a href="../configuration.html" title="Configuration"> <i class="none"></i> Configuration</a> </li> <li class="nav-header">Language Specific Documentation</li> <li> <a href="../trap-api/index.html" title="Java"> <i class="none"></i> Java</a> </li> <li> <a href="../trap-js/index.html" title="JavaScript"> <i class="none"></i> JavaScript</a> </li> <li class="nav-header">Project Documentation</li> <li> <a href="project-info.html" title="Project Information"> <i class="icon-chevron-down"></i> Project Information</a> <ul class="nav nav-list"> <li> <a href="index.html" title="About"> <i class="none"></i> About</a> </li> <li> <a href="plugin-management.html" title="Plugin Management"> <i class="none"></i> Plugin Management</a> </li> <li> <a href="distribution-management.html" title="Distribution Management"> <i class="none"></i> Distribution Management</a> </li> <li> <a href="dependency-info.html" title="Dependency Information"> <i class="none"></i> Dependency Information</a> </li> <li> <a href="dependency-convergence.html" title="Dependency Convergence"> <i class="none"></i> Dependency Convergence</a> </li> <li> <a href="source-repository.html" title="Source Repository"> <i class="none"></i> Source Repository</a> </li> <li> <a href="mail-lists.html" title="Mailing Lists"> <i class="none"></i> Mailing Lists</a> </li> <li> <a href="issue-tracking.html" title="Issue Tracking"> <i class="none"></i> Issue Tracking</a> </li> <li> <a href="integration.html" title="Continuous Integration"> <i class="none"></i> Continuous Integration</a> </li> <li> <a href="plugins.html" title="Project Plugins"> <i class="none"></i> Project Plugins</a> </li> <li> <a href="license.html" title="Project License"> <i class="none"></i> Project License</a> </li> <li> <a href="dependency-management.html" title="Dependency Management"> <i class="none"></i> Dependency Management</a> </li> <li> <a href="team-list.html" title="Project Team"> <i class="none"></i> Project Team</a> </li> <li> <a href="project-summary.html" title="Project Summary"> <i class="none"></i> Project Summary</a> </li> <li class="active"> <a href="#"><i class="none"></i>Dependencies</a> </li> </ul> </li> <li> <a href="project-reports.html" title="Project Reports"> <i class="icon-chevron-right"></i> Project Reports</a> </li> </ul> <form id="search-form" action="http://www.google.com/search" method="get" > <input value="ericssonresearch.github.io/trap/trap-network-nio1/" name="sitesearch" type="hidden"/> <input class="search-query" name="q" id="query" type="text" /> </form> <script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=search-form"></script> <hr class="divider" /> <div id="poweredBy"> <div class="clear"></div> <div class="clear"></div> <div class="clear"></div> <a href="http://maven.apache.org/" title="Built by Maven" class="poweredBy"> <img class="builtBy" alt="Built by Maven" src="./images/logos/maven-feather.png" /> </a> </div> </div> </div> <div id="bodyColumn" class="span9" > <a name="Project_Dependencies"></a> <div class="section"> <h2>Project Dependencies<a name="Project_Dependencies"></a></h2><a name="Project_Dependencies_compile"></a> <div class="section"> <h3>compile<a name="compile"></a></h3> <p>The following is a list of compile dependencies for this project. These dependencies are required to compile and run the application:</p> <table border="0" class="table table-striped"> <tr class="a"> <th>GroupId</th> <th>ArtifactId</th> <th>Version</th> <th>Type</th> <th>License</th></tr> <tr class="b"> <td>com.ericsson.research.trap</td> <td><a class="externalLink" href="http://ericssonresearch.github.io/trap/trap-network/trap-network-nio/">trap-network-nio</a></td> <td>1.3</td> <td>jar</td> <td><a class="externalLink" href="http://opensource.org/licenses/BSD-3-Clause">BSD 3-clause</a></td></tr> <tr class="a"> <td>com.ericsson.research.trap</td> <td><a class="externalLink" href="http://ericssonresearch.github.io/trap/trap-utils-api/">trap-utils-api</a></td> <td>1.3</td> <td>jar</td> <td><a class="externalLink" href="http://opensource.org/licenses/BSD-3-Clause">BSD 3-clause</a></td></tr></table></div><a name="Project_Dependencies_test"></a> <div class="section"> <h3>test<a name="test"></a></h3> <p>The following is a list of test dependencies for this project. These dependencies are only required to compile and run unit tests for the application:</p> <table border="0" class="table table-striped"> <tr class="a"> <th>GroupId</th> <th>ArtifactId</th> <th>Version</th> <th>Type</th> <th>License</th></tr> <tr class="b"> <td>junit</td> <td><a class="externalLink" href="http://junit.org">junit</a></td> <td>4.10</td> <td>jar</td> <td><a class="externalLink" href="http://www.opensource.org/licenses/cpl1.0.txt">Common Public License Version 1.0</a></td></tr></table></div></div><a name="Project_Transitive_Dependencies"></a> <div class="section"> <h2>Project Transitive Dependencies<a name="Project_Transitive_Dependencies"></a></h2> <p>The following is a list of transitive dependencies for this project. Transitive dependencies are the dependencies of the project dependencies.</p><a name="Project_Transitive_Dependencies_test"></a> <div class="section"> <h3>test<a name="test"></a></h3> <p>The following is a list of test dependencies for this project. These dependencies are only required to compile and run unit tests for the application:</p> <table border="0" class="table table-striped"> <tr class="a"> <th>GroupId</th> <th>ArtifactId</th> <th>Version</th> <th>Type</th> <th>License</th></tr> <tr class="b"> <td>org.hamcrest</td> <td>hamcrest-core</td> <td>1.1</td> <td>jar</td> <td><a class="externalLink" href="http://www.opensource.org/licenses/bsd-license.php">BSD style</a></td></tr></table></div></div><a name="Project_Dependency_Graph"></a> <div class="section"> <h2>Project Dependency Graph<a name="Project_Dependency_Graph"></a></h2><script language="javascript" type="text/javascript"> function toggleDependencyDetail( divId, imgId ) { var div = document.getElementById( divId ); var img = document.getElementById( imgId ); if( div.style.display == '' ) { div.style.display = 'none'; img.src='./images/icon_info_sml.gif'; } else { div.style.display = ''; img.src='./images/close.gif'; } } </script> <a name="Dependency_Tree"></a> <div class="section"> <h3>Dependency Tree<a name="Dependency_Tree"></a></h3> <ul> <li>com.ericsson.research.trap:trap-network-nio1:jar:1.3 <img id="_img1" src="./images/icon_info_sml.gif" alt="Information" onclick="toggleDependencyDetail( '_dep0', '_img1' );" style="cursor: pointer;vertical-align:text-bottom;"></img><div id="_dep0" style="display:none"> <table border="0" class="table table-striped"> <tr class="a"> <th>TrAP Networking: Sockets using NIO1 (Legacy)</th></tr> <tr class="b"> <td> <p><b>Description: </b>java.nio managed sockets (TCP). Server and Client sockets.</p> <p><b>URL: </b><a class="externalLink" href="http://ericssonresearch.github.io/trap/trap-network-nio1/">http://ericssonresearch.github.io/trap/trap-network-nio1/</a></p> <p><b>Project License: </b><a class="externalLink" href="http://opensource.org/licenses/BSD-3-Clause">BSD 3-clause</a></p></td></tr></table></div> <ul> <li>junit:junit:jar:4.10 (test) <img id="_img3" src="./images/icon_info_sml.gif" alt="Information" onclick="toggleDependencyDetail( '_dep2', '_img3' );" style="cursor: pointer;vertical-align:text-bottom;"></img><div id="_dep2" style="display:none"> <table border="0" class="table table-striped"> <tr class="a"> <th>JUnit</th></tr> <tr class="b"> <td> <p><b>Description: </b>JUnit is a regression testing framework written by Erich Gamma and Kent Beck. It is used by the developer who implements unit tests in Java.</p> <p><b>URL: </b><a class="externalLink" href="http://junit.org">http://junit.org</a></p> <p><b>Project License: </b><a class="externalLink" href="http://www.opensource.org/licenses/cpl1.0.txt">Common Public License Version 1.0</a></p></td></tr></table></div> <ul> <li>org.hamcrest:hamcrest-core:jar:1.1 (test) <img id="_img5" src="./images/icon_info_sml.gif" alt="Information" onclick="toggleDependencyDetail( '_dep4', '_img5' );" style="cursor: pointer;vertical-align:text-bottom;"></img><div id="_dep4" style="display:none"> <table border="0" class="table table-striped"> <tr class="a"> <th>Hamcrest Core</th></tr> <tr class="b"> <td> <p><b>Description: </b>There is currently no description associated with this project.</p> <p><b>Project License: </b><a class="externalLink" href="http://www.opensource.org/licenses/bsd-license.php">BSD style</a></p></td></tr></table></div></li></ul></li> <li>com.ericsson.research.trap:trap-utils-api:jar:1.3 (compile) <img id="_img7" src="./images/icon_info_sml.gif" alt="Information" onclick="toggleDependencyDetail( '_dep6', '_img7' );" style="cursor: pointer;vertical-align:text-bottom;"></img><div id="_dep6" style="display:none"> <table border="0" class="table table-striped"> <tr class="a"> <th>TrAP Utils API</th></tr> <tr class="b"> <td> <p><b>Description: </b>Parent pom for the Transport Abstraction Package. This defines all properties for the children. The Transport Abstraction Package, or trap, provides an overlaying socket api that can be used across multiple underlying transports, while supporting reconnects, wifi/cellular handover, compression and multiplexing.</p> <p><b>URL: </b><a class="externalLink" href="http://ericssonresearch.github.io/trap/trap-utils-api/">http://ericssonresearch.github.io/trap/trap-utils-api/</a></p> <p><b>Project License: </b><a class="externalLink" href="http://opensource.org/licenses/BSD-3-Clause">BSD 3-clause</a></p></td></tr></table></div></li> <li>com.ericsson.research.trap:trap-network-nio:jar:1.3 (compile) <img id="_img9" src="./images/icon_info_sml.gif" alt="Information" onclick="toggleDependencyDetail( '_dep8', '_img9' );" style="cursor: pointer;vertical-align:text-bottom;"></img><div id="_dep8" style="display:none"> <table border="0" class="table table-striped"> <tr class="a"> <th>trap-network-nio</th></tr> <tr class="b"> <td> <p><b>Description: </b>Protocol implementations for non-blocking sockets and websockets.</p> <p><b>URL: </b><a class="externalLink" href="http://ericssonresearch.github.io/trap/trap-network/trap-network-nio/">http://ericssonresearch.github.io/trap/trap-network/trap-network-nio/</a></p> <p><b>Project License: </b><a class="externalLink" href="http://opensource.org/licenses/BSD-3-Clause">BSD 3-clause</a></p></td></tr></table></div></li></ul></li></ul></div></div><a name="Licenses"></a> <div class="section"> <h2>Licenses<a name="Licenses"></a></h2> <p><b>BSD 3-clause: </b>TrAP Networking: Sockets using NIO1 (Legacy), TrAP Utils API, trap-network-nio</p> <p><b>BSD style: </b>Hamcrest Core</p> <p><b>Common Public License Version 1.0: </b>JUnit</p></div><a name="Dependency_File_Details"></a> <div class="section"> <h2>Dependency File Details<a name="Dependency_File_Details"></a></h2> <table border="0" class="table table-striped"> <tr class="a"> <th>Filename</th> <th>Size</th> <th>Entries</th> <th>Classes</th> <th>Packages</th> <th>JDK Rev</th> <th>Debug</th></tr> <tr class="b"> <td>trap-network-nio-1.3.jar</td> <td>5.23 kB</td> <td>18</td> <td>6</td> <td>1</td> <td>1.6</td> <td>debug</td></tr> <tr class="a"> <td>trap-utils-api-1.3.jar</td> <td>45.97 kB</td> <td>48</td> <td>35</td> <td>2</td> <td>1.5</td> <td>debug</td></tr> <tr class="b"> <td>junit-4.10.jar</td> <td>247.23 kB</td> <td>290</td> <td>252</td> <td>31</td> <td>1.5</td> <td>debug</td></tr> <tr class="a"> <td>hamcrest-core-1.1.jar</td> <td>74.85 kB</td> <td>54</td> <td>21</td> <td>3</td> <td>1.5</td> <td>debug</td></tr> <tr class="b"> <th>Total</th> <th>Size</th> <th>Entries</th> <th>Classes</th> <th>Packages</th> <th>JDK Rev</th> <th>Debug</th></tr> <tr class="a"> <td>4</td> <td>373.28 kB</td> <td>410</td> <td>314</td> <td>37</td> <td>1.6</td> <td>4</td></tr> <tr class="b"> <td>compile: 2</td> <td>compile: 51.21 kB</td> <td>compile: 66</td> <td>compile: 41</td> <td>compile: 3</td> <td>-</td> <td>compile: 2</td></tr> <tr class="a"> <td>test: 2</td> <td>test: 322.07 kB</td> <td>test: 344</td> <td>test: 273</td> <td>test: 34</td> <td>-</td> <td>test: 2</td></tr></table></div><a name="Dependency_Repository_Locations"></a> <div class="section"> <h2>Dependency Repository Locations<a name="Dependency_Repository_Locations"></a></h2> <table border="0" class="table table-striped"> <tr class="a"> <th>Repo ID</th> <th>URL</th> <th>Release</th> <th>Snapshot</th> <th>Blacklisted</th></tr> <tr class="b"> <td>warp-releases</td> <td><a class="externalLink" href="http://cf.ericsson.net/nexus/content/repositories/warp-releases/">http://cf.ericsson.net/nexus/content/repositories/warp-releases/</a></td> <td>Yes</td> <td>Yes</td> <td>Yes</td></tr> <tr class="a"> <td>central</td> <td><a class="externalLink" href="http://repo.maven.apache.org/maven2">http://repo.maven.apache.org/maven2</a></td> <td>Yes</td> <td>-</td> <td>-</td></tr> <tr class="b"> <td>trap-snapshots</td> <td><a class="externalLink" href="https://oss.sonatype.com/content/repositories/snapshots">https://oss.sonatype.com/content/repositories/snapshots</a></td> <td>-</td> <td>Yes</td> <td>-</td></tr></table> <p>Repository locations for each of the Dependencies.</p> <table border="0" class="table table-striped"> <tr class="a"> <th>Artifact</th> <th>central</th> <th>airbourne-trap-snapshots</th></tr> <tr class="b"> <td>com.ericsson.research.trap:trap-network-nio:jar:1.3</td> <td><a class="externalLink" href="http://repo.maven.apache.org/maven2/com/ericsson/research/trap/trap-network-nio/1.3/trap-network-nio-1.3.jar"><img alt="Found at http://repo.maven.apache.org/maven2" src="images/icon_success_sml.gif" /></a></td> <td>-</td></tr> <tr class="a"> <td>com.ericsson.research.trap:trap-utils-api:jar:1.3</td> <td><a class="externalLink" href="http://repo.maven.apache.org/maven2/com/ericsson/research/trap/trap-utils-api/1.3/trap-utils-api-1.3.jar"><img alt="Found at http://repo.maven.apache.org/maven2" src="images/icon_success_sml.gif" /></a></td> <td>-</td></tr> <tr class="b"> <td>junit:junit:jar:4.10</td> <td><a class="externalLink" href="http://repo.maven.apache.org/maven2/junit/junit/4.10/junit-4.10.jar"><img alt="Found at http://repo.maven.apache.org/maven2" src="images/icon_success_sml.gif" /></a></td> <td>-</td></tr> <tr class="a"> <td>org.hamcrest:hamcrest-core:jar:1.1</td> <td><a class="externalLink" href="http://repo.maven.apache.org/maven2/org/hamcrest/hamcrest-core/1.1/hamcrest-core-1.1.jar"><img alt="Found at http://repo.maven.apache.org/maven2" src="images/icon_success_sml.gif" /></a></td> <td>-</td></tr> <tr class="b"> <th>Total</th> <th>central</th> <th>airbourne-trap-snapshots</th></tr> <tr class="a"> <td>4 (compile: 2, test: 2)</td> <td>4</td> <td>0</td></tr></table></div> </div> </div> </div> <hr/> <footer> <div class="container-fluid"> <div class="row span12">Copyright &copy; 2014 <a href="https://www.ericsson.com">Ericsson AB</a>. All Rights Reserved. </div> </div> </footer> </body> </html>
princeofdarkness76/trap
trap-network-nio1/dependencies.html
HTML
bsd-3-clause
21,173
<html> <body> <script src="typeshave.min.js"/></script> <script> typeshave = require("typeshave"); typeshave.verbose = 1; typesafe = require("typeshave").typesafe; var foo = typesafe({ foo: { type: "string" }, bar: { type: "integer" }, bes: { type: "boolean" } }, function(foo,bar,bes){ alert("ok data passed!"); }); foo( "flop",123, true ); </script> </body> </html>
coderofsalvation/typeshave.js
dist/index.html
HTML
bsd-3-clause
461
<?php namespace Phass\Entity; class Contact extends GlassModelAbstract { /** * @var string */ protected $_kind; /** * @var string */ protected $_source; /** * @var string */ protected $_id; /** * @var string */ protected $_displayName; /** * @var \ArrayObject */ protected $_imageUrls; /** * @var string */ protected $_type; /** * @var \ArrayObject */ protected $_acceptTypes; /** * @var string */ protected $_phoneNumber; /** * @var int */ protected $_priority; /** * @var \ArrayObject */ protected $_acceptCommands; /** * @var string */ protected $_speakableName; /** * @var \ArrayObject */ protected $_sharingFeatures; public function __construct() { $this->_imageUrls = new \ArrayObject(); $this->_acceptTypes = new \ArrayObject(); $this->_acceptCommands = new \ArrayObject(); $this->_sharingFeatures = new \ArrayObject(); } public function toArray() { return array( 'kind' => $this->getKind(), 'source' => $this->getSource(), 'id' => $this->getId(), 'displayName' => $this->getDisplayName(), 'type' => $this->getType(), 'phoneNumber' => $this->getPhoneNumber(), 'priority' => $this->getPriority(), 'speakableName' => $this->getSpeakableName(), 'imageUrls' => $this->getImageUrls()->getArrayCopy(), 'acceptTypes' => $this->getAcceptTypes()->getArrayCopy(), 'acceptCommands' => $this->getAcceptCommands()->getArrayCopy(), 'sharingFeatures' => $this->getSharingFeatures()->getArrayCopy() ); } public function fromJsonResult(array $result) { $this->setKind(isset($result['kind']) ? $result['kind'] : null) ->setSource(isset($result['source']) ? $result['source'] : null) ->setId(isset($result['id']) ? $result['id'] : null) ->setDisplayName(isset($result['displayName']) ? $result['displayName'] : null) ->setType(isset($result['type']) ? $result['type'] : null) ->setPhoneNumber(isset($result['phoneNumber']) ? $result['phoneNumber'] : null) ->setPriority(isset($result['priority']) ? (int)$result['priority'] : null) ->setSpeakableName(isset($result['speakableName']) ? $result['speakableName'] : null); if(isset($result['imageUrls']) && is_array($result['imageUrls'])) { $this->setImageUrls($result['imageUrls']); } if(isset($result['acceptTypes']) && is_array($result['acceptTypes'])) { $this->setAcceptTypes($result['acceptTypes']); } if(isset($result['acceptCommands']) && is_array($result['acceptCommands'])) { $this->setAcceptCommands($result['acceptCommands']); } if(isset($result['sharingFeatures']) && is_array($result['sharingFeatures'])) { $this->setSharingFeatures($result['sharingFeatures']); } return $this; } /** * @return the $_sharingFeatures */ public function getSharingFeatures() { return $this->_sharingFeatures; } /** * @param ArrayObject $_sharingFeatures * @return self */ public function setSharingFeatures(array $_sharingFeatures) { $this->_sharingFeatures = new \ArrayObject($_sharingFeatures); return $this; } /** * @return the $_kind */ public function getKind() { return $this->_kind; } /** * @return the $_source */ public function getSource() { return $this->_source; } /** * @return the $_id */ public function getId() { return $this->_id; } /** * @return the $_displayName */ public function getDisplayName() { return $this->_displayName; } /** * @return the $_imageUrls */ public function getImageUrls() { return $this->_imageUrls; } /** * @return the $_type */ public function getType() { return $this->_type; } /** * @return the $_acceptTypes */ public function getAcceptTypes() { return $this->_acceptTypes; } /** * @return the $_phoneNumber */ public function getPhoneNumber() { return $this->_phoneNumber; } /** * @return the $_priority */ public function getPriority() { return $this->_priority; } /** * @return the $_acceptCommands */ public function getAcceptCommands() { return $this->_acceptCommands; } /** * @return the $_speakableName */ public function getSpeakableName() { return $this->_speakableName; } /** * @param string $_kind * @return self */ public function setKind($_kind) { $this->_kind = $_kind; return $this; } /** * @param string $_source * @return self */ public function setSource($_source) { $this->_source = $_source; return $this; } /** * @param string $_id * @return self */ public function setId($_id) { $this->_id = $_id; return $this; } /** * @param string $_displayName * @return self */ public function setDisplayName($_displayName) { $this->_displayName = $_displayName; return $this; } /** * @param ArrayObject $_imageUrls * @return self */ public function setImageUrls(array $_imageUrls) { $this->_imageUrls = new \ArrayObject($_imageUrls); return $this; } /** * @param string $_type * @return self */ public function setType($_type) { $this->_type = $_type; return $this; } /** * @param ArrayObject $_acceptTypes * @return self */ public function setAcceptTypes(array $_acceptTypes) { $this->_acceptTypes = new \ArrayObject($_acceptTypes); return $this; } /** * @param string $_phoneNumber * @return self */ public function setPhoneNumber($_phoneNumber) { $this->_phoneNumber = $_phoneNumber; return $this; } /** * @param number $_priority * @return self */ public function setPriority($_priority) { $this->_priority = $_priority; return $this; } /** * @param ArrayObject $_acceptCommands * @return self */ public function setAcceptCommands(array $_acceptCommands) { $this->_acceptCommands = new \ArrayObject($_acceptCommands); return $this; } /** * @param string $_speakableName * @return self */ public function setSpeakableName($_speakableName) { $this->_speakableName = $_speakableName; return $this; } }
coogle/phass
src/Phass/Entity/Contact.php
PHP
bsd-3-clause
6,565
<?php namespace lukisongroup\purchasing\controllers; use Yii; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use yii\data\ArrayDataProvider; use yii\helpers\Json; use yii\web\Response; use yii\helpers\ArrayHelper; use kartik\mpdf\Pdf; use lukisongroup\purchasing\models\pr\Purchaseorder; use lukisongroup\purchasing\models\pr\PurchaseorderSearch; use lukisongroup\purchasing\models\pr\Purchasedetail; use lukisongroup\purchasing\models\pr\Podetail; use lukisongroup\purchasing\models\pr\DiscountValidation; use lukisongroup\purchasing\models\pr\PajakValidation; use lukisongroup\purchasing\models\pr\DeliveryValidation; use lukisongroup\purchasing\models\pr\EtdValidation; use lukisongroup\purchasing\models\pr\EtaValidation; use lukisongroup\purchasing\models\pr\SupplierValidation; use lukisongroup\purchasing\models\pr\ShippingValidation; use lukisongroup\purchasing\models\pr\BillingValidation; use lukisongroup\purchasing\models\pr\LoginForm; use lukisongroup\purchasing\models\pr\NewPoValidation; use lukisongroup\purchasing\models\ro\Requestorder; use lukisongroup\purchasing\models\ro\RequestorderSearch; use lukisongroup\purchasing\models\ro\Rodetail; use lukisongroup\purchasing\models\ro\RodetailSearch; use lukisongroup\purchasing\models\Statuspo; use lukisongroup\esm\models\Barang; use lukisongroup\master\models\Barangumum; class PurchaseOrderController extends Controller { public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], ], ], ]; } /* * Index Po | Purchaseorder| Purchasedetail * @author ptrnov <piter@lukison.com> * @since 1.2 */ public function actionIndex() { $searchModel = new PurchaseorderSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); $model = new Purchaseorder(); /*Model Validasi Generate Code*/ $poHeaderVal = new NewPoValidation(); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'model' => $model, 'poHeaderVal'=>$poHeaderVal, ]); } /* * View Po | Purchaseorder| Purchasedetail * @author ptrnov <piter@lukison.com> * @since 1.2 */ public function actionView($kd) { /* return $this->render('view', [ 'model' => Purchaseorder::find()->where(['KD_PO'=>$kd])->one(), ]); */ $poHeader = Purchaseorder::find()->where(['KD_PO'=>$kd])->one(); $poDetail = Purchasedetail::find()->where(['KD_PO'=>$kd])->all(); $dataProvider = new ArrayDataProvider([ 'key' => 'KD_PO', 'allModels'=>$poDetail, 'pagination' => [ 'pageSize' => 20, ], ]); return $this->render( 'view', [ 'poHeader' => $poHeader, 'poDetail' => $poDetail, //'detro' => $detro, //'employ' => $employ, //'dept' => $dept, 'dataProvider' => $dataProvider, ]); } /* * Create PO * PO Generate | PO Normal | PO Plus * ID_SUPPLIER=null| SHIPPING=Null | BILLING=Null | ETD=Null | ETA=Null | SUMMARY [DISCOUNT|TAX|DELEVERY] * GRID | EDITING =[HARGA|QTY|UNIT] -> VALIDATION HARGA | QTY [Tidak boleh lebih dari SQTY], (RO to PO ->HARGA = Manual Input), SO(SO to PO -> Harga=Harga Otomatis dari SO) * @author ptrnov <piter@lukison.com> * @since 1.2 */ public function actionCreate($kdpo) { $searchModel = new RequestorderSearch(); $dataProvider = $searchModel->caripo(Yii::$app->request->queryParams); $poHeader = Purchaseorder::find()->where(['KD_PO'=>$kdpo])->one(); $supplier = $poHeader->suplier; $bill = $poHeader->bill; $ship = $poHeader->ship; $employee= $poHeader->employe; $poDetail = Purchasedetail::find()->where(['KD_PO'=>$kdpo])->andWhere('STATUS <> 3')->all(); $poDetailProvider = new ArrayDataProvider([ 'key' => 'KD_PO', 'allModels'=>$poDetail, 'pagination' => [ 'pageSize' => 20, ], ]); return $this->render('create', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'poDetailProvider'=>$poDetailProvider, 'poHeader'=> $poHeader, 'supplier'=>$supplier, 'bill' => $bill, 'ship' => $ship, 'employee'=>$employee, ]); } /* * Create PO | Generate PO | * PO PLUS ['POA.'.date('ymdhis')] -> POA DENGAN LIMIT HARGA * PO Normal ['PO.'.date('ymdhis')] -> PO Dengan Persetujuan orderby | RequestOrder|SalesOrder * @author ptrnov <piter@lukison.com> * @since 1.2 */ public function actionSimpanpo() { $poHeaderVal = new NewPoValidation; if(Yii::$app->request->isAjax){ $poHeaderVal->load(Yii::$app->request->post()); return Json::encode(\yii\widgets\ActiveForm::validate($poHeaderVal)); }else{ if($poHeaderVal->load(Yii::$app->request->post())){ if ($poHeaderVal->generatepo_saved()){ $hsl = \Yii::$app->request->post(); //$kdPo =$poHeaderVal->PO_RSLT return $this->redirect(['create', 'kdpo'=>$poHeaderVal->PO_RSLT]); //echo "test"; } } } } public function actionDetail($kd_ro,$kdpo) { $roDetail = Rodetail::find()->where(['KD_RO'=>$kd_ro, 'STATUS'=>101])->all(); $roDetailProvider = new ArrayDataProvider([ 'key' => 'ID', 'allModels'=>$roDetail, 'pagination' => [ 'pageSize' => 20, ], ]); return $this->renderAjax('_detail', [ // ubah ini 'roDetail' => $roDetail, 'roDetailProvider'=>$roDetailProvider, 'kdpo' => $kdpo, 'kd_ro' => $kd_ro, ]); } /* * Action ChekBook Grid RO to PO | _detail * @author ptrnov <piter@lukison.com> * @since 1.2 * @categoty : AJAX */ public function actionCk() { if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; $request= Yii::$app->request; //$dataKeylist=$request->post('keylist'); //$dataKeyRslt=$request->post('keysRslt'); //$kdRo=$request->post('kdRo'); $dataKeySelect=$request->post('keysSelect'); $dataKdRo=$request->post('kdRo'); $dataKdBrg=$request->post('kdBrg'); //$valueCk=$request->post('value'); //$roDetail = Rodetail::findOne($id); //$roDetail->TMP_CK = 1;// valueCk;//$roDetail->TMP_CK==0 ? 1 :0; //$roDetail->save(); //print_r($dataKeySelect); //print_r($dataKdRo); //print_r(json_encode($dataKeySelect)); //$poDetail = Podetail::find()->where(['KD_PO'=>$kdpo, 'ID'=>$idpo])->one(); /* Before Action -> 0 */ $AryKdRo = ArrayHelper::map (Rodetail::find()->where(['KD_RO'=>$dataKdRo])->andWhere('STATUS=101')->all(),'ID','ID'); //print_r($AryKdRo); $foreaceAryKdRo=$AryKdRo!=0?$AryKdRo:'Array([0]=>"0")'; foreach ($foreaceAryKdRo as $keyRo){ $roDetailHapus = Rodetail::findOne($keyRo); $roDetailHapus->TMP_CK =0; $roDetailHapus->save(); } $res = array('status' => 'true'); /* An Action -> 0 */ //print_r($dataKeySelect); if ($dataKeySelect!=0){ //$foreaceGvRoToPo=$dataKeySelect!=0? $dataKeySelect:'Array([0]=>"0")'; foreach ($dataKeySelect as $idx){ $roDetail=Rodetail::find()->where(['KD_RO'=>$dataKdRo,'ID'=>$idx])->andWhere('STATUS=101')->one(); $poDetail=Purchasedetail::find()->where(['KD_RO'=>$dataKdRo,'KD_BARANG'=>$roDetail->KD_BARANG])->one(); if (!$poDetail){ //$roDetail = Rodetail::findOne($idx); $roDetail->TMP_CK =1; $roDetail->save(); $res = array('status' => true); /* tidak ada Data pada Purchasedetail |KD_RO&KD_BARANG */ }else{ $res = array('status' => false); /* sudah ada Data pada Purchasedetail |KD_RO&KD_BARANG */ } } }; //$res = array('status' => 't'); return $res; /* return Json::encode([ 'status' => '1', ]); */ /* return $res; return Json(new {success = true}); */ //return $a; /* return [ //'status' => 'false', 'message' => 'message', ]; */ } } public function actionSimpan() { $cons = \Yii::$app->db_esm; $tes = Yii::$app->request->post(); $kdpo = $tes['kdpo']; $kdro = $tes['kdro']; $status = ''; foreach ($tes['selection'] as $key => $isi) { $pp = explode('_',$isi); $rd = Rodetail::find()->where(['ID'=>$pp[1]])->one(); $ckpo = Purchasedetail::find()->where(['KD_BARANG'=> $rd->KD_BARANG, 'KD_PO'=>$kdpo, 'UNIT'=>$rd->UNIT])->andWhere('STATUS <> 3')->one(); if(count($ckpo) == 0){ $command = $cons->createCommand(); $command->insert('p0002', [ 'KD_PO'=> $kdpo, 'QTY'=> $rd->SQTY, 'UNIT'=> $rd->UNIT, 'STATUS'=> 0, 'KD_BARANG'=> $rd->KD_BARANG, ] )->execute(); $id = $cons->getLastInsertID(); $command->insert('p0021', [ 'KD_PO'=> $kdpo, 'KD_RO'=> $tes['kdro'], 'ID_DET_RO'=> $pp[1], 'ID_DET_PO'=> $id, 'QTY'=> $rd->SQTY, 'UNIT'=> $rd->UNIT, 'STATUS'=>1, ] )->execute(); } else { $dpo = Podetail::find()->where(['ID_DET_PO'=>$ckpo->ID, 'KD_RO'=>$kdro])->andWhere('STATUS <> 3')->one(); if(count($dpo) == 1){ $status .= '<p class="bg-danger" style="padding:15px;" >RO "<b>'.$kdro.'</b>" dengan kode barang " <b>'.$rd->KD_BARANG.'</b> " Sudah ada di dalam list.<br/> silahkan ubah jumlah Quantity barangnya.</p>'; } else { $command = $cons->createCommand(); $command->insert('p0021', [ 'KD_PO'=> $kdpo, 'KD_RO'=> $tes['kdro'], 'ID_DET_RO'=> $pp[1], 'ID_DET_PO'=> $ckpo->ID, 'QTY'=> $rd->SQTY, 'UNIT'=> $rd->UNIT, 'STATUS'=>1, ] )->execute(); $ttl = $rd->SQTY + $ckpo->QTY; $idpo = $ckpo->ID; $command->update('p0002', ['QTY'=>$ttl], "ID='$idpo'")->execute(); } } } \Yii::$app->getSession()->setFlash('error', $status); return $this->redirect(['create','kdpo'=>$kdpo]); } public function actionSpo($kdpo) { $cons = \Yii::$app->db_esm; $post = Yii::$app->request->post(); $ttl = count($post['qty']); $hsl = 0; $idpo = $post['idpo']; for($a=0; $a<=$ttl-1; $a++){ $qty = $post['sqty'][$a]; $ket = $post['ket'][$a]; $id = $post['id'][$a]; $hsl = $hsl + $qty; $command = $cons->createCommand(); $command->update('p0021', ['QTY'=>$qty, 'NOTE'=>$ket], "ID='$id'")->execute(); } $command->update('p0002', ['QTY'=>$hsl], "ID='$idpo'")->execute(); return $this->redirect(['create','kdpo'=>$kdpo]); } public function actionDelpo($idpo,$kdpo) { $podet = Podetail::find()->where(['KD_PO'=>$kdpo, 'ID'=>$idpo])->one(); $po = Purchasedetail::find()->where(['KD_PO'=>$kdpo, 'ID'=>$podet->ID_DET_PO])->one(); $sisa = $po->QTY - $podet->QTY; if($sisa == '0'){ \Yii::$app->db_esm->createCommand()->update('p0002', ['QTY'=>$sisa, 'STATUS'=>'3'], "ID='$po->ID'")->execute(); } else { \Yii::$app->db_esm->createCommand()->update('p0002', ['QTY'=>$sisa], "ID='$po->ID'")->execute(); } $podet->STATUS = '3'; $podet->save(); return $this->redirect(['create', 'kdpo'=>$kdpo]); } public function actionCreatepo() { $post = Yii::$app->request->post(); $coall = count($post['hargaBarang']); $kdpo = $post['kdpo']; for ($i=0; $i < $coall ; $i++) { $kdBrg = $post['kdBarang'][$i]; $harga = $post['hargaBarang'][$i]; $ckBrg = explode('.', $kdBrg); if($ckBrg[0] == 'BRG'){ $nmBrg = Barang::find('NM_BARANG')->where(['KD_BARANG'=>$kdBrg])->one(); $nmBrg->HARGA = $harga; $nmBrg->save(); } else if($ckBrg[0] == 'BRGU') { $nmBrg = Barangumum::find('NM_BARANG')->where(['KD_BARANG'=>$kdBrg])->one(); $nmBrg->HARGA = $harga; $nmBrg->save(); } $detpo = Purchasedetail::find('ID')->where(['KD_BARANG'=>$kdBrg, 'KD_PO'=>$kdpo])->one(); $cons = \Yii::$app->db_esm; $command = $cons->createCommand(); $command->update('p0002', ['HARGA'=>$harga], "ID='$detpo->ID'")->execute(); } $po = Purchaseorder::find()->where(['KD_PO'=>$kdpo])->one(); $po->STATUS = '101'; $po->PAJAK = $post['pajak']; $po->DISC = $post['disc']; $po->NOTE = $post['note']; $po->ETA = $post['eta']; $po->ETD = $post['etd']; $po->SHIPPING = $post['shipping']; $po->BILLING = $post['billing']; $po->DELIVERY_COST = $post['delvCost']; $po->save(); return $this->redirect([' ']); } public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->ID]); } else { return $this->render('update', [ 'model' => $model, ]); } } /* * ALAMAT Supplier Edit * $roHeader->KD_SUPPLIER | Ajax Request $request->post('kD_SUPPLIER'); * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionSupplierView($kdpo){ $poHeaderVal = new SupplierValidation; $poHeader= Purchaseorder::findOne($kdpo); return $this->renderAjax('_frmsupplier',[ 'poHeaderVal'=>$poHeaderVal, 'poHeader'=>$poHeader, ]); } public function actionSupplierSave() { $poHeaderVal = new SupplierValidation; if(Yii::$app->request->isAjax){ $poHeaderVal->load(Yii::$app->request->post()); return Json::encode(\yii\widgets\ActiveForm::validate($poHeaderVal)); }else{ if($poHeaderVal->load(Yii::$app->request->post())){ if ($poHeaderVal->supplier_saved()){ $hsl = \Yii::$app->request->post(); $kdPo = $hsl['SupplierValidation']['kD_PO']; return $this->redirect(['create', 'kdpo'=>$kdPo]); } } } } /* * ALAMAT Shipping Edit * $roHeader->SHIPPING | Ajax Request $request->post('sHIPPING'); * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionShippingView($kdpo){ $poHeaderVal = new ShippingValidation; $poHeader= Purchaseorder::findOne($kdpo); return $this->renderAjax('_frmshipping',[ 'poHeaderVal'=>$poHeaderVal, 'poHeader'=>$poHeader, ]); } public function actionShippingSave() { $poHeaderVal = new ShippingValidation; if(Yii::$app->request->isAjax){ $poHeaderVal->load(Yii::$app->request->post()); return Json::encode(\yii\widgets\ActiveForm::validate($poHeaderVal)); }else{ if($poHeaderVal->load(Yii::$app->request->post())){ if ($poHeaderVal->shipping_saved()){ $hsl = \Yii::$app->request->post(); $kdPo = $hsl['ShippingValidation']['kD_PO']; return $this->redirect(['create', 'kdpo'=>$kdPo]); } } } } /* * ALAMAT BILLING Edit * $roHeader->SHIPPING | Ajax Request $request->post('sHIPPING'); * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionBillingView($kdpo){ $poHeaderVal = new BillingValidation; $poHeader= Purchaseorder::findOne($kdpo); return $this->renderAjax('_frmbilling',[ 'poHeaderVal'=>$poHeaderVal, 'poHeader'=>$poHeader, ]); } public function actionBillingSave() { $poHeaderVal = new BillingValidation; if(Yii::$app->request->isAjax){ $poHeaderVal->load(Yii::$app->request->post()); return Json::encode(\yii\widgets\ActiveForm::validate($poHeaderVal)); }else{ if($poHeaderVal->load(Yii::$app->request->post())){ if ($poHeaderVal->billing_saved()){ $hsl = \Yii::$app->request->post(); $kdPo = $hsl['BillingValidation']['kD_PO']; return $this->redirect(['create', 'kdpo'=>$kdPo]); } } } } /* * Discount Edit * $roHeader->DISCOUNT | Ajax Request $request->post('disc'); * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionDiscountView($kdpo){ $poHeaderVal = new DiscountValidation; $poHeader= Purchaseorder::findOne($kdpo); return $this->renderAjax('_frmdiscount',[ 'poHeaderVal'=>$poHeaderVal, 'poHeader'=>$poHeader, ]); } public function actionDiscountSave() { $poHeaderVal = new DiscountValidation; if(Yii::$app->request->isAjax){ $poHeaderVal->load(Yii::$app->request->post()); return Json::encode(\yii\widgets\ActiveForm::validate($poHeaderVal)); }else{ if($poHeaderVal->load(Yii::$app->request->post())){ if ($poHeaderVal->discount_saved()){ $hsl = \Yii::$app->request->post(); $kdPo = $hsl['DiscountValidation']['kD_PO']; return $this->redirect(['create', 'kdpo'=>$kdPo]); } } } } /* * Pajak Edit * $roHeader->PAJAK | Ajax $request->post('tax'); * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionPajakView($kdpo){ $poHeaderVal = new PajakValidation; $poHeader= Purchaseorder::findOne($kdpo); return $this->renderAjax('_frmpajak',[ 'poHeaderVal'=>$poHeaderVal, 'poHeader'=>$poHeader, ]); } public function actionPajakSave() { $poHeaderVal = new PajakValidation; if(Yii::$app->request->isAjax){ $poHeaderVal->load(Yii::$app->request->post()); return Json::encode(\yii\widgets\ActiveForm::validate($poHeaderVal)); }else{ if($poHeaderVal->load(Yii::$app->request->post())){ if ($poHeaderVal->discount_saved()){ $hsl = \Yii::$app->request->post(); $kdPo = $hsl['PajakValidation']['kD_PO']; return $this->redirect(['create', 'kdpo'=>$kdPo]); } } } } /* * DELIVERY_COST Edit * $roHeader->DELIVERY_COST | Ajax $request->post('tax'); * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionDeliveryView($kdpo){ $poHeaderVal = new DeliveryValidation; $poHeader= Purchaseorder::findOne($kdpo); return $this->renderAjax('_frmdelivery',[ 'poHeaderVal'=>$poHeaderVal, 'poHeader'=>$poHeader, ]); } public function actionDeliverySave(){ $poHeaderVal = new DeliveryValidation; if(Yii::$app->request->isAjax){ $poHeaderVal->load(Yii::$app->request->post()); return Json::encode(\yii\widgets\ActiveForm::validate($poHeaderVal)); }else{ if($poHeaderVal->load(Yii::$app->request->post())){ if ($poHeaderVal->delevery_saved()){ $hsl = \Yii::$app->request->post(); $kdPo = $hsl['DeliveryValidation']['kD_PO']; return $this->redirect(['create', 'kdpo'=>$kdPo]); } } } } /* * ETD EDIT * $roHeader->ETD | Ajax $request->post('eTD'); * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionEtdView($kdpo){ $poHeaderVal = new EtdValidation; $poHeader= Purchaseorder::findOne($kdpo); return $this->renderAjax('_frmetd',[ 'poHeaderVal'=>$poHeaderVal, 'poHeader'=>$poHeader, ]); } public function actionEtdSave(){ $poHeaderVal = new EtdValidation; if(Yii::$app->request->isAjax){ $poHeaderVal->load(Yii::$app->request->post()); return Json::encode(\yii\widgets\ActiveForm::validate($poHeaderVal)); }else{ if($poHeaderVal->load(Yii::$app->request->post())){ if ($poHeaderVal->etd_saved()){ $hsl = \Yii::$app->request->post(); $kdPo = $hsl['EtdValidation']['kD_PO']; return $this->redirect(['create', 'kdpo'=>$kdPo]); }else{ $hsl = \Yii::$app->request->post(); $kdPo = $hsl['EtdValidation']['kD_PO']; return $this->redirect(['create', 'kdpo'=>$kdPo]); } } } } /* * ETA EDIT * $roHeader->ETA | Ajax $request->post('eTA'); * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionEtaView($kdpo){ $poHeaderVal = new EtaValidation; $poHeader= Purchaseorder::findOne($kdpo); return $this->renderAjax('_frmeta',[ 'poHeaderVal'=>$poHeaderVal, 'poHeader'=>$poHeader, ]); } public function actionEtaSave(){ $poHeaderVal = new EtaValidation; if(Yii::$app->request->isAjax){ $poHeaderVal->load(Yii::$app->request->post()); return Json::encode(\yii\widgets\ActiveForm::validate($poHeaderVal)); }else{ if($poHeaderVal->load(Yii::$app->request->post())){ if ($poHeaderVal->eta_saved()){ $hsl = \Yii::$app->request->post(); $kdPo = $hsl['EtaValidation']['kD_PO']; return $this->redirect(['create', 'kdpo'=>$kdPo]); } } } } /* * PO FIRST SIGNATURE |ApprovedView | ApprovedSave * $poHeader->STATUS =1 * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionApprovedView($kdpo){ $loginform = new LoginForm(); $poHeader = Purchaseorder::find()->where(['KD_PO' =>$kdpo])->one(); $employe = $poHeader->employe; return $this->renderAjax('login_signature', [ 'poHeader' => $poHeader, 'employe' => $employe, 'loginform' => $loginform, ]); } public function actionApprovedSave(){ $loginform = new LoginForm(); /*Ajax Load*/ if(Yii::$app->request->isAjax){ $loginform->load(Yii::$app->request->post()); return Json::encode(\yii\widgets\ActiveForm::validate($loginform)); }else{ /*Normal Load*/ if($loginform->load(Yii::$app->request->post())){ if ($loginform->loginform_saved()){ $hsl = \Yii::$app->request->post(); $kdpo = $hsl['LoginForm']['kdpo']; return $this->redirect(['create', 'kdpo'=>$kdpo]); } } } } /* * PDF | Purchaseorder| Purchasedetail * @author ptrnov <piter@lukison.com> * @since 1.2 */ public function actionCetakpdf($kdpo) { $poHeader = Purchaseorder::find()->where(['KD_PO'=>$kdpo])->one(); $poDetail = Purchasedetail::find()->where(['KD_PO'=>$kdpo])->all(); $dataProvider = new ArrayDataProvider([ 'key' => 'KD_PO', 'allModels'=>$poDetail, 'pagination' => [ 'pageSize' => 20, ], ]); $content = $this->renderPartial( 'pdf', [ 'poHeader' => $poHeader, //'roHeader' => $roHeader, //'detro' => $detro, //'employ' => $employ, //'dept' => $dept, 'dataProvider' => $dataProvider, ]); $pdf = new Pdf([ // set to use core fonts only 'mode' => Pdf::MODE_CORE, // A4 paper format 'format' => Pdf::FORMAT_A4, // portrait orientation 'orientation' => Pdf::ORIENT_PORTRAIT, // stream to browser inline 'destination' => Pdf::DEST_BROWSER, // your html content input 'content' => $content, // format content from your own css file if needed or use the // enhanced bootstrap css built by Krajee for mPDF formatting //D:\xampp\htdocs\advanced\lukisongroup\web\widget\pdf-asset 'cssFile' => '@lukisongroup/web/widget/pdf-asset/kv-mpdf-bootstrap.min.css', // any css to be embedded if required 'cssInline' => '.kv-heading-1{font-size:12px}', // set mPDF properties on the fly 'options' => ['title' => 'Form Request Order','subject'=>'ro'], // call mPDF methods on the fly 'methods' => [ 'SetHeader'=>['Copyright@LukisonGroup '.date("r")], 'SetFooter'=>['{PAGENO}'], ] ]); return $pdf->render(); /* $mpdf=new mPDF(); $mpdf->WriteHTML($this->renderPartial( 'pdf', [ 'model' => Purchaseorder::find()->where(['KD_PO'=>$kdpo])->one(), ])); $mpdf->Output(); exit; */ } public function actionConfirm($kdpo) { /* $hsl = Purchaseorder::find()->where(['KD_PO'=>$kdpo])->one(); if($hsl->APPROVE_BY == ''){ $hsl->APPROVE_BY = Yii::$app->user->identity->EMP_ID; $hsl->APPROVE_AT = date('Y-m-d H:i:s'); $hsl->STATUS = 102; $hsl->save(); return $this->redirect(['view','kd'=>$kdpo]); } else { return $this->redirect(['view','kd'=>$kdpo]); } */ } public function actionConfirmdir($kdpo) { /* $hsl = Purchaseorder::find()->where(['KD_PO'=>$kdpo])->one(); if($hsl->APPROVE_DIR == ''){ $hsl->APPROVE_DIR = Yii::$app->user->identity->EMP_ID; $hsl->TGL_APPROVE = date('Y-m-d H:i:s'); $hsl->STATUS = 1; $hsl->save(); return $this->redirect(['view','kd'=>$kdpo]); } else { return $this->redirect(['view','kd'=>$kdpo]); } */ } /** * Deletes an existing Purchaseorder model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param string $id * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the Purchaseorder model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param string $id * @return Purchaseorder the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Purchaseorder::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }
adem-team/advanced
lukisongroup/purchasing/controllers/0C_purchasing-update_ver 1.1.1/PurchaseOrderController.php
PHP
bsd-3-clause
26,299
module Phidgets # This class represents a PhidgetFrequencyCounter. class FrequencyCounter Klass = Phidgets::FFI::CPhidgetFrequencyCounter include Phidgets::Common # Collection of frequency counter inputs # @return [FrequencyCounterInputs] attr_reader :inputs attr_reader :attributes # The attributes of a PhidgetFrequencyCounter def attributes super.merge({ :inputs => inputs.size, }) end # Sets an count handler callback function. This is called when ticks are counted on an frequency counter input, or when the timeout expires # # @param [String] obj Object to pass to the callback function. This is optional. # @param [Proc] Block When the callback is executed, the device and object are yielded to this block. # @example # fc.on_count do |device, input, time, count, obj| # puts "Channel #{input.index}: #{count} pulses in #{time} microseconds" # end # As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. # @return [Boolean] returns true or raises an error def on_count(obj=nil, &block) @on_count_obj = obj @on_count = Proc.new { |device, obj_ptr, index, time, counts| yield self, @inputs[index], time, counts, object_for(obj_ptr) } Klass.set_OnCount_Handler(@handle, @on_count, pointer_for(obj)) end # This class represents a frequency counter input for a PhidgetFrequencyCounter. All the properties of a frequency counter input are stored and modified in this class. class FrequencyCounterInputs Klass = Phidgets::FFI::CPhidgetFrequencyCounter private def initialize(handle, index) @handle, @index = handle, index.to_i end public # @return [Integer] returns index of the frequency counter input, or raises an error. def index @index end # @return [Boolean] returns the enabled state of a frequency counter input, or raises an error. def enabled ptr = ::FFI::MemoryPointer.new(:int) Klass.getEnabled(@handle, @index, ptr) (ptr.get_int(0) == 0) ? false : true end # Sets the enabled state of a frequency counter input, or raises an error. # @param [Boolean] new_state new state # @return [Boolean] returns enabled state of a frequency counter input, or raises an error. def enabled=(new_state) tmp = new_state ? 1 : 0 Klass.setEnabled(@handle, @index, tmp) new_state end # @return [Phidgets::FFI::FrequencyCounterFilterTypes] returns the filter type of the frequency counter input, or raises an error. def filter_type ptr = ::FFI::MemoryPointer.new(:int) Klass.getFilter(@handle, @index, ptr) Phidgets::FFI::FrequencyCounterFilterTypes[ptr.get_int(0)] end # Sets the filter type of the frequency counter input, or raises an error. # @param [Phidgets::FFI::FrequencyCounterFilterTypes] new_filter new filter # @return [Phidgets::FFI::FrequencyCounterFilterTypes] returns the filter type of the frequency counter input, or raises an error. def filter_type=(new_filter) ptr = ::FFI::MemoryPointer.new(:int) Klass.setFilter(@handle, @index, Phidgets::FFI::FrequencyCounterFilterTypes[new_filter]) new_filter end # @return [Integer] returns the measured frequency of the frequency counter input, in Hz, or raises an error. def frequency ptr = ::FFI::MemoryPointer.new(:double) Klass.getFrequency(@handle, @index, ptr) ptr.get_double(0) end # @return [Integer] returns the timeout for the frequency counter input, in microseconds, or raises an error. def timeout ptr = ::FFI::MemoryPointer.new(:int) Klass.getTimeout(@handle, @index, ptr) ptr.get_int(0) end # Sets the timeout for the frequency counter input, in microseconds, or raises an error. # @param [Integer] new_timeout new timeout # @return [Integer] returns timeout of the frequency counter input, or raises an error. def timeout=(new_timeout) Klass.setTimeout(@handle, @index, new_timeout.to_i) new_timeout.to_i end # @return [Integer] returns the number of ticks counted since last reset, or raises an error. def total_count ptr = ::FFI::MemoryPointer.new(:long) Klass.getTotalCount(@handle, @index, ptr) ptr.get_long(0) end # @return [Integer] returns the total time since last reset, in microseconds, or raises an error. def total_time ptr = ::FFI::MemoryPointer.new(:long_long) Klass.getTotalTime(@handle, @index, ptr) ptr.get_long_long(0) end end #FrequencyCounterInputs private def load_device_attributes load_inputs end def load_inputs ptr = ::FFI::MemoryPointer.new(:int) Klass.getFrequencyInputCount(@handle, ptr) @inputs = [] ptr.get_int(0).times do |i| @inputs << FrequencyCounterInputs.new(@handle, i) end end def remove_specific_event_handlers Klass.set_OnCount_Handler(@handle, nil, nil) end end end
kreynolds/phidgets-ffi
lib/phidgets-ffi/frequency_counter.rb
Ruby
bsd-3-clause
5,068
{-# LANGUAGE OverloadedStrings #-} module Futhark.Compiler ( runPipelineOnProgram , runCompilerOnProgram , runPipelineOnSource , interpretAction' , FutharkConfig (..) , newFutharkConfig , dumpError ) where import Data.Monoid import Control.Monad import Control.Monad.IO.Class import Data.Maybe import System.Exit (exitWith, ExitCode(..)) import System.IO import qualified Data.Text as T import qualified Data.Text.IO as T import Prelude import Language.Futhark.Parser import Futhark.Internalise import Futhark.Pipeline import Futhark.Actions import qualified Language.Futhark as E import qualified Language.Futhark.TypeChecker as E import Futhark.MonadFreshNames import Futhark.Representation.AST import qualified Futhark.Representation.SOACS as I import qualified Futhark.TypeCheck as I data FutharkConfig = FutharkConfig { futharkVerbose :: Maybe (Maybe FilePath) } newFutharkConfig :: FutharkConfig newFutharkConfig = FutharkConfig { futharkVerbose = Nothing } dumpError :: FutharkConfig -> CompileError -> IO () dumpError config err = do T.hPutStrLn stderr $ errorDesc err case (errorData err, futharkVerbose config) of (s, Just outfile) -> maybe (T.hPutStr stderr) T.writeFile outfile $ s <> "\n" _ -> return () runCompilerOnProgram :: FutharkConfig -> Pipeline I.SOACS lore -> Action lore -> FilePath -> IO () runCompilerOnProgram config pipeline action file = do res <- runFutharkM compile $ isJust $ futharkVerbose config case res of Left err -> liftIO $ do dumpError config err exitWith $ ExitFailure 2 Right () -> return () where compile = do source <- liftIO $ T.readFile file prog <- runPipelineOnSource config pipeline file source when (isJust $ futharkVerbose config) $ liftIO $ hPutStrLn stderr $ "Running action " ++ actionName action actionProcedure action prog runPipelineOnProgram :: FutharkConfig -> Pipeline I.SOACS tolore -> FilePath -> FutharkM (Prog tolore) runPipelineOnProgram config pipeline file = do source <- liftIO $ T.readFile file runPipelineOnSource config pipeline file source runPipelineOnSource :: FutharkConfig -> Pipeline I.SOACS tolore -> FilePath -> T.Text -> FutharkM (Prog tolore) runPipelineOnSource config pipeline filename srccode = do parsed_prog <- parseSourceProgram filename srccode (tagged_ext_prog, namesrc) <- typeCheckSourceProgram parsed_prog putNameSource namesrc res <- internaliseProg tagged_ext_prog case res of Left err -> compileErrorS "During internalisation:" err Right int_prog -> do typeCheckInternalProgram int_prog runPasses pipeline pipeline_config int_prog where pipeline_config = PipelineConfig { pipelineVerbose = isJust $ futharkVerbose config , pipelineValidate = True } parseSourceProgram :: FilePath -> T.Text -> FutharkM E.UncheckedProg parseSourceProgram filename file_contents = do parsed <- liftIO $ parseFuthark filename file_contents case parsed of Left err -> compileError (T.pack $ show err) () Right prog -> return prog typeCheckSourceProgram :: E.UncheckedProg -> FutharkM (E.Prog, VNameSource) typeCheckSourceProgram prog = case E.checkProg prog of Left err -> compileError (T.pack $ show err) () Right prog' -> return prog' typeCheckInternalProgram :: I.Prog -> FutharkM () typeCheckInternalProgram prog = case I.checkProg prog of Left err -> compileError (T.pack $ "After internalisation:\n" ++ show err) prog Right () -> return () interpretAction' :: Action I.SOACS interpretAction' = interpretAction parseValues' where parseValues' :: FilePath -> T.Text -> Either ParseError [I.Value] parseValues' path s = fmap concat $ mapM internalise =<< parseValues path s internalise v = maybe (Left $ ParseError $ "Invalid input value: " ++ I.pretty v) Right $ internaliseValue v
mrakgr/futhark
src/Futhark/Compiler.hs
Haskell
bsd-3-clause
4,305
<?php declare(strict_types=1); /** * This file is part of the PHP_CompatInfoDB package. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Bartlett\CompatInfoDb\Tests\Reference\Extension\PhpBundle\Json; use Bartlett\CompatInfoDb\Tests\Reference\GenericTest; /** * Unit tests for PHP_CompatInfo_Db, json extension Reference * * @since Release 3.0.0RC1 of PHP_CompatInfo * @since Release 1.0.0alpha1 of PHP_CompatInfo_Db * @author Laurent Laville * @author Remi Collet */ class JsonExtensionTest extends GenericTest { /** * Sets up the shared fixture. * * @return void */ public static function setUpBeforeClass(): void { // New features of JSONC alternative extension self::$ignoredconstants = array( 'JSON_C_BUNDLED', 'JSON_C_VERSION', 'JSON_PARSER_NOTSTRICT', ); self::$ignoredclasses = array( 'JsonIncrementalParser', // @see https://github.com/symfony/polyfill-php73/blob/main/Resources/stubs/JsonException.php 'JsonException' ); parent::setUpBeforeClass(); } }
llaville/php-compatinfo-db
tests/Reference/Extension/PhpBundle/Json/JsonExtensionTest.php
PHP
bsd-3-clause
1,225
""" This module implements atom/bond/structure-wise descriptor calculated from pretrained megnet model """ import os from typing import Dict, Union import numpy as np from tensorflow.keras.models import Model from megnet.models import GraphModel, MEGNetModel from megnet.utils.typing import StructureOrMolecule DEFAULT_MODEL = os.path.join(os.path.dirname(__file__), "../../mvl_models/mp-2019.4.1/formation_energy.hdf5") class MEGNetDescriptor: """ MEGNet descriptors. This class takes a trained model and then compute the intermediate outputs as structure features """ def __init__(self, model_name: Union[str, GraphModel, MEGNetModel] = DEFAULT_MODEL, use_cache: bool = True): """ Args: model_name (str or MEGNetModel): trained model. If it is str, then only models in mvl_models are used. use_cache (bool): whether to use cache for structure graph calculations """ if isinstance(model_name, str): model = MEGNetModel.from_file(model_name) elif isinstance(model_name, GraphModel): model = model_name else: raise ValueError("model_name only support str or GraphModel object") layers = model.layers important_prefix = ["meg", "set", "concatenate"] all_names = [i.name for i in layers if any(i.name.startswith(j) for j in important_prefix)] if any(i.startswith("megnet") for i in all_names): self.version = "v2" else: self.version = "v1" valid_outputs = [i.output for i in layers if any(i.name.startswith(j) for j in important_prefix)] outputs = [] valid_names = [] for i, j in zip(all_names, valid_outputs): if isinstance(j, list): for k, l in enumerate(j): valid_names.append(i + f"_{k}") outputs.append(l) else: valid_names.append(i) outputs.append(j) full_model = Model(inputs=model.inputs, outputs=outputs) model.model = full_model self.model = model self.valid_names = valid_names self._cache: Dict[str, float] = {} self.use_cache = use_cache def _predict_structure(self, structure: StructureOrMolecule) -> np.ndarray: graph = self.model.graph_converter.convert(structure) inp = self.model.graph_converter.graph_to_input(graph) return self.model.predict(inp) def _predict_feature(self, structure: StructureOrMolecule) -> np.ndarray: if not self.use_cache: return self._predict_structure(structure) s = str(structure) if s in self._cache: return self._cache[s] result = self._predict_structure(structure) self._cache[s] = result return result def _get_features(self, structure: StructureOrMolecule, prefix: str, level: int, index: int = None) -> np.ndarray: name = prefix if level is not None: name = f"{prefix}_{level}" if index is not None: name += f"_{index}" if name not in self.valid_names: raise ValueError(f"{name} not in original megnet model") ind = self.valid_names.index(name) out_all = self._predict_feature(structure) return out_all[ind][0] def _get_updated_prefix_level(self, prefix: str, level: int): mapping = { "meg_net_layer": ["megnet", level - 1], "set2_set": ["set2set_atom" if level == 1 else "set2set_bond", None], "concatenate": ["concatenate", None], } if self.version == "v2": return mapping[prefix][0], mapping[prefix][1] # type: ignore return prefix, level def get_atom_features(self, structure: StructureOrMolecule, level: int = 3) -> np.ndarray: """ Get megnet atom features from structure Args: structure: pymatgen structure or molecule level: int, indicating the block number of megnet, starting from 1 Returns: nxm atomic feature matrix """ prefix, level = self._get_updated_prefix_level("meg_net_layer", level) return self._get_features(structure, prefix=prefix, level=level, index=0) def get_bond_features(self, structure: StructureOrMolecule, level: int = 3) -> np.ndarray: """ Get bond features at megnet block level Args: structure: pymatgen structure level: int Returns: n_bond x m bond feature matrix """ prefix, level = self._get_updated_prefix_level("meg_net_layer", level) return self._get_features(structure, prefix=prefix, level=level, index=1) def get_global_features(self, structure: StructureOrMolecule, level: int = 2) -> np.ndarray: """ Get state features at megnet block level Args: structure: pymatgen structure or molecule level: int Returns: 1 x m_g global feature vector """ prefix, level = self._get_updated_prefix_level("meg_net_layer", level) return self._get_features(structure, prefix=prefix, level=level, index=2) def get_set2set(self, structure: StructureOrMolecule, ftype: str = "atom") -> np.ndarray: """ Get set2set output as features Args: structure (StructureOrMolecule): pymatgen structure or molecule ftype (str): atom or bond Returns: feature matrix, each row is a vector for an atom or bond """ mapping = {"atom": 1, "bond": 2} prefix, level = self._get_updated_prefix_level("set2_set", level=mapping[ftype]) return self._get_features(structure, prefix=prefix, level=level) def get_structure_features(self, structure: StructureOrMolecule) -> np.ndarray: """ Get structure level feature vector Args: structure (StructureOrMolecule): pymatgen structure or molecule Returns: one feature vector for the structure """ prefix, level = self._get_updated_prefix_level("concatenate", level=1) return self._get_features(structure, prefix=prefix, level=level)
materialsvirtuallab/megnet
megnet/utils/descriptor.py
Python
bsd-3-clause
6,396
<?xml version="1.0" encoding="UTF-8"?> <CustomMetadata xmlns="http://soap.sforce.com/2006/04/metadata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <label>Prebuilt NPSP Report</label> <protected>true</protected> <values> <field>Description_Label__c</field> <value xsi:type="xsd:string">gseuChecklistItemPrebuiltNPSPReportDesc</value> </values> <values> <field>Extra_Info_Label__c</field> <value xsi:type="xsd:string">gsChecklistItemExtraTwoMinutesVideo</value> </values> <values> <field>GS_Checklist_Section__c</field> <value xsi:type="xsd:string">Your_Data</value> </values> <values> <field>Has_Link__c</field> <value xsi:type="xsd:boolean">true</value> </values> <values> <field>Image__c</field> <value xsi:type="xsd:string">Run_a_Prebuilt_NPSP_Report.svg</value> </values> <values> <field>Link_Label__c</field> <value xsi:type="xsd:string">gseuChecklistItemPrebuiltNPSPReportLinkLabel</value> </values> <values> <field>Link_URL__c</field> <value xsi:type="xsd:string">https://sforce.co/36UP0Oe</value> </values> <values> <field>Position__c</field> <value xsi:type="xsd:double">1.0</value> </values> <values> <field>Primary_Button_Label__c</field> <value xsi:type="xsd:string">gseuChecklistItemPrebuiltNPSPReportPriBtnLabel</value> </values> <values> <field>Primary_Button_Type__c</field> <value xsi:type="xsd:string">link</value> </values> <values> <field>Primary_Button_Value__c</field> <value xsi:type="xsd:string">https://bit.ly/2Le63lL</value> </values> <values> <field>Secondary_Button_Label__c</field> <value xsi:type="xsd:string">gseuChecklistItemPrebuiltNPSPReportSecBtnLabel</value> </values> <values> <field>Secondary_Button_Type__c</field> <value xsi:type="xsd:string">link</value> </values> <values> <field>Secondary_Button_Value__c</field> <value xsi:type="xsd:string">https://sforce.co/3oyVGYb</value> </values> <values> <field>Title_Label__c</field> <value xsi:type="xsd:string">gseuChecklistItemPrebuiltNPSPReportTitle</value> </values> </CustomMetadata>
SalesforceFoundation/Cumulus
src/customMetadata/GetStartedChecklistItem.Prebuilt_NPSP_Report.md
Markdown
bsd-3-clause
2,397
<?php use yii\helpers\Html; ?> <div class="clearfix"> <?php $i=0; foreach ($nodes as $node) : ?> <?php if($i!=0 && $i%3 == 0): ?> </div><div class="clearfix"> <?php endif; ?> <div class="col-lg-4"> <div class="thumbnail"> <?= HTML::a(Yii::$app->imageCache->thumb($node->image, 'post'), [ 'product/view', 'slug'=> $node->slug ]); ?> </div> <h5 class="grid-product-title"><?=HTML::a($node->title, [ 'product/view', 'slug' => $node->slug ]); ?> </h5> </div><!--One Item--> <?php $i++; endforeach; ?> </div> <div class="text-center"> <?=HTML::a(HTML::img('img/icon-xem-them.png'), ['category/view', 'slug' => $category_slug]); ?> </div>
nguyentuansieu/phutungoto
common/onecms/views/widget/front_product.php
PHP
bsd-3-clause
719
/* * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com> * 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 name of Redis 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. */ #include "redis.h" #include "cluster.h" #include "slowlog.h" #include "bio.h" #include "latency.h" #include <time.h> #include <signal.h> #include <sys/wait.h> #include <errno.h> #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <arpa/inet.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/uio.h> #include <limits.h> #include <float.h> #include <math.h> #include <sys/resource.h> #include <sys/utsname.h> #include <locale.h> /* Our shared "common" objects */ struct sharedObjectsStruct shared; /* Global vars that are actually used as constants. The following double * values are used for double on-disk serialization, and are initialized * at runtime to avoid strange compiler optimizations. */ double R_Zero, R_PosInf, R_NegInf, R_Nan; /*================================= Globals ================================= */ /* Global vars */ struct redisServer server; /* server global state */ /* Our command table. * * Every entry is composed of the following fields: * * name: a string representing the command name. * function: pointer to the C function implementing the command. * arity: number of arguments, it is possible to use -N to say >= N * sflags: command flags as string. See below for a table of flags. * flags: flags as bitmask. Computed by Redis using the 'sflags' field. * get_keys_proc: an optional function to get key arguments from a command. * This is only used when the following three fields are not * enough to specify what arguments are keys. * first_key_index: first argument that is a key * last_key_index: last argument that is a key * key_step: step to get all the keys from first to last argument. For instance * in MSET the step is two since arguments are key,val,key,val,... * microseconds: microseconds of total execution time for this command. * calls: total number of calls of this command. * * The flags, microseconds and calls fields are computed by Redis and should * always be set to zero. * * Command flags are expressed using strings where every character represents * a flag. Later the populateCommandTable() function will take care of * populating the real 'flags' field using this characters. * * This is the meaning of the flags: * * w: write command (may modify the key space). * r: read command (will never modify the key space). * m: may increase memory usage once called. Don't allow if out of memory. * a: admin command, like SAVE or SHUTDOWN. * p: Pub/Sub related command. * f: force replication of this command, regardless of server.dirty. * s: command not allowed in scripts. * R: random command. Command is not deterministic, that is, the same command * with the same arguments, with the same key space, may have different * results. For instance SPOP and RANDOMKEY are two random commands. * S: Sort command output array if called from script, so that the output * is deterministic. * l: Allow command while loading the database. * t: Allow command while a slave has stale data but is not allowed to * server this data. Normally no command is accepted in this condition * but just a few. * M: Do not automatically propagate the command on MONITOR. * k: Perform an implicit ASKING for this command, so the command will be * accepted in cluster mode if the slot is marked as 'importing'. * F: Fast command: O(1) or O(log(N)) command that should never delay * its execution as long as the kernel scheduler is giving us time. * Note that commands that may trigger a DEL as a side effect (like SET) * are not fast commands. */ struct redisCommand redisCommandTable[] = { {"get",getCommand,2,"rF",0,NULL,1,1,1,0,0}, {"set",setCommand,-3,"wm",0,NULL,1,1,1,0,0}, {"setnx",setnxCommand,3,"wmF",0,NULL,1,1,1,0,0}, {"setex",setexCommand,4,"wm",0,NULL,1,1,1,0,0}, {"psetex",psetexCommand,4,"wm",0,NULL,1,1,1,0,0}, {"append",appendCommand,3,"wm",0,NULL,1,1,1,0,0}, {"strlen",strlenCommand,2,"rF",0,NULL,1,1,1,0,0}, {"del",delCommand,-2,"w",0,NULL,1,-1,1,0,0}, {"exists",existsCommand,-2,"rF",0,NULL,1,-1,1,0,0}, {"setbit",setbitCommand,4,"wm",0,NULL,1,1,1,0,0}, {"getbit",getbitCommand,3,"rF",0,NULL,1,1,1,0,0}, {"setrange",setrangeCommand,4,"wm",0,NULL,1,1,1,0,0}, {"getrange",getrangeCommand,4,"r",0,NULL,1,1,1,0,0}, {"substr",getrangeCommand,4,"r",0,NULL,1,1,1,0,0}, {"incr",incrCommand,2,"wmF",0,NULL,1,1,1,0,0}, {"decr",decrCommand,2,"wmF",0,NULL,1,1,1,0,0}, {"mget",mgetCommand,-2,"r",0,NULL,1,-1,1,0,0}, {"rpush",rpushCommand,-3,"wmF",0,NULL,1,1,1,0,0}, {"lpush",lpushCommand,-3,"wmF",0,NULL,1,1,1,0,0}, {"rpushx",rpushxCommand,3,"wmF",0,NULL,1,1,1,0,0}, {"lpushx",lpushxCommand,3,"wmF",0,NULL,1,1,1,0,0}, {"linsert",linsertCommand,5,"wm",0,NULL,1,1,1,0,0}, {"rpop",rpopCommand,2,"wF",0,NULL,1,1,1,0,0}, {"lpop",lpopCommand,2,"wF",0,NULL,1,1,1,0,0}, {"brpop",brpopCommand,-3,"ws",0,NULL,1,1,1,0,0}, {"brpoplpush",brpoplpushCommand,4,"wms",0,NULL,1,2,1,0,0}, {"blpop",blpopCommand,-3,"ws",0,NULL,1,-2,1,0,0}, {"llen",llenCommand,2,"rF",0,NULL,1,1,1,0,0}, {"lindex",lindexCommand,3,"r",0,NULL,1,1,1,0,0}, {"lset",lsetCommand,4,"wm",0,NULL,1,1,1,0,0}, {"lrange",lrangeCommand,4,"r",0,NULL,1,1,1,0,0}, {"ltrim",ltrimCommand,4,"w",0,NULL,1,1,1,0,0}, {"lrem",lremCommand,4,"w",0,NULL,1,1,1,0,0}, {"rpoplpush",rpoplpushCommand,3,"wm",0,NULL,1,2,1,0,0}, {"sadd",saddCommand,-3,"wmF",0,NULL,1,1,1,0,0}, {"srem",sremCommand,-3,"wF",0,NULL,1,1,1,0,0}, {"smove",smoveCommand,4,"wF",0,NULL,1,2,1,0,0}, {"sismember",sismemberCommand,3,"rF",0,NULL,1,1,1,0,0}, {"scard",scardCommand,2,"rF",0,NULL,1,1,1,0,0}, {"spop",spopCommand,2,"wRsF",0,NULL,1,1,1,0,0}, {"srandmember",srandmemberCommand,-2,"rR",0,NULL,1,1,1,0,0}, {"sinter",sinterCommand,-2,"rS",0,NULL,1,-1,1,0,0}, {"sinterstore",sinterstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0}, {"sunion",sunionCommand,-2,"rS",0,NULL,1,-1,1,0,0}, {"sunionstore",sunionstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0}, {"sdiff",sdiffCommand,-2,"rS",0,NULL,1,-1,1,0,0}, {"sdiffstore",sdiffstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0}, {"smembers",sinterCommand,2,"rS",0,NULL,1,1,1,0,0}, {"sscan",sscanCommand,-3,"rR",0,NULL,1,1,1,0,0}, {"zadd",zaddCommand,-4,"wmF",0,NULL,1,1,1,0,0}, {"zincrby",zincrbyCommand,4,"wmF",0,NULL,1,1,1,0,0}, {"zrem",zremCommand,-3,"wF",0,NULL,1,1,1,0,0}, {"zremrangebyscore",zremrangebyscoreCommand,4,"w",0,NULL,1,1,1,0,0}, {"zremrangebyrank",zremrangebyrankCommand,4,"w",0,NULL,1,1,1,0,0}, {"zremrangebylex",zremrangebylexCommand,4,"w",0,NULL,1,1,1,0,0}, {"zunionstore",zunionstoreCommand,-4,"wm",0,zunionInterGetKeys,0,0,0,0,0}, {"zinterstore",zinterstoreCommand,-4,"wm",0,zunionInterGetKeys,0,0,0,0,0}, {"zrange",zrangeCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zrangebyscore",zrangebyscoreCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zrevrangebyscore",zrevrangebyscoreCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zrangebylex",zrangebylexCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zrevrangebylex",zrevrangebylexCommand,-4,"r",0,NULL,1,1,1,0,0}, // "key max_score_value min_score_value limit prefix1 [ prefix2 ... prefixN ]", { "zrangebylexin", // name: a string representing the command name. zrangebylexinCommand, // function: pointer to the C function implementing the command. -8, // arity: number of arguments, it is possible to use -N to say >= N "r", // sflags: command flags as string. See below for a table of flags. 0, // flags: flags as bitmask. Computed by Redis using the 'sflags' field. NULL, // get_keys_proc: an optional function to get key arguments from a command. This is only used when the following three fields are not enough to specify what arguments are keys. 1, // first_key_index: first argument that is a key 1, // last_key_index: last argument that is a key 1, // key_step: step to get all the keys from first to last argument. For instance in MSET the step is two since arguments are key,val,key,val,... 0, // microseconds: microseconds of total execution time for this command. 0 // calls: total number of calls of this command; The flags, microseconds and calls fields are computed by Redis and should always be set to zero. }, {"zcount",zcountCommand,4,"rF",0,NULL,1,1,1,0,0}, {"zlexcount",zlexcountCommand,4,"rF",0,NULL,1,1,1,0,0}, {"zrevrange",zrevrangeCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zcard",zcardCommand,2,"rF",0,NULL,1,1,1,0,0}, {"zscore",zscoreCommand,3,"rF",0,NULL,1,1,1,0,0}, {"zrank",zrankCommand,3,"rF",0,NULL,1,1,1,0,0}, {"zrevrank",zrevrankCommand,3,"rF",0,NULL,1,1,1,0,0}, {"zscan",zscanCommand,-3,"rR",0,NULL,1,1,1,0,0}, {"hset",hsetCommand,4,"wmF",0,NULL,1,1,1,0,0}, {"hsetnx",hsetnxCommand,4,"wmF",0,NULL,1,1,1,0,0}, {"hget",hgetCommand,3,"rF",0,NULL,1,1,1,0,0}, {"hmset",hmsetCommand,-4,"wm",0,NULL,1,1,1,0,0}, {"hmget",hmgetCommand,-3,"r",0,NULL,1,1,1,0,0}, {"hincrby",hincrbyCommand,4,"wmF",0,NULL,1,1,1,0,0}, {"hincrbyfloat",hincrbyfloatCommand,4,"wmF",0,NULL,1,1,1,0,0}, {"hdel",hdelCommand,-3,"wF",0,NULL,1,1,1,0,0}, {"hlen",hlenCommand,2,"rF",0,NULL,1,1,1,0,0}, {"hkeys",hkeysCommand,2,"rS",0,NULL,1,1,1,0,0}, {"hvals",hvalsCommand,2,"rS",0,NULL,1,1,1,0,0}, {"hgetall",hgetallCommand,2,"r",0,NULL,1,1,1,0,0}, {"hexists",hexistsCommand,3,"rF",0,NULL,1,1,1,0,0}, {"hscan",hscanCommand,-3,"rR",0,NULL,1,1,1,0,0}, {"incrby",incrbyCommand,3,"wmF",0,NULL,1,1,1,0,0}, {"decrby",decrbyCommand,3,"wmF",0,NULL,1,1,1,0,0}, {"incrbyfloat",incrbyfloatCommand,3,"wmF",0,NULL,1,1,1,0,0}, {"getset",getsetCommand,3,"wm",0,NULL,1,1,1,0,0}, {"mset",msetCommand,-3,"wm",0,NULL,1,-1,2,0,0}, {"msetnx",msetnxCommand,-3,"wm",0,NULL,1,-1,2,0,0}, {"randomkey",randomkeyCommand,1,"rR",0,NULL,0,0,0,0,0}, {"select",selectCommand,2,"rlF",0,NULL,0,0,0,0,0}, {"move",moveCommand,3,"wF",0,NULL,1,1,1,0,0}, {"rename",renameCommand,3,"w",0,NULL,1,2,1,0,0}, {"renamenx",renamenxCommand,3,"wF",0,NULL,1,2,1,0,0}, {"expire",expireCommand,3,"wF",0,NULL,1,1,1,0,0}, {"expireat",expireatCommand,3,"wF",0,NULL,1,1,1,0,0}, {"pexpire",pexpireCommand,3,"wF",0,NULL,1,1,1,0,0}, {"pexpireat",pexpireatCommand,3,"wF",0,NULL,1,1,1,0,0}, {"keys",keysCommand,2,"rS",0,NULL,0,0,0,0,0}, {"scan",scanCommand,-2,"rR",0,NULL,0,0,0,0,0}, {"dbsize",dbsizeCommand,1,"rF",0,NULL,0,0,0,0,0}, {"auth",authCommand,2,"rsltF",0,NULL,0,0,0,0,0}, {"ping",pingCommand,-1,"rtF",0,NULL,0,0,0,0,0}, {"echo",echoCommand,2,"rF",0,NULL,0,0,0,0,0}, {"save",saveCommand,1,"ars",0,NULL,0,0,0,0,0}, {"bgsave",bgsaveCommand,1,"ar",0,NULL,0,0,0,0,0}, {"bgrewriteaof",bgrewriteaofCommand,1,"ar",0,NULL,0,0,0,0,0}, {"shutdown",shutdownCommand,-1,"arlt",0,NULL,0,0,0,0,0}, {"lastsave",lastsaveCommand,1,"rRF",0,NULL,0,0,0,0,0}, {"type",typeCommand,2,"rF",0,NULL,1,1,1,0,0}, {"multi",multiCommand,1,"rsF",0,NULL,0,0,0,0,0}, {"exec",execCommand,1,"sM",0,NULL,0,0,0,0,0}, {"discard",discardCommand,1,"rsF",0,NULL,0,0,0,0,0}, {"sync",syncCommand,1,"ars",0,NULL,0,0,0,0,0}, {"psync",syncCommand,3,"ars",0,NULL,0,0,0,0,0}, {"replconf",replconfCommand,-1,"arslt",0,NULL,0,0,0,0,0}, {"flushdb",flushdbCommand,1,"w",0,NULL,0,0,0,0,0}, {"flushall",flushallCommand,1,"w",0,NULL,0,0,0,0,0}, {"sort",sortCommand,-2,"wm",0,sortGetKeys,1,1,1,0,0}, {"info",infoCommand,-1,"rlt",0,NULL,0,0,0,0,0}, {"monitor",monitorCommand,1,"ars",0,NULL,0,0,0,0,0}, {"ttl",ttlCommand,2,"rF",0,NULL,1,1,1,0,0}, {"pttl",pttlCommand,2,"rF",0,NULL,1,1,1,0,0}, {"persist",persistCommand,2,"wF",0,NULL,1,1,1,0,0}, {"slaveof",slaveofCommand,3,"ast",0,NULL,0,0,0,0,0}, {"role",roleCommand,1,"lst",0,NULL,0,0,0,0,0}, {"debug",debugCommand,-2,"as",0,NULL,0,0,0,0,0}, {"config",configCommand,-2,"art",0,NULL,0,0,0,0,0}, {"subscribe",subscribeCommand,-2,"rpslt",0,NULL,0,0,0,0,0}, {"unsubscribe",unsubscribeCommand,-1,"rpslt",0,NULL,0,0,0,0,0}, {"psubscribe",psubscribeCommand,-2,"rpslt",0,NULL,0,0,0,0,0}, {"punsubscribe",punsubscribeCommand,-1,"rpslt",0,NULL,0,0,0,0,0}, {"publish",publishCommand,3,"pltrF",0,NULL,0,0,0,0,0}, {"pubsub",pubsubCommand,-2,"pltrR",0,NULL,0,0,0,0,0}, {"watch",watchCommand,-2,"rsF",0,NULL,1,-1,1,0,0}, {"unwatch",unwatchCommand,1,"rsF",0,NULL,0,0,0,0,0}, {"cluster",clusterCommand,-2,"ar",0,NULL,0,0,0,0,0}, {"restore",restoreCommand,-4,"wm",0,NULL,1,1,1,0,0}, {"restore-asking",restoreCommand,-4,"wmk",0,NULL,1,1,1,0,0}, {"migrate",migrateCommand,-6,"w",0,migrateGetKeys,0,0,0,0,0}, {"asking",askingCommand,1,"r",0,NULL,0,0,0,0,0}, {"readonly",readonlyCommand,1,"rF",0,NULL,0,0,0,0,0}, {"readwrite",readwriteCommand,1,"rF",0,NULL,0,0,0,0,0}, {"dump",dumpCommand,2,"r",0,NULL,1,1,1,0,0}, {"object",objectCommand,3,"r",0,NULL,2,2,2,0,0}, {"client",clientCommand,-2,"rs",0,NULL,0,0,0,0,0}, {"eval",evalCommand,-3,"s",0,evalGetKeys,0,0,0,0,0}, {"evalsha",evalShaCommand,-3,"s",0,evalGetKeys,0,0,0,0,0}, {"slowlog",slowlogCommand,-2,"r",0,NULL,0,0,0,0,0}, {"script",scriptCommand,-2,"rs",0,NULL,0,0,0,0,0}, {"time",timeCommand,1,"rRF",0,NULL,0,0,0,0,0}, {"bitop",bitopCommand,-4,"wm",0,NULL,2,-1,1,0,0}, {"bitcount",bitcountCommand,-2,"r",0,NULL,1,1,1,0,0}, {"bitpos",bitposCommand,-3,"r",0,NULL,1,1,1,0,0}, {"wait",waitCommand,3,"rs",0,NULL,0,0,0,0,0}, {"command",commandCommand,0,"rlt",0,NULL,0,0,0,0,0}, {"pfselftest",pfselftestCommand,1,"r",0,NULL,0,0,0,0,0}, {"pfadd",pfaddCommand,-2,"wmF",0,NULL,1,1,1,0,0}, {"pfcount",pfcountCommand,-2,"r",0,NULL,1,-1,1,0,0}, {"pfmerge",pfmergeCommand,-2,"wm",0,NULL,1,-1,1,0,0}, {"pfdebug",pfdebugCommand,-3,"w",0,NULL,0,0,0,0,0}, {"latency",latencyCommand,-2,"arslt",0,NULL,0,0,0,0,0} }; struct evictionPoolEntry *evictionPoolAlloc(void); /*============================ Utility functions ============================ */ /* Low level logging. To use only for very big messages, otherwise * redisLog() is to prefer. */ void redisLogRaw(int level, const char *msg) { const int syslogLevelMap[] = { LOG_DEBUG, LOG_INFO, LOG_NOTICE, LOG_WARNING }; const char *c = ".-*#"; FILE *fp; char buf[64]; int rawmode = (level & REDIS_LOG_RAW); int log_to_stdout = server.logfile[0] == '\0'; level &= 0xff; /* clear flags */ if (level < server.verbosity) return; fp = log_to_stdout ? stdout : fopen(server.logfile,"a"); if (!fp) return; if (rawmode) { fprintf(fp,"%s",msg); } else { int off; struct timeval tv; int role_char; pid_t pid = getpid(); gettimeofday(&tv,NULL); off = strftime(buf,sizeof(buf),"%d %b %H:%M:%S.",localtime(&tv.tv_sec)); snprintf(buf+off,sizeof(buf)-off,"%03d",(int)tv.tv_usec/1000); if (server.sentinel_mode) { role_char = 'X'; /* Sentinel. */ } else if (pid != server.pid) { role_char = 'C'; /* RDB / AOF writing child. */ } else { role_char = (server.masterhost ? 'S':'M'); /* Slave or Master. */ } fprintf(fp,"%d:%c %s %c %s\n", (int)getpid(),role_char, buf,c[level],msg); } fflush(fp); if (!log_to_stdout) fclose(fp); if (server.syslog_enabled) syslog(syslogLevelMap[level], "%s", msg); } /* Like redisLogRaw() but with printf-alike support. This is the function that * is used across the code. The raw version is only used in order to dump * the INFO output on crash. */ void redisLog(int level, const char *fmt, ...) { va_list ap; char msg[REDIS_MAX_LOGMSG_LEN]; if ((level&0xff) < server.verbosity) return; va_start(ap, fmt); vsnprintf(msg, sizeof(msg), fmt, ap); va_end(ap); redisLogRaw(level,msg); } /* Log a fixed message without printf-alike capabilities, in a way that is * safe to call from a signal handler. * * We actually use this only for signals that are not fatal from the point * of view of Redis. Signals that are going to kill the server anyway and * where we need printf-alike features are served by redisLog(). */ void redisLogFromHandler(int level, const char *msg) { int fd; int log_to_stdout = server.logfile[0] == '\0'; char buf[64]; if ((level&0xff) < server.verbosity || (log_to_stdout && server.daemonize)) return; fd = log_to_stdout ? STDOUT_FILENO : open(server.logfile, O_APPEND|O_CREAT|O_WRONLY, 0644); if (fd == -1) return; ll2string(buf,sizeof(buf),getpid()); if (write(fd,buf,strlen(buf)) == -1) goto err; if (write(fd,":signal-handler (",17) == -1) goto err; ll2string(buf,sizeof(buf),time(NULL)); if (write(fd,buf,strlen(buf)) == -1) goto err; if (write(fd,") ",2) == -1) goto err; if (write(fd,msg,strlen(msg)) == -1) goto err; if (write(fd,"\n",1) == -1) goto err; err: if (!log_to_stdout) close(fd); } /* Return the UNIX time in microseconds */ long long ustime(void) { struct timeval tv; long long ust; gettimeofday(&tv, NULL); ust = ((long long)tv.tv_sec)*1000000; ust += tv.tv_usec; return ust; } /* Return the UNIX time in milliseconds */ long long mstime(void) { return ustime()/1000; } /* After an RDB dump or AOF rewrite we exit from children using _exit() instead of * exit(), because the latter may interact with the same file objects used by * the parent process. However if we are testing the coverage normal exit() is * used in order to obtain the right coverage information. */ void exitFromChild(int retcode) { #ifdef COVERAGE_TEST exit(retcode); #else _exit(retcode); #endif } /*====================== Hash table type implementation ==================== */ /* This is a hash table type that uses the SDS dynamic strings library as * keys and redis objects as values (objects can hold SDS strings, * lists, sets). */ void dictVanillaFree(void *privdata, void *val) { DICT_NOTUSED(privdata); zfree(val); } void dictListDestructor(void *privdata, void *val) { DICT_NOTUSED(privdata); listRelease((list*)val); } int dictSdsKeyCompare(void *privdata, const void *key1, const void *key2) { int l1,l2; DICT_NOTUSED(privdata); l1 = sdslen((sds)key1); l2 = sdslen((sds)key2); if (l1 != l2) return 0; return memcmp(key1, key2, l1) == 0; } /* A case insensitive version used for the command lookup table and other * places where case insensitive non binary-safe comparison is needed. */ int dictSdsKeyCaseCompare(void *privdata, const void *key1, const void *key2) { DICT_NOTUSED(privdata); return strcasecmp(key1, key2) == 0; } void dictRedisObjectDestructor(void *privdata, void *val) { DICT_NOTUSED(privdata); if (val == NULL) return; /* Values of swapped out keys as set to NULL */ decrRefCount(val); } void dictSdsDestructor(void *privdata, void *val) { DICT_NOTUSED(privdata); sdsfree(val); } int dictObjKeyCompare(void *privdata, const void *key1, const void *key2) { const robj *o1 = key1, *o2 = key2; return dictSdsKeyCompare(privdata,o1->ptr,o2->ptr); } unsigned int dictObjHash(const void *key) { const robj *o = key; return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); } unsigned int dictSdsHash(const void *key) { return dictGenHashFunction((unsigned char*)key, sdslen((char*)key)); } unsigned int dictSdsCaseHash(const void *key) { return dictGenCaseHashFunction((unsigned char*)key, sdslen((char*)key)); } int dictEncObjKeyCompare(void *privdata, const void *key1, const void *key2) { robj *o1 = (robj*) key1, *o2 = (robj*) key2; int cmp; if (o1->encoding == REDIS_ENCODING_INT && o2->encoding == REDIS_ENCODING_INT) return o1->ptr == o2->ptr; o1 = getDecodedObject(o1); o2 = getDecodedObject(o2); cmp = dictSdsKeyCompare(privdata,o1->ptr,o2->ptr); decrRefCount(o1); decrRefCount(o2); return cmp; } unsigned int dictEncObjHash(const void *key) { robj *o = (robj*) key; if (sdsEncodedObject(o)) { return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); } else { if (o->encoding == REDIS_ENCODING_INT) { char buf[32]; int len; len = ll2string(buf,32,(long)o->ptr); return dictGenHashFunction((unsigned char*)buf, len); } else { unsigned int hash; o = getDecodedObject(o); hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); decrRefCount(o); return hash; } } } /* Sets type hash table */ dictType setDictType = { dictEncObjHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictEncObjKeyCompare, /* key compare */ dictRedisObjectDestructor, /* key destructor */ NULL /* val destructor */ }; /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */ dictType zsetDictType = { dictEncObjHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictEncObjKeyCompare, /* key compare */ dictRedisObjectDestructor, /* key destructor */ NULL /* val destructor */ }; /* Db->dict, keys are sds strings, vals are Redis objects. */ dictType dbDictType = { dictSdsHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCompare, /* key compare */ dictSdsDestructor, /* key destructor */ dictRedisObjectDestructor /* val destructor */ }; /* server.lua_scripts sha (as sds string) -> scripts (as robj) cache. */ dictType shaScriptObjectDictType = { dictSdsCaseHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCaseCompare, /* key compare */ dictSdsDestructor, /* key destructor */ dictRedisObjectDestructor /* val destructor */ }; /* Db->expires */ dictType keyptrDictType = { dictSdsHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCompare, /* key compare */ NULL, /* key destructor */ NULL /* val destructor */ }; /* Command table. sds string -> command struct pointer. */ dictType commandTableDictType = { dictSdsCaseHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCaseCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; /* Hash type hash table (note that small hashes are represented with ziplists) */ dictType hashDictType = { dictEncObjHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictEncObjKeyCompare, /* key compare */ dictRedisObjectDestructor, /* key destructor */ dictRedisObjectDestructor /* val destructor */ }; /* Keylist hash table type has unencoded redis objects as keys and * lists as values. It's used for blocking operations (BLPOP) and to * map swapped keys to a list of clients waiting for this keys to be loaded. */ dictType keylistDictType = { dictObjHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictObjKeyCompare, /* key compare */ dictRedisObjectDestructor, /* key destructor */ dictListDestructor /* val destructor */ }; /* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to * clusterNode structures. */ dictType clusterNodesDictType = { dictSdsHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; /* Cluster re-addition blacklist. This maps node IDs to the time * we can re-add this node. The goal is to avoid readding a removed * node for some time. */ dictType clusterNodesBlackListDictType = { dictSdsCaseHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCaseCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; /* Migrate cache dict type. */ dictType migrateCacheDictType = { dictSdsHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; /* Replication cached script dict (server.repl_scriptcache_dict). * Keys are sds SHA1 strings, while values are not used at all in the current * implementation. */ dictType replScriptCacheDictType = { dictSdsCaseHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCaseCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; int htNeedsResize(dict *dict) { long long size, used; size = dictSlots(dict); used = dictSize(dict); return (size && used && size > DICT_HT_INITIAL_SIZE && (used*100/size < REDIS_HT_MINFILL)); } /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL * we resize the hash table to save memory */ void tryResizeHashTables(int dbid) { if (htNeedsResize(server.db[dbid].dict)) dictResize(server.db[dbid].dict); if (htNeedsResize(server.db[dbid].expires)) dictResize(server.db[dbid].expires); } /* Our hash table implementation performs rehashing incrementally while * we write/read from the hash table. Still if the server is idle, the hash * table will use two tables for a long time. So we try to use 1 millisecond * of CPU time at every call of this function to perform some rehahsing. * * The function returns 1 if some rehashing was performed, otherwise 0 * is returned. */ int incrementallyRehash(int dbid) { /* Keys dictionary */ if (dictIsRehashing(server.db[dbid].dict)) { dictRehashMilliseconds(server.db[dbid].dict,1); return 1; /* already used our millisecond for this loop... */ } /* Expires */ if (dictIsRehashing(server.db[dbid].expires)) { dictRehashMilliseconds(server.db[dbid].expires,1); return 1; /* already used our millisecond for this loop... */ } return 0; } /* This function is called once a background process of some kind terminates, * as we want to avoid resizing the hash tables when there is a child in order * to play well with copy-on-write (otherwise when a resize happens lots of * memory pages are copied). The goal of this function is to update the ability * for dict.c to resize the hash tables accordingly to the fact we have o not * running childs. */ void updateDictResizePolicy(void) { if (server.rdb_child_pid == -1 && server.aof_child_pid == -1) dictEnableResize(); else dictDisableResize(); } /* ======================= Cron: called every 100 ms ======================== */ /* Helper function for the activeExpireCycle() function. * This function will try to expire the key that is stored in the hash table * entry 'de' of the 'expires' hash table of a Redis database. * * If the key is found to be expired, it is removed from the database and * 1 is returned. Otherwise no operation is performed and 0 is returned. * * When a key is expired, server.stat_expiredkeys is incremented. * * The parameter 'now' is the current time in milliseconds as is passed * to the function to avoid too many gettimeofday() syscalls. */ int activeExpireCycleTryExpire(redisDb *db, dictEntry *de, long long now) { long long t = dictGetSignedIntegerVal(de); if (now > t) { sds key = dictGetKey(de); robj *keyobj = createStringObject(key,sdslen(key)); propagateExpire(db,keyobj); dbDelete(db,keyobj); notifyKeyspaceEvent(REDIS_NOTIFY_EXPIRED, "expired",keyobj,db->id); decrRefCount(keyobj); server.stat_expiredkeys++; return 1; } else { return 0; } } /* Try to expire a few timed out keys. The algorithm used is adaptive and * will use few CPU cycles if there are few expiring keys, otherwise * it will get more aggressive to avoid that too much memory is used by * keys that can be removed from the keyspace. * * No more than REDIS_DBCRON_DBS_PER_CALL databases are tested at every * iteration. * * This kind of call is used when Redis detects that timelimit_exit is * true, so there is more work to do, and we do it more incrementally from * the beforeSleep() function of the event loop. * * Expire cycle type: * * If type is ACTIVE_EXPIRE_CYCLE_FAST the function will try to run a * "fast" expire cycle that takes no longer than EXPIRE_FAST_CYCLE_DURATION * microseconds, and is not repeated again before the same amount of time. * * If type is ACTIVE_EXPIRE_CYCLE_SLOW, that normal expire cycle is * executed, where the time limit is a percentage of the REDIS_HZ period * as specified by the REDIS_EXPIRELOOKUPS_TIME_PERC define. */ void activeExpireCycle(int type) { /* This function has some global state in order to continue the work * incrementally across calls. */ static unsigned int current_db = 0; /* Last DB tested. */ static int timelimit_exit = 0; /* Time limit hit in previous call? */ static long long last_fast_cycle = 0; /* When last fast cycle ran. */ int j, iteration = 0; int dbs_per_call = REDIS_DBCRON_DBS_PER_CALL; long long start = ustime(), timelimit; if (type == ACTIVE_EXPIRE_CYCLE_FAST) { /* Don't start a fast cycle if the previous cycle did not exited * for time limt. Also don't repeat a fast cycle for the same period * as the fast cycle total duration itself. */ if (!timelimit_exit) return; if (start < last_fast_cycle + ACTIVE_EXPIRE_CYCLE_FAST_DURATION*2) return; last_fast_cycle = start; } /* We usually should test REDIS_DBCRON_DBS_PER_CALL per iteration, with * two exceptions: * * 1) Don't test more DBs than we have. * 2) If last time we hit the time limit, we want to scan all DBs * in this iteration, as there is work to do in some DB and we don't want * expired keys to use memory for too much time. */ if (dbs_per_call > server.dbnum || timelimit_exit) dbs_per_call = server.dbnum; /* We can use at max ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC percentage of CPU time * per iteration. Since this function gets called with a frequency of * server.hz times per second, the following is the max amount of * microseconds we can spend in this function. */ timelimit = 1000000*ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC/server.hz/100; timelimit_exit = 0; if (timelimit <= 0) timelimit = 1; if (type == ACTIVE_EXPIRE_CYCLE_FAST) timelimit = ACTIVE_EXPIRE_CYCLE_FAST_DURATION; /* in microseconds. */ for (j = 0; j < dbs_per_call; j++) { int expired; redisDb *db = server.db+(current_db % server.dbnum); /* Increment the DB now so we are sure if we run out of time * in the current DB we'll restart from the next. This allows to * distribute the time evenly across DBs. */ current_db++; /* Continue to expire if at the end of the cycle more than 25% * of the keys were expired. */ do { unsigned long num, slots; long long now, ttl_sum; int ttl_samples; /* If there is nothing to expire try next DB ASAP. */ if ((num = dictSize(db->expires)) == 0) { db->avg_ttl = 0; break; } slots = dictSlots(db->expires); now = mstime(); /* When there are less than 1% filled slots getting random * keys is expensive, so stop here waiting for better times... * The dictionary will be resized asap. */ if (num && slots > DICT_HT_INITIAL_SIZE && (num*100/slots < 1)) break; /* The main collection cycle. Sample random keys among keys * with an expire set, checking for expired ones. */ expired = 0; ttl_sum = 0; ttl_samples = 0; if (num > ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP) num = ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP; while (num--) { dictEntry *de; long long ttl; if ((de = dictGetRandomKey(db->expires)) == NULL) break; ttl = dictGetSignedIntegerVal(de)-now; if (activeExpireCycleTryExpire(db,de,now)) expired++; if (ttl < 0) ttl = 0; ttl_sum += ttl; ttl_samples++; } /* Update the average TTL stats for this database. */ if (ttl_samples) { long long avg_ttl = ttl_sum/ttl_samples; if (db->avg_ttl == 0) db->avg_ttl = avg_ttl; /* Smooth the value averaging with the previous one. */ db->avg_ttl = (db->avg_ttl+avg_ttl)/2; } /* We can't block forever here even if there are many keys to * expire. So after a given amount of milliseconds return to the * caller waiting for the other active expire cycle. */ iteration++; if ((iteration & 0xf) == 0) { /* check once every 16 iterations. */ long long elapsed = ustime()-start; latencyAddSampleIfNeeded("expire-cycle",elapsed/1000); if (elapsed > timelimit) timelimit_exit = 1; } if (timelimit_exit) return; /* We don't repeat the cycle if there are less than 25% of keys * found expired in the current DB. */ } while (expired > ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP/4); } } unsigned int getLRUClock(void) { return (mstime()/REDIS_LRU_CLOCK_RESOLUTION) & REDIS_LRU_CLOCK_MAX; } /* Add a sample to the operations per second array of samples. */ void trackInstantaneousMetric(int metric, long long current_reading) { long long t = mstime() - server.inst_metric[metric].last_sample_time; long long ops = current_reading - server.inst_metric[metric].last_sample_count; long long ops_sec; ops_sec = t > 0 ? (ops*1000/t) : 0; server.inst_metric[metric].samples[server.inst_metric[metric].idx] = ops_sec; server.inst_metric[metric].idx++; server.inst_metric[metric].idx %= REDIS_METRIC_SAMPLES; server.inst_metric[metric].last_sample_time = mstime(); server.inst_metric[metric].last_sample_count = current_reading; } /* Return the mean of all the samples. */ long long getInstantaneousMetric(int metric) { int j; long long sum = 0; for (j = 0; j < REDIS_METRIC_SAMPLES; j++) sum += server.inst_metric[metric].samples[j]; return sum / REDIS_METRIC_SAMPLES; } /* Check for timeouts. Returns non-zero if the client was terminated. * The function gets the current time in milliseconds as argument since * it gets called multiple times in a loop, so calling gettimeofday() for * each iteration would be costly without any actual gain. */ int clientsCronHandleTimeout(redisClient *c, mstime_t now_ms) { time_t now = now_ms/1000; if (server.maxidletime && !(c->flags & REDIS_SLAVE) && /* no timeout for slaves */ !(c->flags & REDIS_MASTER) && /* no timeout for masters */ !(c->flags & REDIS_BLOCKED) && /* no timeout for BLPOP */ !(c->flags & REDIS_PUBSUB) && /* no timeout for Pub/Sub clients */ (now - c->lastinteraction > server.maxidletime)) { redisLog(REDIS_VERBOSE,"Closing idle client"); freeClient(c); return 1; } else if (c->flags & REDIS_BLOCKED) { /* Blocked OPS timeout is handled with milliseconds resolution. * However note that the actual resolution is limited by * server.hz. */ if (c->bpop.timeout != 0 && c->bpop.timeout < now_ms) { /* Handle blocking operation specific timeout. */ replyToBlockedClientTimedOut(c); unblockClient(c); } else if (server.cluster_enabled) { /* Cluster: handle unblock & redirect of clients blocked * into keys no longer served by this server. */ if (clusterRedirectBlockedClientIfNeeded(c)) unblockClient(c); } } return 0; } /* The client query buffer is an sds.c string that can end with a lot of * free space not used, this function reclaims space if needed. * * The function always returns 0 as it never terminates the client. */ int clientsCronResizeQueryBuffer(redisClient *c) { size_t querybuf_size = sdsAllocSize(c->querybuf); time_t idletime = server.unixtime - c->lastinteraction; /* There are two conditions to resize the query buffer: * 1) Query buffer is > BIG_ARG and too big for latest peak. * 2) Client is inactive and the buffer is bigger than 1k. */ if (((querybuf_size > REDIS_MBULK_BIG_ARG) && (querybuf_size/(c->querybuf_peak+1)) > 2) || (querybuf_size > 1024 && idletime > 2)) { /* Only resize the query buffer if it is actually wasting space. */ if (sdsavail(c->querybuf) > 1024) { c->querybuf = sdsRemoveFreeSpace(c->querybuf); } } /* Reset the peak again to capture the peak memory usage in the next * cycle. */ c->querybuf_peak = 0; return 0; } #define CLIENTS_CRON_MIN_ITERATIONS 5 void clientsCron(void) { /* Make sure to process at least numclients/server.hz of clients * per call. Since this function is called server.hz times per second * we are sure that in the worst case we process all the clients in 1 * second. */ int numclients = listLength(server.clients); int iterations = numclients/server.hz; mstime_t now = mstime(); /* Process at least a few clients while we are at it, even if we need * to process less than CLIENTS_CRON_MIN_ITERATIONS to meet our contract * of processing each client once per second. */ if (iterations < CLIENTS_CRON_MIN_ITERATIONS) iterations = (numclients < CLIENTS_CRON_MIN_ITERATIONS) ? numclients : CLIENTS_CRON_MIN_ITERATIONS; while(listLength(server.clients) && iterations--) { redisClient *c; listNode *head; /* Rotate the list, take the current head, process. * This way if the client must be removed from the list it's the * first element and we don't incur into O(N) computation. */ listRotate(server.clients); head = listFirst(server.clients); c = listNodeValue(head); /* The following functions do different service checks on the client. * The protocol is that they return non-zero if the client was * terminated. */ if (clientsCronHandleTimeout(c,now)) continue; if (clientsCronResizeQueryBuffer(c)) continue; } } /* This function handles 'background' operations we are required to do * incrementally in Redis databases, such as active key expiring, resizing, * rehashing. */ void databasesCron(void) { /* Expire keys by random sampling. Not required for slaves * as master will synthesize DELs for us. */ if (server.active_expire_enabled && server.masterhost == NULL) activeExpireCycle(ACTIVE_EXPIRE_CYCLE_SLOW); /* Perform hash tables rehashing if needed, but only if there are no * other processes saving the DB on disk. Otherwise rehashing is bad * as will cause a lot of copy-on-write of memory pages. */ if (server.rdb_child_pid == -1 && server.aof_child_pid == -1) { /* We use global counters so if we stop the computation at a given * DB we'll be able to start from the successive in the next * cron loop iteration. */ static unsigned int resize_db = 0; static unsigned int rehash_db = 0; int dbs_per_call = REDIS_DBCRON_DBS_PER_CALL; int j; /* Don't test more DBs than we have. */ if (dbs_per_call > server.dbnum) dbs_per_call = server.dbnum; /* Resize */ for (j = 0; j < dbs_per_call; j++) { tryResizeHashTables(resize_db % server.dbnum); resize_db++; } /* Rehash */ if (server.activerehashing) { for (j = 0; j < dbs_per_call; j++) { int work_done = incrementallyRehash(rehash_db % server.dbnum); rehash_db++; if (work_done) { /* If the function did some work, stop here, we'll do * more at the next cron loop. */ break; } } } } } /* We take a cached value of the unix time in the global state because with * virtual memory and aging there is to store the current time in objects at * every object access, and accuracy is not needed. To access a global var is * a lot faster than calling time(NULL) */ void updateCachedTime(void) { server.unixtime = time(NULL); server.mstime = mstime(); } /* This is our timer interrupt, called server.hz times per second. * Here is where we do a number of things that need to be done asynchronously. * For instance: * * - Active expired keys collection (it is also performed in a lazy way on * lookup). * - Software watchdog. * - Update some statistic. * - Incremental rehashing of the DBs hash tables. * - Triggering BGSAVE / AOF rewrite, and handling of terminated children. * - Clients timeout of different kinds. * - Replication reconnection. * - Many more... * * Everything directly called here will be called server.hz times per second, * so in order to throttle execution of things we want to do less frequently * a macro is used: run_with_period(milliseconds) { .... } */ int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) { int j; REDIS_NOTUSED(eventLoop); REDIS_NOTUSED(id); REDIS_NOTUSED(clientData); /* Software watchdog: deliver the SIGALRM that will reach the signal * handler if we don't return here fast enough. */ if (server.watchdog_period) watchdogScheduleSignal(server.watchdog_period); /* Update the time cache. */ updateCachedTime(); run_with_period(100) { trackInstantaneousMetric(REDIS_METRIC_COMMAND,server.stat_numcommands); trackInstantaneousMetric(REDIS_METRIC_NET_INPUT, server.stat_net_input_bytes); trackInstantaneousMetric(REDIS_METRIC_NET_OUTPUT, server.stat_net_output_bytes); } /* We have just REDIS_LRU_BITS bits per object for LRU information. * So we use an (eventually wrapping) LRU clock. * * Note that even if the counter wraps it's not a big problem, * everything will still work but some object will appear younger * to Redis. However for this to happen a given object should never be * touched for all the time needed to the counter to wrap, which is * not likely. * * Note that you can change the resolution altering the * REDIS_LRU_CLOCK_RESOLUTION define. */ server.lruclock = getLRUClock(); /* Record the max memory used since the server was started. */ if (zmalloc_used_memory() > server.stat_peak_memory) server.stat_peak_memory = zmalloc_used_memory(); /* Sample the RSS here since this is a relatively slow call. */ server.resident_set_size = zmalloc_get_rss(); /* We received a SIGTERM, shutting down here in a safe way, as it is * not ok doing so inside the signal handler. */ if (server.shutdown_asap) { if (prepareForShutdown(0) == REDIS_OK) exit(0); redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information"); server.shutdown_asap = 0; } /* Show some info about non-empty databases */ run_with_period(5000) { for (j = 0; j < server.dbnum; j++) { long long size, used, vkeys; size = dictSlots(server.db[j].dict); used = dictSize(server.db[j].dict); vkeys = dictSize(server.db[j].expires); if (used || vkeys) { redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size); /* dictPrintStats(server.dict); */ } } } /* Show information about connected clients */ if (!server.sentinel_mode) { run_with_period(5000) { redisLog(REDIS_VERBOSE, "%lu clients connected (%lu slaves), %zu bytes in use", listLength(server.clients)-listLength(server.slaves), listLength(server.slaves), zmalloc_used_memory()); } } /* We need to do a few operations on clients asynchronously. */ clientsCron(); /* Handle background operations on Redis databases. */ databasesCron(); /* Start a scheduled AOF rewrite if this was requested by the user while * a BGSAVE was in progress. */ if (server.rdb_child_pid == -1 && server.aof_child_pid == -1 && server.aof_rewrite_scheduled) { rewriteAppendOnlyFileBackground(); } /* Check if a background saving or AOF rewrite in progress terminated. */ if (server.rdb_child_pid != -1 || server.aof_child_pid != -1) { int statloc; pid_t pid; if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) { int exitcode = WEXITSTATUS(statloc); int bysignal = 0; if (WIFSIGNALED(statloc)) bysignal = WTERMSIG(statloc); if (pid == -1) { redisLog(LOG_WARNING,"wait3() returned an error: %s. " "rdb_child_pid = %d, aof_child_pid = %d", strerror(errno), (int) server.rdb_child_pid, (int) server.aof_child_pid); } else if (pid == server.rdb_child_pid) { backgroundSaveDoneHandler(exitcode,bysignal); } else if (pid == server.aof_child_pid) { backgroundRewriteDoneHandler(exitcode,bysignal); } else { redisLog(REDIS_WARNING, "Warning, detected child with unmatched pid: %ld", (long)pid); } updateDictResizePolicy(); } } else { /* If there is not a background saving/rewrite in progress check if * we have to save/rewrite now */ for (j = 0; j < server.saveparamslen; j++) { struct saveparam *sp = server.saveparams+j; /* Save if we reached the given amount of changes, * the given amount of seconds, and if the latest bgsave was * successful or if, in case of an error, at least * REDIS_BGSAVE_RETRY_DELAY seconds already elapsed. */ if (server.dirty >= sp->changes && server.unixtime-server.lastsave > sp->seconds && (server.unixtime-server.lastbgsave_try > REDIS_BGSAVE_RETRY_DELAY || server.lastbgsave_status == REDIS_OK)) { redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...", sp->changes, (int)sp->seconds); rdbSaveBackground(server.rdb_filename); break; } } /* Trigger an AOF rewrite if needed */ if (server.rdb_child_pid == -1 && server.aof_child_pid == -1 && server.aof_rewrite_perc && server.aof_current_size > server.aof_rewrite_min_size) { long long base = server.aof_rewrite_base_size ? server.aof_rewrite_base_size : 1; long long growth = (server.aof_current_size*100/base) - 100; if (growth >= server.aof_rewrite_perc) { redisLog(REDIS_NOTICE,"Starting automatic rewriting of AOF on %lld%% growth",growth); rewriteAppendOnlyFileBackground(); } } } /* AOF postponed flush: Try at every cron cycle if the slow fsync * completed. */ if (server.aof_flush_postponed_start) flushAppendOnlyFile(0); /* AOF write errors: in this case we have a buffer to flush as well and * clear the AOF error in case of success to make the DB writable again, * however to try every second is enough in case of 'hz' is set to * an higher frequency. */ run_with_period(1000) { if (server.aof_last_write_status == REDIS_ERR) flushAppendOnlyFile(0); } /* Close clients that need to be closed asynchronous */ freeClientsInAsyncFreeQueue(); /* Clear the paused clients flag if needed. */ clientsArePaused(); /* Don't check return value, just use the side effect. */ /* Replication cron function -- used to reconnect to master and * to detect transfer failures. */ run_with_period(1000) replicationCron(); /* Run the Redis Cluster cron. */ run_with_period(100) { if (server.cluster_enabled) clusterCron(); } /* Run the Sentinel timer if we are in sentinel mode. */ run_with_period(100) { if (server.sentinel_mode) sentinelTimer(); } /* Cleanup expired MIGRATE cached sockets. */ run_with_period(1000) { migrateCloseTimedoutSockets(); } server.cronloops++; return 1000/server.hz; } /* This function gets called every time Redis is entering the * main loop of the event driven library, that is, before to sleep * for ready file descriptors. */ void beforeSleep(struct aeEventLoop *eventLoop) { REDIS_NOTUSED(eventLoop); /* Call the Redis Cluster before sleep function. Note that this function * may change the state of Redis Cluster (from ok to fail or vice versa), * so it's a good idea to call it before serving the unblocked clients * later in this function. */ if (server.cluster_enabled) clusterBeforeSleep(); /* Run a fast expire cycle (the called function will return * ASAP if a fast cycle is not needed). */ if (server.active_expire_enabled && server.masterhost == NULL) activeExpireCycle(ACTIVE_EXPIRE_CYCLE_FAST); /* Send all the slaves an ACK request if at least one client blocked * during the previous event loop iteration. */ if (server.get_ack_from_slaves) { robj *argv[3]; argv[0] = createStringObject("REPLCONF",8); argv[1] = createStringObject("GETACK",6); argv[2] = createStringObject("*",1); /* Not used argument. */ replicationFeedSlaves(server.slaves, server.slaveseldb, argv, 3); decrRefCount(argv[0]); decrRefCount(argv[1]); decrRefCount(argv[2]); server.get_ack_from_slaves = 0; } /* Unblock all the clients blocked for synchronous replication * in WAIT. */ if (listLength(server.clients_waiting_acks)) processClientsWaitingReplicas(); /* Try to process pending commands for clients that were just unblocked. */ if (listLength(server.unblocked_clients)) processUnblockedClients(); /* Write the AOF buffer on disk */ flushAppendOnlyFile(0); } /* =========================== Server initialization ======================== */ void createSharedObjects(void) { int j; shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n")); shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n")); shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n")); shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n")); shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n")); shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n")); shared.cnegone = createObject(REDIS_STRING,sdsnew(":-1\r\n")); shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n")); shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n")); shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n")); shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n")); shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n")); shared.emptyscan = createObject(REDIS_STRING,sdsnew("*2\r\n$1\r\n0\r\n*0\r\n")); shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew( "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n")); shared.nokeyerr = createObject(REDIS_STRING,sdsnew( "-ERR no such key\r\n")); shared.syntaxerr = createObject(REDIS_STRING,sdsnew( "-ERR syntax error\r\n")); shared.sameobjecterr = createObject(REDIS_STRING,sdsnew( "-ERR source and destination objects are the same\r\n")); shared.outofrangeerr = createObject(REDIS_STRING,sdsnew( "-ERR index out of range\r\n")); shared.noscripterr = createObject(REDIS_STRING,sdsnew( "-NOSCRIPT No matching script. Please use EVAL.\r\n")); shared.loadingerr = createObject(REDIS_STRING,sdsnew( "-LOADING Redis is loading the dataset in memory\r\n")); shared.slowscripterr = createObject(REDIS_STRING,sdsnew( "-BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.\r\n")); shared.masterdownerr = createObject(REDIS_STRING,sdsnew( "-MASTERDOWN Link with MASTER is down and slave-serve-stale-data is set to 'no'.\r\n")); shared.bgsaveerr = createObject(REDIS_STRING,sdsnew( "-MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error.\r\n")); shared.roslaveerr = createObject(REDIS_STRING,sdsnew( "-READONLY You can't write against a read only slave.\r\n")); shared.noautherr = createObject(REDIS_STRING,sdsnew( "-NOAUTH Authentication required.\r\n")); shared.oomerr = createObject(REDIS_STRING,sdsnew( "-OOM command not allowed when used memory > 'maxmemory'.\r\n")); shared.execaborterr = createObject(REDIS_STRING,sdsnew( "-EXECABORT Transaction discarded because of previous errors.\r\n")); shared.noreplicaserr = createObject(REDIS_STRING,sdsnew( "-NOREPLICAS Not enough good slaves to write.\r\n")); shared.busykeyerr = createObject(REDIS_STRING,sdsnew( "-BUSYKEY Target key name already exists.\r\n")); shared.space = createObject(REDIS_STRING,sdsnew(" ")); shared.colon = createObject(REDIS_STRING,sdsnew(":")); shared.plus = createObject(REDIS_STRING,sdsnew("+")); for (j = 0; j < REDIS_SHARED_SELECT_CMDS; j++) { char dictid_str[64]; int dictid_len; dictid_len = ll2string(dictid_str,sizeof(dictid_str),j); shared.select[j] = createObject(REDIS_STRING, sdscatprintf(sdsempty(), "*2\r\n$6\r\nSELECT\r\n$%d\r\n%s\r\n", dictid_len, dictid_str)); } shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13); shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14); shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15); shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18); shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17); shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19); shared.del = createStringObject("DEL",3); shared.rpop = createStringObject("RPOP",4); shared.lpop = createStringObject("LPOP",4); shared.lpush = createStringObject("LPUSH",5); for (j = 0; j < REDIS_SHARED_INTEGERS; j++) { shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j); shared.integers[j]->encoding = REDIS_ENCODING_INT; } for (j = 0; j < REDIS_SHARED_BULKHDR_LEN; j++) { shared.mbulkhdr[j] = createObject(REDIS_STRING, sdscatprintf(sdsempty(),"*%d\r\n",j)); shared.bulkhdr[j] = createObject(REDIS_STRING, sdscatprintf(sdsempty(),"$%d\r\n",j)); } /* The following two shared objects, minstring and maxstrings, are not * actually used for their value but as a special object meaning * respectively the minimum possible string and the maximum possible * string in string comparisons for the ZRANGEBYLEX command. */ shared.minstring = createStringObject("minstring",9); shared.maxstring = createStringObject("maxstring",9); } void initServerConfig(void) { int j; getRandomHexChars(server.runid,REDIS_RUN_ID_SIZE); server.configfile = NULL; server.hz = REDIS_DEFAULT_HZ; server.runid[REDIS_RUN_ID_SIZE] = '\0'; server.arch_bits = (sizeof(long) == 8) ? 64 : 32; server.port = REDIS_SERVERPORT; server.tcp_backlog = REDIS_TCP_BACKLOG; server.bindaddr_count = 0; server.unixsocket = NULL; server.unixsocketperm = REDIS_DEFAULT_UNIX_SOCKET_PERM; server.ipfd_count = 0; server.sofd = -1; server.dbnum = REDIS_DEFAULT_DBNUM; server.verbosity = REDIS_DEFAULT_VERBOSITY; server.maxidletime = REDIS_MAXIDLETIME; server.tcpkeepalive = REDIS_DEFAULT_TCP_KEEPALIVE; server.active_expire_enabled = 1; server.client_max_querybuf_len = REDIS_MAX_QUERYBUF_LEN; server.saveparams = NULL; server.loading = 0; server.logfile = zstrdup(REDIS_DEFAULT_LOGFILE); server.syslog_enabled = REDIS_DEFAULT_SYSLOG_ENABLED; server.syslog_ident = zstrdup(REDIS_DEFAULT_SYSLOG_IDENT); server.syslog_facility = LOG_LOCAL0; server.daemonize = REDIS_DEFAULT_DAEMONIZE; server.aof_state = REDIS_AOF_OFF; server.aof_fsync = REDIS_DEFAULT_AOF_FSYNC; server.aof_no_fsync_on_rewrite = REDIS_DEFAULT_AOF_NO_FSYNC_ON_REWRITE; server.aof_rewrite_perc = REDIS_AOF_REWRITE_PERC; server.aof_rewrite_min_size = REDIS_AOF_REWRITE_MIN_SIZE; server.aof_rewrite_base_size = 0; server.aof_rewrite_scheduled = 0; server.aof_last_fsync = time(NULL); server.aof_rewrite_time_last = -1; server.aof_rewrite_time_start = -1; server.aof_lastbgrewrite_status = REDIS_OK; server.aof_delayed_fsync = 0; server.aof_fd = -1; server.aof_selected_db = -1; /* Make sure the first time will not match */ server.aof_flush_postponed_start = 0; server.aof_rewrite_incremental_fsync = REDIS_DEFAULT_AOF_REWRITE_INCREMENTAL_FSYNC; server.aof_load_truncated = REDIS_DEFAULT_AOF_LOAD_TRUNCATED; server.pidfile = zstrdup(REDIS_DEFAULT_PID_FILE); server.rdb_filename = zstrdup(REDIS_DEFAULT_RDB_FILENAME); server.aof_filename = zstrdup(REDIS_DEFAULT_AOF_FILENAME); server.requirepass = NULL; server.rdb_compression = REDIS_DEFAULT_RDB_COMPRESSION; server.rdb_checksum = REDIS_DEFAULT_RDB_CHECKSUM; server.stop_writes_on_bgsave_err = REDIS_DEFAULT_STOP_WRITES_ON_BGSAVE_ERROR; server.activerehashing = REDIS_DEFAULT_ACTIVE_REHASHING; server.notify_keyspace_events = 0; server.maxclients = REDIS_MAX_CLIENTS; server.bpop_blocked_clients = 0; server.maxmemory = REDIS_DEFAULT_MAXMEMORY; server.maxmemory_policy = REDIS_DEFAULT_MAXMEMORY_POLICY; server.maxmemory_samples = REDIS_DEFAULT_MAXMEMORY_SAMPLES; server.hash_max_ziplist_entries = REDIS_HASH_MAX_ZIPLIST_ENTRIES; server.hash_max_ziplist_value = REDIS_HASH_MAX_ZIPLIST_VALUE; server.list_max_ziplist_entries = REDIS_LIST_MAX_ZIPLIST_ENTRIES; server.list_max_ziplist_value = REDIS_LIST_MAX_ZIPLIST_VALUE; server.set_max_intset_entries = REDIS_SET_MAX_INTSET_ENTRIES; server.zset_max_ziplist_entries = REDIS_ZSET_MAX_ZIPLIST_ENTRIES; server.zset_max_ziplist_value = REDIS_ZSET_MAX_ZIPLIST_VALUE; server.hll_sparse_max_bytes = REDIS_DEFAULT_HLL_SPARSE_MAX_BYTES; server.shutdown_asap = 0; server.repl_ping_slave_period = REDIS_REPL_PING_SLAVE_PERIOD; server.repl_timeout = REDIS_REPL_TIMEOUT; server.repl_min_slaves_to_write = REDIS_DEFAULT_MIN_SLAVES_TO_WRITE; server.repl_min_slaves_max_lag = REDIS_DEFAULT_MIN_SLAVES_MAX_LAG; server.cluster_enabled = 0; server.cluster_node_timeout = REDIS_CLUSTER_DEFAULT_NODE_TIMEOUT; server.cluster_migration_barrier = REDIS_CLUSTER_DEFAULT_MIGRATION_BARRIER; server.cluster_slave_validity_factor = REDIS_CLUSTER_DEFAULT_SLAVE_VALIDITY; server.cluster_require_full_coverage = REDIS_CLUSTER_DEFAULT_REQUIRE_FULL_COVERAGE; server.cluster_configfile = zstrdup(REDIS_DEFAULT_CLUSTER_CONFIG_FILE); server.lua_caller = NULL; server.lua_time_limit = REDIS_LUA_TIME_LIMIT; server.lua_client = NULL; server.lua_timedout = 0; server.migrate_cached_sockets = dictCreate(&migrateCacheDictType,NULL); server.next_client_id = 1; /* Client IDs, start from 1 .*/ server.loading_process_events_interval_bytes = (1024*1024*2); server.lruclock = getLRUClock(); resetServerSaveParams(); appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */ appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */ appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */ /* Replication related */ server.masterauth = NULL; server.masterhost = NULL; server.masterport = 6379; server.master = NULL; server.cached_master = NULL; server.repl_master_initial_offset = -1; server.repl_state = REDIS_REPL_NONE; server.repl_syncio_timeout = REDIS_REPL_SYNCIO_TIMEOUT; server.repl_serve_stale_data = REDIS_DEFAULT_SLAVE_SERVE_STALE_DATA; server.repl_slave_ro = REDIS_DEFAULT_SLAVE_READ_ONLY; server.repl_down_since = 0; /* Never connected, repl is down since EVER. */ server.repl_disable_tcp_nodelay = REDIS_DEFAULT_REPL_DISABLE_TCP_NODELAY; server.repl_diskless_sync = REDIS_DEFAULT_REPL_DISKLESS_SYNC; server.repl_diskless_sync_delay = REDIS_DEFAULT_REPL_DISKLESS_SYNC_DELAY; server.slave_priority = REDIS_DEFAULT_SLAVE_PRIORITY; server.master_repl_offset = 0; /* Replication partial resync backlog */ server.repl_backlog = NULL; server.repl_backlog_size = REDIS_DEFAULT_REPL_BACKLOG_SIZE; server.repl_backlog_histlen = 0; server.repl_backlog_idx = 0; server.repl_backlog_off = 0; server.repl_backlog_time_limit = REDIS_DEFAULT_REPL_BACKLOG_TIME_LIMIT; server.repl_no_slaves_since = time(NULL); /* Client output buffer limits */ for (j = 0; j < REDIS_CLIENT_TYPE_COUNT; j++) server.client_obuf_limits[j] = clientBufferLimitsDefaults[j]; /* Double constants initialization */ R_Zero = 0.0; R_PosInf = 1.0/R_Zero; R_NegInf = -1.0/R_Zero; R_Nan = R_Zero/R_Zero; /* Command table -- we initiialize it here as it is part of the * initial configuration, since command names may be changed via * redis.conf using the rename-command directive. */ server.commands = dictCreate(&commandTableDictType,NULL); server.orig_commands = dictCreate(&commandTableDictType,NULL); populateCommandTable(); server.delCommand = lookupCommandByCString("del"); server.multiCommand = lookupCommandByCString("multi"); server.lpushCommand = lookupCommandByCString("lpush"); server.lpopCommand = lookupCommandByCString("lpop"); server.rpopCommand = lookupCommandByCString("rpop"); /* Slow log */ server.slowlog_log_slower_than = REDIS_SLOWLOG_LOG_SLOWER_THAN; server.slowlog_max_len = REDIS_SLOWLOG_MAX_LEN; /* Latency monitor */ server.latency_monitor_threshold = REDIS_DEFAULT_LATENCY_MONITOR_THRESHOLD; /* Debugging */ server.assert_failed = "<no assertion failed>"; server.assert_file = "<no file>"; server.assert_line = 0; server.bug_report_start = 0; server.watchdog_period = 0; } /* This function will try to raise the max number of open files accordingly to * the configured max number of clients. It also reserves a number of file * descriptors (REDIS_MIN_RESERVED_FDS) for extra operations of * persistence, listening sockets, log files and so forth. * * If it will not be possible to set the limit accordingly to the configured * max number of clients, the function will do the reverse setting * server.maxclients to the value that we can actually handle. */ void adjustOpenFilesLimit(void) { rlim_t maxfiles = server.maxclients+REDIS_MIN_RESERVED_FDS; struct rlimit limit; if (getrlimit(RLIMIT_NOFILE,&limit) == -1) { redisLog(REDIS_WARNING,"Unable to obtain the current NOFILE limit (%s), assuming 1024 and setting the max clients configuration accordingly.", strerror(errno)); server.maxclients = 1024-REDIS_MIN_RESERVED_FDS; } else { rlim_t oldlimit = limit.rlim_cur; /* Set the max number of files if the current limit is not enough * for our needs. */ if (oldlimit < maxfiles) { rlim_t bestlimit; int setrlimit_error = 0; /* Try to set the file limit to match 'maxfiles' or at least * to the higher value supported less than maxfiles. */ bestlimit = maxfiles; while(bestlimit > oldlimit) { rlim_t decr_step = 16; limit.rlim_cur = bestlimit; limit.rlim_max = bestlimit; if (setrlimit(RLIMIT_NOFILE,&limit) != -1) break; setrlimit_error = errno; /* We failed to set file limit to 'bestlimit'. Try with a * smaller limit decrementing by a few FDs per iteration. */ if (bestlimit < decr_step) break; bestlimit -= decr_step; } /* Assume that the limit we get initially is still valid if * our last try was even lower. */ if (bestlimit < oldlimit) bestlimit = oldlimit; if (bestlimit < maxfiles) { int old_maxclients = server.maxclients; server.maxclients = bestlimit-REDIS_MIN_RESERVED_FDS; if (server.maxclients < 1) { redisLog(REDIS_WARNING,"Your current 'ulimit -n' " "of %llu is not enough for Redis to start. " "Please increase your open file limit to at least " "%llu. Exiting.", (unsigned long long) oldlimit, (unsigned long long) maxfiles); exit(1); } redisLog(REDIS_WARNING,"You requested maxclients of %d " "requiring at least %llu max file descriptors.", old_maxclients, (unsigned long long) maxfiles); redisLog(REDIS_WARNING,"Redis can't set maximum open files " "to %llu because of OS error: %s.", (unsigned long long) maxfiles, strerror(setrlimit_error)); redisLog(REDIS_WARNING,"Current maximum open files is %llu. " "maxclients has been reduced to %d to compensate for " "low ulimit. " "If you need higher maxclients increase 'ulimit -n'.", (unsigned long long) bestlimit, server.maxclients); } else { redisLog(REDIS_NOTICE,"Increased maximum number of open files " "to %llu (it was originally set to %llu).", (unsigned long long) maxfiles, (unsigned long long) oldlimit); } } } } /* Check that server.tcp_backlog can be actually enforced in Linux according * to the value of /proc/sys/net/core/somaxconn, or warn about it. */ void checkTcpBacklogSettings(void) { #ifdef HAVE_PROC_SOMAXCONN FILE *fp = fopen("/proc/sys/net/core/somaxconn","r"); char buf[1024]; if (!fp) return; if (fgets(buf,sizeof(buf),fp) != NULL) { int somaxconn = atoi(buf); if (somaxconn > 0 && somaxconn < server.tcp_backlog) { redisLog(REDIS_WARNING,"WARNING: The TCP backlog setting of %d cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of %d.", server.tcp_backlog, somaxconn); } } fclose(fp); #endif } /* Initialize a set of file descriptors to listen to the specified 'port' * binding the addresses specified in the Redis server configuration. * * The listening file descriptors are stored in the integer array 'fds' * and their number is set in '*count'. * * The addresses to bind are specified in the global server.bindaddr array * and their number is server.bindaddr_count. If the server configuration * contains no specific addresses to bind, this function will try to * bind * (all addresses) for both the IPv4 and IPv6 protocols. * * On success the function returns REDIS_OK. * * On error the function returns REDIS_ERR. For the function to be on * error, at least one of the server.bindaddr addresses was * impossible to bind, or no bind addresses were specified in the server * configuration but the function is not able to bind * for at least * one of the IPv4 or IPv6 protocols. */ int listenToPort(int port, int *fds, int *count) { int j; /* Force binding of 0.0.0.0 if no bind address is specified, always * entering the loop if j == 0. */ if (server.bindaddr_count == 0) server.bindaddr[0] = NULL; for (j = 0; j < server.bindaddr_count || j == 0; j++) { if (server.bindaddr[j] == NULL) { /* Bind * for both IPv6 and IPv4, we enter here only if * server.bindaddr_count == 0. */ fds[*count] = anetTcp6Server(server.neterr,port,NULL, server.tcp_backlog); if (fds[*count] != ANET_ERR) { anetNonBlock(NULL,fds[*count]); (*count)++; } fds[*count] = anetTcpServer(server.neterr,port,NULL, server.tcp_backlog); if (fds[*count] != ANET_ERR) { anetNonBlock(NULL,fds[*count]); (*count)++; } /* Exit the loop if we were able to bind * on IPv4 or IPv6, * otherwise fds[*count] will be ANET_ERR and we'll print an * error and return to the caller with an error. */ if (*count) break; } else if (strchr(server.bindaddr[j],':')) { /* Bind IPv6 address. */ fds[*count] = anetTcp6Server(server.neterr,port,server.bindaddr[j], server.tcp_backlog); } else { /* Bind IPv4 address. */ fds[*count] = anetTcpServer(server.neterr,port,server.bindaddr[j], server.tcp_backlog); } if (fds[*count] == ANET_ERR) { redisLog(REDIS_WARNING, "Creating Server TCP listening socket %s:%d: %s", server.bindaddr[j] ? server.bindaddr[j] : "*", port, server.neterr); return REDIS_ERR; } anetNonBlock(NULL,fds[*count]); (*count)++; } return REDIS_OK; } /* Resets the stats that we expose via INFO or other means that we want * to reset via CONFIG RESETSTAT. The function is also used in order to * initialize these fields in initServer() at server startup. */ void resetServerStats(void) { int j; server.stat_numcommands = 0; server.stat_numconnections = 0; server.stat_expiredkeys = 0; server.stat_evictedkeys = 0; server.stat_keyspace_misses = 0; server.stat_keyspace_hits = 0; server.stat_fork_time = 0; server.stat_fork_rate = 0; server.stat_rejected_conn = 0; server.stat_sync_full = 0; server.stat_sync_partial_ok = 0; server.stat_sync_partial_err = 0; for (j = 0; j < REDIS_METRIC_COUNT; j++) { server.inst_metric[j].idx = 0; server.inst_metric[j].last_sample_time = mstime(); server.inst_metric[j].last_sample_count = 0; memset(server.inst_metric[j].samples,0, sizeof(server.inst_metric[j].samples)); } server.stat_net_input_bytes = 0; server.stat_net_output_bytes = 0; server.aof_delayed_fsync = 0; } void initServer(void) { int j; signal(SIGHUP, SIG_IGN); signal(SIGPIPE, SIG_IGN); setupSignalHandlers(); if (server.syslog_enabled) { openlog(server.syslog_ident, LOG_PID | LOG_NDELAY | LOG_NOWAIT, server.syslog_facility); } server.pid = getpid(); server.current_client = NULL; server.clients = listCreate(); server.clients_to_close = listCreate(); server.slaves = listCreate(); server.monitors = listCreate(); server.slaveseldb = -1; /* Force to emit the first SELECT command. */ server.unblocked_clients = listCreate(); server.ready_keys = listCreate(); server.clients_waiting_acks = listCreate(); server.get_ack_from_slaves = 0; server.clients_paused = 0; createSharedObjects(); adjustOpenFilesLimit(); server.el = aeCreateEventLoop(server.maxclients+REDIS_EVENTLOOP_FDSET_INCR); server.db = zmalloc(sizeof(redisDb)*server.dbnum); /* Open the TCP listening socket for the user commands. */ if (server.port != 0 && listenToPort(server.port,server.ipfd,&server.ipfd_count) == REDIS_ERR) exit(1); /* Open the listening Unix domain socket. */ if (server.unixsocket != NULL) { unlink(server.unixsocket); /* don't care if this fails */ server.sofd = anetUnixServer(server.neterr,server.unixsocket, server.unixsocketperm, server.tcp_backlog); if (server.sofd == ANET_ERR) { redisLog(REDIS_WARNING, "Opening Unix socket: %s", server.neterr); exit(1); } anetNonBlock(NULL,server.sofd); } /* Abort if there are no listening sockets at all. */ if (server.ipfd_count == 0 && server.sofd < 0) { redisLog(REDIS_WARNING, "Configured to not listen anywhere, exiting."); exit(1); } /* Create the Redis databases, and initialize other internal state. */ for (j = 0; j < server.dbnum; j++) { server.db[j].dict = dictCreate(&dbDictType,NULL); server.db[j].expires = dictCreate(&keyptrDictType,NULL); server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL); server.db[j].ready_keys = dictCreate(&setDictType,NULL); server.db[j].watched_keys = dictCreate(&keylistDictType,NULL); server.db[j].eviction_pool = evictionPoolAlloc(); server.db[j].id = j; server.db[j].avg_ttl = 0; } server.pubsub_channels = dictCreate(&keylistDictType,NULL); server.pubsub_patterns = listCreate(); listSetFreeMethod(server.pubsub_patterns,freePubsubPattern); listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern); server.cronloops = 0; server.rdb_child_pid = -1; server.aof_child_pid = -1; server.rdb_child_type = REDIS_RDB_CHILD_TYPE_NONE; aofRewriteBufferReset(); server.aof_buf = sdsempty(); server.lastsave = time(NULL); /* At startup we consider the DB saved. */ server.lastbgsave_try = 0; /* At startup we never tried to BGSAVE. */ server.rdb_save_time_last = -1; server.rdb_save_time_start = -1; server.dirty = 0; resetServerStats(); /* A few stats we don't want to reset: server startup time, and peak mem. */ server.stat_starttime = time(NULL); server.stat_peak_memory = 0; server.resident_set_size = 0; server.lastbgsave_status = REDIS_OK; server.aof_last_write_status = REDIS_OK; server.aof_last_write_errno = 0; server.repl_good_slaves_count = 0; updateCachedTime(); /* Create the serverCron() time event, that's our main way to process * background operations. */ if(aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL) == AE_ERR) { redisPanic("Can't create the serverCron time event."); exit(1); } /* Create an event handler for accepting new connections in TCP and Unix * domain sockets. */ for (j = 0; j < server.ipfd_count; j++) { if (aeCreateFileEvent(server.el, server.ipfd[j], AE_READABLE, acceptTcpHandler,NULL) == AE_ERR) { redisPanic( "Unrecoverable error creating server.ipfd file event."); } } if (server.sofd > 0 && aeCreateFileEvent(server.el,server.sofd,AE_READABLE, acceptUnixHandler,NULL) == AE_ERR) redisPanic("Unrecoverable error creating server.sofd file event."); /* Open the AOF file if needed. */ if (server.aof_state == REDIS_AOF_ON) { server.aof_fd = open(server.aof_filename, O_WRONLY|O_APPEND|O_CREAT,0644); if (server.aof_fd == -1) { redisLog(REDIS_WARNING, "Can't open the append-only file: %s", strerror(errno)); exit(1); } } /* 32 bit instances are limited to 4GB of address space, so if there is * no explicit limit in the user provided configuration we set a limit * at 3 GB using maxmemory with 'noeviction' policy'. This avoids * useless crashes of the Redis instance for out of memory. */ if (server.arch_bits == 32 && server.maxmemory == 0) { redisLog(REDIS_WARNING,"Warning: 32 bit instance detected but no memory limit set. Setting 3 GB maxmemory limit with 'noeviction' policy now."); server.maxmemory = 3072LL*(1024*1024); /* 3 GB */ server.maxmemory_policy = REDIS_MAXMEMORY_NO_EVICTION; } if (server.cluster_enabled) clusterInit(); replicationScriptCacheInit(); scriptingInit(); slowlogInit(); latencyMonitorInit(); bioInit(); } /* Populates the Redis Command Table starting from the hard coded list * we have on top of redis.c file. */ void populateCommandTable(void) { int j; int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand); for (j = 0; j < numcommands; j++) { struct redisCommand *c = redisCommandTable+j; char *f = c->sflags; int retval1, retval2; while(*f != '\0') { switch(*f) { case 'w': c->flags |= REDIS_CMD_WRITE; break; case 'r': c->flags |= REDIS_CMD_READONLY; break; case 'm': c->flags |= REDIS_CMD_DENYOOM; break; case 'a': c->flags |= REDIS_CMD_ADMIN; break; case 'p': c->flags |= REDIS_CMD_PUBSUB; break; case 's': c->flags |= REDIS_CMD_NOSCRIPT; break; case 'R': c->flags |= REDIS_CMD_RANDOM; break; case 'S': c->flags |= REDIS_CMD_SORT_FOR_SCRIPT; break; case 'l': c->flags |= REDIS_CMD_LOADING; break; case 't': c->flags |= REDIS_CMD_STALE; break; case 'M': c->flags |= REDIS_CMD_SKIP_MONITOR; break; case 'k': c->flags |= REDIS_CMD_ASKING; break; case 'F': c->flags |= REDIS_CMD_FAST; break; default: redisPanic("Unsupported command flag"); break; } f++; } retval1 = dictAdd(server.commands, sdsnew(c->name), c); /* Populate an additional dictionary that will be unaffected * by rename-command statements in redis.conf. */ retval2 = dictAdd(server.orig_commands, sdsnew(c->name), c); redisAssert(retval1 == DICT_OK && retval2 == DICT_OK); } } void resetCommandTableStats(void) { int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand); int j; for (j = 0; j < numcommands; j++) { struct redisCommand *c = redisCommandTable+j; c->microseconds = 0; c->calls = 0; } } /* ========================== Redis OP Array API ============================ */ void redisOpArrayInit(redisOpArray *oa) { oa->ops = NULL; oa->numops = 0; } int redisOpArrayAppend(redisOpArray *oa, struct redisCommand *cmd, int dbid, robj **argv, int argc, int target) { redisOp *op; oa->ops = zrealloc(oa->ops,sizeof(redisOp)*(oa->numops+1)); op = oa->ops+oa->numops; op->cmd = cmd; op->dbid = dbid; op->argv = argv; op->argc = argc; op->target = target; oa->numops++; return oa->numops; } void redisOpArrayFree(redisOpArray *oa) { while(oa->numops) { int j; redisOp *op; oa->numops--; op = oa->ops+oa->numops; for (j = 0; j < op->argc; j++) decrRefCount(op->argv[j]); zfree(op->argv); } zfree(oa->ops); } /* ====================== Commands lookup and execution ===================== */ struct redisCommand *lookupCommand(sds name) { return dictFetchValue(server.commands, name); } struct redisCommand *lookupCommandByCString(char *s) { struct redisCommand *cmd; sds name = sdsnew(s); cmd = dictFetchValue(server.commands, name); sdsfree(name); return cmd; } /* Lookup the command in the current table, if not found also check in * the original table containing the original command names unaffected by * redis.conf rename-command statement. * * This is used by functions rewriting the argument vector such as * rewriteClientCommandVector() in order to set client->cmd pointer * correctly even if the command was renamed. */ struct redisCommand *lookupCommandOrOriginal(sds name) { struct redisCommand *cmd = dictFetchValue(server.commands, name); if (!cmd) cmd = dictFetchValue(server.orig_commands,name); return cmd; } /* Propagate the specified command (in the context of the specified database id) * to AOF and Slaves. * * flags are an xor between: * + REDIS_PROPAGATE_NONE (no propagation of command at all) * + REDIS_PROPAGATE_AOF (propagate into the AOF file if is enabled) * + REDIS_PROPAGATE_REPL (propagate into the replication link) */ void propagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int flags) { if (server.aof_state != REDIS_AOF_OFF && flags & REDIS_PROPAGATE_AOF) feedAppendOnlyFile(cmd,dbid,argv,argc); if (flags & REDIS_PROPAGATE_REPL) replicationFeedSlaves(server.slaves,dbid,argv,argc); } /* Used inside commands to schedule the propagation of additional commands * after the current command is propagated to AOF / Replication. */ void alsoPropagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int target) { redisOpArrayAppend(&server.also_propagate,cmd,dbid,argv,argc,target); } /* It is possible to call the function forceCommandPropagation() inside a * Redis command implementation in order to to force the propagation of a * specific command execution into AOF / Replication. */ void forceCommandPropagation(redisClient *c, int flags) { if (flags & REDIS_PROPAGATE_REPL) c->flags |= REDIS_FORCE_REPL; if (flags & REDIS_PROPAGATE_AOF) c->flags |= REDIS_FORCE_AOF; } /* Call() is the core of Redis execution of a command */ void call(redisClient *c, int flags) { long long dirty, start, duration; int client_old_flags = c->flags; /* Sent the command to clients in MONITOR mode, only if the commands are * not generated from reading an AOF. */ if (listLength(server.monitors) && !server.loading && !(c->cmd->flags & (REDIS_CMD_SKIP_MONITOR|REDIS_CMD_ADMIN))) { replicationFeedMonitors(c,server.monitors,c->db->id,c->argv,c->argc); } /* Call the command. */ c->flags &= ~(REDIS_FORCE_AOF|REDIS_FORCE_REPL); redisOpArrayInit(&server.also_propagate); dirty = server.dirty; start = ustime(); c->cmd->proc(c); duration = ustime()-start; dirty = server.dirty-dirty; if (dirty < 0) dirty = 0; /* When EVAL is called loading the AOF we don't want commands called * from Lua to go into the slowlog or to populate statistics. */ if (server.loading && c->flags & REDIS_LUA_CLIENT) flags &= ~(REDIS_CALL_SLOWLOG | REDIS_CALL_STATS); /* If the caller is Lua, we want to force the EVAL caller to propagate * the script if the command flag or client flag are forcing the * propagation. */ if (c->flags & REDIS_LUA_CLIENT && server.lua_caller) { if (c->flags & REDIS_FORCE_REPL) server.lua_caller->flags |= REDIS_FORCE_REPL; if (c->flags & REDIS_FORCE_AOF) server.lua_caller->flags |= REDIS_FORCE_AOF; } /* Log the command into the Slow log if needed, and populate the * per-command statistics that we show in INFO commandstats. */ if (flags & REDIS_CALL_SLOWLOG && c->cmd->proc != execCommand) { char *latency_event = (c->cmd->flags & REDIS_CMD_FAST) ? "fast-command" : "command"; latencyAddSampleIfNeeded(latency_event,duration/1000); slowlogPushEntryIfNeeded(c->argv,c->argc,duration); } if (flags & REDIS_CALL_STATS) { c->cmd->microseconds += duration; c->cmd->calls++; } /* Propagate the command into the AOF and replication link */ if (flags & REDIS_CALL_PROPAGATE) { int flags = REDIS_PROPAGATE_NONE; if (c->flags & REDIS_FORCE_REPL) flags |= REDIS_PROPAGATE_REPL; if (c->flags & REDIS_FORCE_AOF) flags |= REDIS_PROPAGATE_AOF; if (dirty) flags |= (REDIS_PROPAGATE_REPL | REDIS_PROPAGATE_AOF); if (flags != REDIS_PROPAGATE_NONE) propagate(c->cmd,c->db->id,c->argv,c->argc,flags); } /* Restore the old FORCE_AOF/REPL flags, since call can be executed * recursively. */ c->flags &= ~(REDIS_FORCE_AOF|REDIS_FORCE_REPL); c->flags |= client_old_flags & (REDIS_FORCE_AOF|REDIS_FORCE_REPL); /* Handle the alsoPropagate() API to handle commands that want to propagate * multiple separated commands. */ if (server.also_propagate.numops) { int j; redisOp *rop; for (j = 0; j < server.also_propagate.numops; j++) { rop = &server.also_propagate.ops[j]; propagate(rop->cmd, rop->dbid, rop->argv, rop->argc, rop->target); } redisOpArrayFree(&server.also_propagate); } server.stat_numcommands++; } /* If this function gets called we already read a whole * command, arguments are in the client argv/argc fields. * processCommand() execute the command or prepare the * server for a bulk read from the client. * * If 1 is returned the client is still alive and valid and * other operations can be performed by the caller. Otherwise * if 0 is returned the client was destroyed (i.e. after QUIT). */ int processCommand(redisClient *c) { /* The QUIT command is handled separately. Normal command procs will * go through checking for replication and QUIT will cause trouble * when FORCE_REPLICATION is enabled and would be implemented in * a regular command proc. */ if (!strcasecmp(c->argv[0]->ptr,"quit")) { addReply(c,shared.ok); c->flags |= REDIS_CLOSE_AFTER_REPLY; return REDIS_ERR; } /* Now lookup the command and check ASAP about trivial error conditions * such as wrong arity, bad command name and so forth. */ c->cmd = c->lastcmd = lookupCommand(c->argv[0]->ptr); if (!c->cmd) { flagTransaction(c); addReplyErrorFormat(c,"unknown command '%s'", (char*)c->argv[0]->ptr); return REDIS_OK; } else if ((c->cmd->arity > 0 && c->cmd->arity != c->argc) || (c->argc < -c->cmd->arity)) { flagTransaction(c); addReplyErrorFormat(c,"wrong number of arguments for '%s' command", c->cmd->name); return REDIS_OK; } /* Check if the user is authenticated */ if (server.requirepass && !c->authenticated && c->cmd->proc != authCommand) { flagTransaction(c); addReply(c,shared.noautherr); return REDIS_OK; } /* If cluster is enabled perform the cluster redirection here. * However we don't perform the redirection if: * 1) The sender of this command is our master. * 2) The command has no key arguments. */ if (server.cluster_enabled && !(c->flags & REDIS_MASTER) && !(c->flags & REDIS_LUA_CLIENT && server.lua_caller->flags & REDIS_MASTER) && !(c->cmd->getkeys_proc == NULL && c->cmd->firstkey == 0)) { int hashslot; if (server.cluster->state != REDIS_CLUSTER_OK) { flagTransaction(c); clusterRedirectClient(c,NULL,0,REDIS_CLUSTER_REDIR_DOWN_STATE); return REDIS_OK; } else { int error_code; clusterNode *n = getNodeByQuery(c,c->cmd,c->argv,c->argc,&hashslot,&error_code); if (n == NULL || n != server.cluster->myself) { flagTransaction(c); clusterRedirectClient(c,n,hashslot,error_code); return REDIS_OK; } } } /* Handle the maxmemory directive. * * First we try to free some memory if possible (if there are volatile * keys in the dataset). If there are not the only thing we can do * is returning an error. */ if (server.maxmemory) { int retval = freeMemoryIfNeeded(); /* freeMemoryIfNeeded may flush slave output buffers. This may result * into a slave, that may be the active client, to be freed. */ if (server.current_client == NULL) return REDIS_ERR; /* It was impossible to free enough memory, and the command the client * is trying to execute is denied during OOM conditions? Error. */ if ((c->cmd->flags & REDIS_CMD_DENYOOM) && retval == REDIS_ERR) { flagTransaction(c); addReply(c, shared.oomerr); return REDIS_OK; } } /* Don't accept write commands if there are problems persisting on disk * and if this is a master instance. */ if (((server.stop_writes_on_bgsave_err && server.saveparamslen > 0 && server.lastbgsave_status == REDIS_ERR) || server.aof_last_write_status == REDIS_ERR) && server.masterhost == NULL && (c->cmd->flags & REDIS_CMD_WRITE || c->cmd->proc == pingCommand)) { flagTransaction(c); if (server.aof_last_write_status == REDIS_OK) addReply(c, shared.bgsaveerr); else addReplySds(c, sdscatprintf(sdsempty(), "-MISCONF Errors writing to the AOF file: %s\r\n", strerror(server.aof_last_write_errno))); return REDIS_OK; } /* Don't accept write commands if there are not enough good slaves and * user configured the min-slaves-to-write option. */ if (server.masterhost == NULL && server.repl_min_slaves_to_write && server.repl_min_slaves_max_lag && c->cmd->flags & REDIS_CMD_WRITE && server.repl_good_slaves_count < server.repl_min_slaves_to_write) { flagTransaction(c); addReply(c, shared.noreplicaserr); return REDIS_OK; } /* Don't accept write commands if this is a read only slave. But * accept write commands if this is our master. */ if (server.masterhost && server.repl_slave_ro && !(c->flags & REDIS_MASTER) && c->cmd->flags & REDIS_CMD_WRITE) { addReply(c, shared.roslaveerr); return REDIS_OK; } /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */ if (c->flags & REDIS_PUBSUB && c->cmd->proc != pingCommand && c->cmd->proc != subscribeCommand && c->cmd->proc != unsubscribeCommand && c->cmd->proc != psubscribeCommand && c->cmd->proc != punsubscribeCommand) { addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / PING / QUIT allowed in this context"); return REDIS_OK; } /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and * we are a slave with a broken link with master. */ if (server.masterhost && server.repl_state != REDIS_REPL_CONNECTED && server.repl_serve_stale_data == 0 && !(c->cmd->flags & REDIS_CMD_STALE)) { flagTransaction(c); addReply(c, shared.masterdownerr); return REDIS_OK; } /* Loading DB? Return an error if the command has not the * REDIS_CMD_LOADING flag. */ if (server.loading && !(c->cmd->flags & REDIS_CMD_LOADING)) { addReply(c, shared.loadingerr); return REDIS_OK; } /* Lua script too slow? Only allow a limited number of commands. */ if (server.lua_timedout && c->cmd->proc != authCommand && c->cmd->proc != replconfCommand && !(c->cmd->proc == shutdownCommand && c->argc == 2 && tolower(((char*)c->argv[1]->ptr)[0]) == 'n') && !(c->cmd->proc == scriptCommand && c->argc == 2 && tolower(((char*)c->argv[1]->ptr)[0]) == 'k')) { flagTransaction(c); addReply(c, shared.slowscripterr); return REDIS_OK; } /* Exec the command */ if (c->flags & REDIS_MULTI && c->cmd->proc != execCommand && c->cmd->proc != discardCommand && c->cmd->proc != multiCommand && c->cmd->proc != watchCommand) { queueMultiCommand(c); addReply(c,shared.queued); } else { call(c,REDIS_CALL_FULL); c->woff = server.master_repl_offset; if (listLength(server.ready_keys)) handleClientsBlockedOnLists(); } return REDIS_OK; } /*================================== Shutdown =============================== */ /* Close listening sockets. Also unlink the unix domain socket if * unlink_unix_socket is non-zero. */ void closeListeningSockets(int unlink_unix_socket) { int j; for (j = 0; j < server.ipfd_count; j++) close(server.ipfd[j]); if (server.sofd != -1) close(server.sofd); if (server.cluster_enabled) for (j = 0; j < server.cfd_count; j++) close(server.cfd[j]); if (unlink_unix_socket && server.unixsocket) { redisLog(REDIS_NOTICE,"Removing the unix socket file."); unlink(server.unixsocket); /* don't care if this fails */ } } int prepareForShutdown(int flags) { int save = flags & REDIS_SHUTDOWN_SAVE; int nosave = flags & REDIS_SHUTDOWN_NOSAVE; redisLog(REDIS_WARNING,"User requested shutdown..."); /* Kill the saving child if there is a background saving in progress. We want to avoid race conditions, for instance our saving child may overwrite the synchronous saving did by SHUTDOWN. */ if (server.rdb_child_pid != -1) { redisLog(REDIS_WARNING,"There is a child saving an .rdb. Killing it!"); kill(server.rdb_child_pid,SIGUSR1); rdbRemoveTempFile(server.rdb_child_pid); } if (server.aof_state != REDIS_AOF_OFF) { /* Kill the AOF saving child as the AOF we already have may be longer * but contains the full dataset anyway. */ if (server.aof_child_pid != -1) { /* If we have AOF enabled but haven't written the AOF yet, don't * shutdown or else the dataset will be lost. */ if (server.aof_state == REDIS_AOF_WAIT_REWRITE) { redisLog(REDIS_WARNING, "Writing initial AOF, can't exit."); return REDIS_ERR; } redisLog(REDIS_WARNING, "There is a child rewriting the AOF. Killing it!"); kill(server.aof_child_pid,SIGUSR1); } /* Append only file: fsync() the AOF and exit */ redisLog(REDIS_NOTICE,"Calling fsync() on the AOF file."); aof_fsync(server.aof_fd); } if ((server.saveparamslen > 0 && !nosave) || save) { redisLog(REDIS_NOTICE,"Saving the final RDB snapshot before exiting."); /* Snapshotting. Perform a SYNC SAVE and exit */ if (rdbSave(server.rdb_filename) != REDIS_OK) { /* Ooops.. error saving! The best we can do is to continue * operating. Note that if there was a background saving process, * in the next cron() Redis will be notified that the background * saving aborted, handling special stuff like slaves pending for * synchronization... */ redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit."); return REDIS_ERR; } } if (server.daemonize) { redisLog(REDIS_NOTICE,"Removing the pid file."); unlink(server.pidfile); } /* Close the listening sockets. Apparently this allows faster restarts. */ closeListeningSockets(1); redisLog(REDIS_WARNING,"%s is now ready to exit, bye bye...", server.sentinel_mode ? "Sentinel" : "Redis"); return REDIS_OK; } /*================================== Commands =============================== */ /* Return zero if strings are the same, non-zero if they are not. * The comparison is performed in a way that prevents an attacker to obtain * information about the nature of the strings just monitoring the execution * time of the function. * * Note that limiting the comparison length to strings up to 512 bytes we * can avoid leaking any information about the password length and any * possible branch misprediction related leak. */ int time_independent_strcmp(char *a, char *b) { char bufa[REDIS_AUTHPASS_MAX_LEN], bufb[REDIS_AUTHPASS_MAX_LEN]; /* The above two strlen perform len(a) + len(b) operations where either * a or b are fixed (our password) length, and the difference is only * relative to the length of the user provided string, so no information * leak is possible in the following two lines of code. */ unsigned int alen = strlen(a); unsigned int blen = strlen(b); unsigned int j; int diff = 0; /* We can't compare strings longer than our static buffers. * Note that this will never pass the first test in practical circumstances * so there is no info leak. */ if (alen > sizeof(bufa) || blen > sizeof(bufb)) return 1; memset(bufa,0,sizeof(bufa)); /* Constant time. */ memset(bufb,0,sizeof(bufb)); /* Constant time. */ /* Again the time of the following two copies is proportional to * len(a) + len(b) so no info is leaked. */ memcpy(bufa,a,alen); memcpy(bufb,b,blen); /* Always compare all the chars in the two buffers without * conditional expressions. */ for (j = 0; j < sizeof(bufa); j++) { diff |= (bufa[j] ^ bufb[j]); } /* Length must be equal as well. */ diff |= alen ^ blen; return diff; /* If zero strings are the same. */ } void authCommand(redisClient *c) { if (!server.requirepass) { addReplyError(c,"Client sent AUTH, but no password is set"); } else if (!time_independent_strcmp(c->argv[1]->ptr, server.requirepass)) { c->authenticated = 1; addReply(c,shared.ok); } else { c->authenticated = 0; addReplyError(c,"invalid password"); } } /* The PING command. It works in a different way if the client is in * in Pub/Sub mode. */ void pingCommand(redisClient *c) { /* The command takes zero or one arguments. */ if (c->argc > 2) { addReplyErrorFormat(c,"wrong number of arguments for '%s' command", c->cmd->name); return; } if (c->flags & REDIS_PUBSUB) { addReply(c,shared.mbulkhdr[2]); addReplyBulkCBuffer(c,"pong",4); if (c->argc == 1) addReplyBulkCBuffer(c,"",0); else addReplyBulk(c,c->argv[1]); } else { if (c->argc == 1) addReply(c,shared.pong); else addReplyBulk(c,c->argv[1]); } } void echoCommand(redisClient *c) { addReplyBulk(c,c->argv[1]); } void timeCommand(redisClient *c) { struct timeval tv; /* gettimeofday() can only fail if &tv is a bad address so we * don't check for errors. */ gettimeofday(&tv,NULL); addReplyMultiBulkLen(c,2); addReplyBulkLongLong(c,tv.tv_sec); addReplyBulkLongLong(c,tv.tv_usec); } /* Helper function for addReplyCommand() to output flags. */ int addReplyCommandFlag(redisClient *c, struct redisCommand *cmd, int f, char *reply) { if (cmd->flags & f) { addReplyStatus(c, reply); return 1; } return 0; } /* Output the representation of a Redis command. Used by the COMMAND command. */ void addReplyCommand(redisClient *c, struct redisCommand *cmd) { if (!cmd) { addReply(c, shared.nullbulk); } else { /* We are adding: command name, arg count, flags, first, last, offset */ addReplyMultiBulkLen(c, 6); addReplyBulkCString(c, cmd->name); addReplyLongLong(c, cmd->arity); int flagcount = 0; void *flaglen = addDeferredMultiBulkLength(c); flagcount += addReplyCommandFlag(c,cmd,REDIS_CMD_WRITE, "write"); flagcount += addReplyCommandFlag(c,cmd,REDIS_CMD_READONLY, "readonly"); flagcount += addReplyCommandFlag(c,cmd,REDIS_CMD_DENYOOM, "denyoom"); flagcount += addReplyCommandFlag(c,cmd,REDIS_CMD_ADMIN, "admin"); flagcount += addReplyCommandFlag(c,cmd,REDIS_CMD_PUBSUB, "pubsub"); flagcount += addReplyCommandFlag(c,cmd,REDIS_CMD_NOSCRIPT, "noscript"); flagcount += addReplyCommandFlag(c,cmd,REDIS_CMD_RANDOM, "random"); flagcount += addReplyCommandFlag(c,cmd,REDIS_CMD_SORT_FOR_SCRIPT,"sort_for_script"); flagcount += addReplyCommandFlag(c,cmd,REDIS_CMD_LOADING, "loading"); flagcount += addReplyCommandFlag(c,cmd,REDIS_CMD_STALE, "stale"); flagcount += addReplyCommandFlag(c,cmd,REDIS_CMD_SKIP_MONITOR, "skip_monitor"); flagcount += addReplyCommandFlag(c,cmd,REDIS_CMD_ASKING, "asking"); flagcount += addReplyCommandFlag(c,cmd,REDIS_CMD_FAST, "fast"); if (cmd->getkeys_proc) { addReplyStatus(c, "movablekeys"); flagcount += 1; } setDeferredMultiBulkLength(c, flaglen, flagcount); addReplyLongLong(c, cmd->firstkey); addReplyLongLong(c, cmd->lastkey); addReplyLongLong(c, cmd->keystep); } } /* COMMAND <subcommand> <args> */ void commandCommand(redisClient *c) { dictIterator *di; dictEntry *de; if (c->argc == 1) { addReplyMultiBulkLen(c, dictSize(server.commands)); di = dictGetIterator(server.commands); while ((de = dictNext(di)) != NULL) { addReplyCommand(c, dictGetVal(de)); } dictReleaseIterator(di); } else if (!strcasecmp(c->argv[1]->ptr, "info")) { int i; addReplyMultiBulkLen(c, c->argc-2); for (i = 2; i < c->argc; i++) { addReplyCommand(c, dictFetchValue(server.commands, c->argv[i]->ptr)); } } else if (!strcasecmp(c->argv[1]->ptr, "count") && c->argc == 2) { addReplyLongLong(c, dictSize(server.commands)); } else if (!strcasecmp(c->argv[1]->ptr,"getkeys") && c->argc >= 3) { struct redisCommand *cmd = lookupCommand(c->argv[2]->ptr); int *keys, numkeys, j; if (!cmd) { addReplyErrorFormat(c,"Invalid command specified"); return; } else if ((cmd->arity > 0 && cmd->arity != c->argc-2) || ((c->argc-2) < -cmd->arity)) { addReplyError(c,"Invalid number of arguments specified for command"); return; } keys = getKeysFromCommand(cmd,c->argv+2,c->argc-2,&numkeys); addReplyMultiBulkLen(c,numkeys); for (j = 0; j < numkeys; j++) addReplyBulk(c,c->argv[keys[j]+2]); getKeysFreeResult(keys); } else { addReplyError(c, "Unknown subcommand or wrong number of arguments."); return; } } /* Convert an amount of bytes into a human readable string in the form * of 100B, 2G, 100M, 4K, and so forth. */ void bytesToHuman(char *s, unsigned long long n) { double d; if (n < 1024) { /* Bytes */ sprintf(s,"%lluB",n); return; } else if (n < (1024*1024)) { d = (double)n/(1024); sprintf(s,"%.2fK",d); } else if (n < (1024LL*1024*1024)) { d = (double)n/(1024*1024); sprintf(s,"%.2fM",d); } else if (n < (1024LL*1024*1024*1024)) { d = (double)n/(1024LL*1024*1024); sprintf(s,"%.2fG",d); } else if (n < (1024LL*1024*1024*1024*1024)) { d = (double)n/(1024LL*1024*1024*1024); sprintf(s,"%.2fT",d); } else if (n < (1024LL*1024*1024*1024*1024*1024)) { d = (double)n/(1024LL*1024*1024*1024*1024); sprintf(s,"%.2fP",d); } else { /* Let's hope we never need this */ sprintf(s,"%lluB",n); } } /* Create the string returned by the INFO command. This is decoupled * by the INFO command itself as we need to report the same information * on memory corruption problems. */ sds genRedisInfoString(char *section) { sds info = sdsempty(); time_t uptime = server.unixtime-server.stat_starttime; int j, numcommands; struct rusage self_ru, c_ru; unsigned long lol, bib; int allsections = 0, defsections = 0; int sections = 0; if (section == NULL) section = "default"; allsections = strcasecmp(section,"all") == 0; defsections = strcasecmp(section,"default") == 0; getrusage(RUSAGE_SELF, &self_ru); getrusage(RUSAGE_CHILDREN, &c_ru); getClientsMaxBuffers(&lol,&bib); /* Server */ if (allsections || defsections || !strcasecmp(section,"server")) { static int call_uname = 1; static struct utsname name; char *mode; if (server.cluster_enabled) mode = "cluster"; else if (server.sentinel_mode) mode = "sentinel"; else mode = "standalone"; if (sections++) info = sdscat(info,"\r\n"); if (call_uname) { /* Uname can be slow and is always the same output. Cache it. */ uname(&name); call_uname = 0; } info = sdscatprintf(info, "# Server\r\n" "redis_version:%s\r\n" "redis_git_sha1:%s\r\n" "redis_git_dirty:%d\r\n" "redis_build_id:%llx\r\n" "redis_mode:%s\r\n" "os:%s %s %s\r\n" "arch_bits:%d\r\n" "multiplexing_api:%s\r\n" "gcc_version:%d.%d.%d\r\n" "process_id:%ld\r\n" "run_id:%s\r\n" "tcp_port:%d\r\n" "uptime_in_seconds:%jd\r\n" "uptime_in_days:%jd\r\n" "hz:%d\r\n" "lru_clock:%ld\r\n" "config_file:%s\r\n", REDIS_VERSION, redisGitSHA1(), strtol(redisGitDirty(),NULL,10) > 0, (unsigned long long) redisBuildId(), mode, name.sysname, name.release, name.machine, server.arch_bits, aeGetApiName(), #ifdef __GNUC__ __GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__, #else 0,0,0, #endif (long) getpid(), server.runid, server.port, (intmax_t)uptime, (intmax_t)(uptime/(3600*24)), server.hz, (unsigned long) server.lruclock, server.configfile ? server.configfile : ""); } /* Clients */ if (allsections || defsections || !strcasecmp(section,"clients")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Clients\r\n" "connected_clients:%lu\r\n" "client_longest_output_list:%lu\r\n" "client_biggest_input_buf:%lu\r\n" "blocked_clients:%d\r\n", listLength(server.clients)-listLength(server.slaves), lol, bib, server.bpop_blocked_clients); } /* Memory */ if (allsections || defsections || !strcasecmp(section,"memory")) { char hmem[64]; char peak_hmem[64]; size_t zmalloc_used = zmalloc_used_memory(); /* Peak memory is updated from time to time by serverCron() so it * may happen that the instantaneous value is slightly bigger than * the peak value. This may confuse users, so we update the peak * if found smaller than the current memory usage. */ if (zmalloc_used > server.stat_peak_memory) server.stat_peak_memory = zmalloc_used; bytesToHuman(hmem,zmalloc_used); bytesToHuman(peak_hmem,server.stat_peak_memory); if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Memory\r\n" "used_memory:%zu\r\n" "used_memory_human:%s\r\n" "used_memory_rss:%zu\r\n" "used_memory_peak:%zu\r\n" "used_memory_peak_human:%s\r\n" "used_memory_lua:%lld\r\n" "mem_fragmentation_ratio:%.2f\r\n" "mem_allocator:%s\r\n", zmalloc_used, hmem, server.resident_set_size, server.stat_peak_memory, peak_hmem, ((long long)lua_gc(server.lua,LUA_GCCOUNT,0))*1024LL, zmalloc_get_fragmentation_ratio(server.resident_set_size), ZMALLOC_LIB ); } /* Persistence */ if (allsections || defsections || !strcasecmp(section,"persistence")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Persistence\r\n" "loading:%d\r\n" "rdb_changes_since_last_save:%lld\r\n" "rdb_bgsave_in_progress:%d\r\n" "rdb_last_save_time:%jd\r\n" "rdb_last_bgsave_status:%s\r\n" "rdb_last_bgsave_time_sec:%jd\r\n" "rdb_current_bgsave_time_sec:%jd\r\n" "aof_enabled:%d\r\n" "aof_rewrite_in_progress:%d\r\n" "aof_rewrite_scheduled:%d\r\n" "aof_last_rewrite_time_sec:%jd\r\n" "aof_current_rewrite_time_sec:%jd\r\n" "aof_last_bgrewrite_status:%s\r\n" "aof_last_write_status:%s\r\n", server.loading, server.dirty, server.rdb_child_pid != -1, (intmax_t)server.lastsave, (server.lastbgsave_status == REDIS_OK) ? "ok" : "err", (intmax_t)server.rdb_save_time_last, (intmax_t)((server.rdb_child_pid == -1) ? -1 : time(NULL)-server.rdb_save_time_start), server.aof_state != REDIS_AOF_OFF, server.aof_child_pid != -1, server.aof_rewrite_scheduled, (intmax_t)server.aof_rewrite_time_last, (intmax_t)((server.aof_child_pid == -1) ? -1 : time(NULL)-server.aof_rewrite_time_start), (server.aof_lastbgrewrite_status == REDIS_OK) ? "ok" : "err", (server.aof_last_write_status == REDIS_OK) ? "ok" : "err"); if (server.aof_state != REDIS_AOF_OFF) { info = sdscatprintf(info, "aof_current_size:%lld\r\n" "aof_base_size:%lld\r\n" "aof_pending_rewrite:%d\r\n" "aof_buffer_length:%zu\r\n" "aof_rewrite_buffer_length:%lu\r\n" "aof_pending_bio_fsync:%llu\r\n" "aof_delayed_fsync:%lu\r\n", (long long) server.aof_current_size, (long long) server.aof_rewrite_base_size, server.aof_rewrite_scheduled, sdslen(server.aof_buf), aofRewriteBufferSize(), bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC), server.aof_delayed_fsync); } if (server.loading) { double perc; time_t eta, elapsed; off_t remaining_bytes = server.loading_total_bytes- server.loading_loaded_bytes; perc = ((double)server.loading_loaded_bytes / (server.loading_total_bytes+1)) * 100; elapsed = time(NULL)-server.loading_start_time; if (elapsed == 0) { eta = 1; /* A fake 1 second figure if we don't have enough info */ } else { eta = (elapsed*remaining_bytes)/(server.loading_loaded_bytes+1); } info = sdscatprintf(info, "loading_start_time:%jd\r\n" "loading_total_bytes:%llu\r\n" "loading_loaded_bytes:%llu\r\n" "loading_loaded_perc:%.2f\r\n" "loading_eta_seconds:%jd\r\n", (intmax_t) server.loading_start_time, (unsigned long long) server.loading_total_bytes, (unsigned long long) server.loading_loaded_bytes, perc, (intmax_t)eta ); } } /* Stats */ if (allsections || defsections || !strcasecmp(section,"stats")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Stats\r\n" "total_connections_received:%lld\r\n" "total_commands_processed:%lld\r\n" "instantaneous_ops_per_sec:%lld\r\n" "total_net_input_bytes:%lld\r\n" "total_net_output_bytes:%lld\r\n" "instantaneous_input_kbps:%.2f\r\n" "instantaneous_output_kbps:%.2f\r\n" "rejected_connections:%lld\r\n" "sync_full:%lld\r\n" "sync_partial_ok:%lld\r\n" "sync_partial_err:%lld\r\n" "expired_keys:%lld\r\n" "evicted_keys:%lld\r\n" "keyspace_hits:%lld\r\n" "keyspace_misses:%lld\r\n" "pubsub_channels:%ld\r\n" "pubsub_patterns:%lu\r\n" "latest_fork_usec:%lld\r\n" "migrate_cached_sockets:%ld\r\n", server.stat_numconnections, server.stat_numcommands, getInstantaneousMetric(REDIS_METRIC_COMMAND), server.stat_net_input_bytes, server.stat_net_output_bytes, (float)getInstantaneousMetric(REDIS_METRIC_NET_INPUT)/1024, (float)getInstantaneousMetric(REDIS_METRIC_NET_OUTPUT)/1024, server.stat_rejected_conn, server.stat_sync_full, server.stat_sync_partial_ok, server.stat_sync_partial_err, server.stat_expiredkeys, server.stat_evictedkeys, server.stat_keyspace_hits, server.stat_keyspace_misses, dictSize(server.pubsub_channels), listLength(server.pubsub_patterns), server.stat_fork_time, dictSize(server.migrate_cached_sockets)); } /* Replication */ if (allsections || defsections || !strcasecmp(section,"replication")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Replication\r\n" "role:%s\r\n", server.masterhost == NULL ? "master" : "slave"); if (server.masterhost) { long long slave_repl_offset = 1; if (server.master) slave_repl_offset = server.master->reploff; else if (server.cached_master) slave_repl_offset = server.cached_master->reploff; info = sdscatprintf(info, "master_host:%s\r\n" "master_port:%d\r\n" "master_link_status:%s\r\n" "master_last_io_seconds_ago:%d\r\n" "master_sync_in_progress:%d\r\n" "slave_repl_offset:%lld\r\n" ,server.masterhost, server.masterport, (server.repl_state == REDIS_REPL_CONNECTED) ? "up" : "down", server.master ? ((int)(server.unixtime-server.master->lastinteraction)) : -1, server.repl_state == REDIS_REPL_TRANSFER, slave_repl_offset ); if (server.repl_state == REDIS_REPL_TRANSFER) { info = sdscatprintf(info, "master_sync_left_bytes:%lld\r\n" "master_sync_last_io_seconds_ago:%d\r\n" , (long long) (server.repl_transfer_size - server.repl_transfer_read), (int)(server.unixtime-server.repl_transfer_lastio) ); } if (server.repl_state != REDIS_REPL_CONNECTED) { info = sdscatprintf(info, "master_link_down_since_seconds:%jd\r\n", (intmax_t)server.unixtime-server.repl_down_since); } info = sdscatprintf(info, "slave_priority:%d\r\n" "slave_read_only:%d\r\n", server.slave_priority, server.repl_slave_ro); } info = sdscatprintf(info, "connected_slaves:%lu\r\n", listLength(server.slaves)); /* If min-slaves-to-write is active, write the number of slaves * currently considered 'good'. */ if (server.repl_min_slaves_to_write && server.repl_min_slaves_max_lag) { info = sdscatprintf(info, "min_slaves_good_slaves:%d\r\n", server.repl_good_slaves_count); } if (listLength(server.slaves)) { int slaveid = 0; listNode *ln; listIter li; listRewind(server.slaves,&li); while((ln = listNext(&li))) { redisClient *slave = listNodeValue(ln); char *state = NULL; char ip[REDIS_IP_STR_LEN]; int port; long lag = 0; if (anetPeerToString(slave->fd,ip,sizeof(ip),&port) == -1) continue; switch(slave->replstate) { case REDIS_REPL_WAIT_BGSAVE_START: case REDIS_REPL_WAIT_BGSAVE_END: state = "wait_bgsave"; break; case REDIS_REPL_SEND_BULK: state = "send_bulk"; break; case REDIS_REPL_ONLINE: state = "online"; break; } if (state == NULL) continue; if (slave->replstate == REDIS_REPL_ONLINE) lag = time(NULL) - slave->repl_ack_time; info = sdscatprintf(info, "slave%d:ip=%s,port=%d,state=%s," "offset=%lld,lag=%ld\r\n", slaveid,ip,slave->slave_listening_port,state, slave->repl_ack_off, lag); slaveid++; } } info = sdscatprintf(info, "master_repl_offset:%lld\r\n" "repl_backlog_active:%d\r\n" "repl_backlog_size:%lld\r\n" "repl_backlog_first_byte_offset:%lld\r\n" "repl_backlog_histlen:%lld\r\n", server.master_repl_offset, server.repl_backlog != NULL, server.repl_backlog_size, server.repl_backlog_off, server.repl_backlog_histlen); } /* CPU */ if (allsections || defsections || !strcasecmp(section,"cpu")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# CPU\r\n" "used_cpu_sys:%.2f\r\n" "used_cpu_user:%.2f\r\n" "used_cpu_sys_children:%.2f\r\n" "used_cpu_user_children:%.2f\r\n", (float)self_ru.ru_stime.tv_sec+(float)self_ru.ru_stime.tv_usec/1000000, (float)self_ru.ru_utime.tv_sec+(float)self_ru.ru_utime.tv_usec/1000000, (float)c_ru.ru_stime.tv_sec+(float)c_ru.ru_stime.tv_usec/1000000, (float)c_ru.ru_utime.tv_sec+(float)c_ru.ru_utime.tv_usec/1000000); } /* cmdtime */ if (allsections || !strcasecmp(section,"commandstats")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Commandstats\r\n"); numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand); for (j = 0; j < numcommands; j++) { struct redisCommand *c = redisCommandTable+j; if (!c->calls) continue; info = sdscatprintf(info, "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n", c->name, c->calls, c->microseconds, (c->calls == 0) ? 0 : ((float)c->microseconds/c->calls)); } } /* Cluster */ if (allsections || defsections || !strcasecmp(section,"cluster")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Cluster\r\n" "cluster_enabled:%d\r\n", server.cluster_enabled); } /* Key space */ if (allsections || defsections || !strcasecmp(section,"keyspace")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Keyspace\r\n"); for (j = 0; j < server.dbnum; j++) { long long keys, vkeys; keys = dictSize(server.db[j].dict); vkeys = dictSize(server.db[j].expires); if (keys || vkeys) { info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld,avg_ttl=%lld\r\n", j, keys, vkeys, server.db[j].avg_ttl); } } } return info; } void infoCommand(redisClient *c) { char *section = c->argc == 2 ? c->argv[1]->ptr : "default"; if (c->argc > 2) { addReply(c,shared.syntaxerr); return; } sds info = genRedisInfoString(section); addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n", (unsigned long)sdslen(info))); addReplySds(c,info); addReply(c,shared.crlf); } void monitorCommand(redisClient *c) { /* ignore MONITOR if already slave or in monitor mode */ if (c->flags & REDIS_SLAVE) return; c->flags |= (REDIS_SLAVE|REDIS_MONITOR); listAddNodeTail(server.monitors,c); addReply(c,shared.ok); } /* ============================ Maxmemory directive ======================== */ /* freeMemoryIfNeeded() gets called when 'maxmemory' is set on the config * file to limit the max memory used by the server, before processing a * command. * * The goal of the function is to free enough memory to keep Redis under the * configured memory limit. * * The function starts calculating how many bytes should be freed to keep * Redis under the limit, and enters a loop selecting the best keys to * evict accordingly to the configured policy. * * If all the bytes needed to return back under the limit were freed the * function returns REDIS_OK, otherwise REDIS_ERR is returned, and the caller * should block the execution of commands that will result in more memory * used by the server. * * ------------------------------------------------------------------------ * * LRU approximation algorithm * * Redis uses an approximation of the LRU algorithm that runs in constant * memory. Every time there is a key to expire, we sample N keys (with * N very small, usually in around 5) to populate a pool of best keys to * evict of M keys (the pool size is defined by REDIS_EVICTION_POOL_SIZE). * * The N keys sampled are added in the pool of good keys to expire (the one * with an old access time) if they are better than one of the current keys * in the pool. * * After the pool is populated, the best key we have in the pool is expired. * However note that we don't remove keys from the pool when they are deleted * so the pool may contain keys that no longer exist. * * When we try to evict a key, and all the entries in the pool don't exist * we populate it again. This time we'll be sure that the pool has at least * one key that can be evicted, if there is at least one key that can be * evicted in the whole database. */ /* Create a new eviction pool. */ struct evictionPoolEntry *evictionPoolAlloc(void) { struct evictionPoolEntry *ep; int j; ep = zmalloc(sizeof(*ep)*REDIS_EVICTION_POOL_SIZE); for (j = 0; j < REDIS_EVICTION_POOL_SIZE; j++) { ep[j].idle = 0; ep[j].key = NULL; } return ep; } /* This is an helper function for freeMemoryIfNeeded(), it is used in order * to populate the evictionPool with a few entries every time we want to * expire a key. Keys with idle time smaller than one of the current * keys are added. Keys are always added if there are free entries. * * We insert keys on place in ascending order, so keys with the smaller * idle time are on the left, and keys with the higher idle time on the * right. */ #define EVICTION_SAMPLES_ARRAY_SIZE 16 void evictionPoolPopulate(dict *sampledict, dict *keydict, struct evictionPoolEntry *pool) { int j, k, count; dictEntry *_samples[EVICTION_SAMPLES_ARRAY_SIZE]; dictEntry **samples; /* Try to use a static buffer: this function is a big hit... * Note: it was actually measured that this helps. */ if (server.maxmemory_samples <= EVICTION_SAMPLES_ARRAY_SIZE) { samples = _samples; } else { samples = zmalloc(sizeof(samples[0])*server.maxmemory_samples); } count = dictGetSomeKeys(sampledict,samples,server.maxmemory_samples); for (j = 0; j < count; j++) { unsigned long long idle; sds key; robj *o; dictEntry *de; de = samples[j]; key = dictGetKey(de); /* If the dictionary we are sampling from is not the main * dictionary (but the expires one) we need to lookup the key * again in the key dictionary to obtain the value object. */ if (sampledict != keydict) de = dictFind(keydict, key); o = dictGetVal(de); idle = estimateObjectIdleTime(o); /* Insert the element inside the pool. * First, find the first empty bucket or the first populated * bucket that has an idle time smaller than our idle time. */ k = 0; while (k < REDIS_EVICTION_POOL_SIZE && pool[k].key && pool[k].idle < idle) k++; if (k == 0 && pool[REDIS_EVICTION_POOL_SIZE-1].key != NULL) { /* Can't insert if the element is < the worst element we have * and there are no empty buckets. */ continue; } else if (k < REDIS_EVICTION_POOL_SIZE && pool[k].key == NULL) { /* Inserting into empty position. No setup needed before insert. */ } else { /* Inserting in the middle. Now k points to the first element * greater than the element to insert. */ if (pool[REDIS_EVICTION_POOL_SIZE-1].key == NULL) { /* Free space on the right? Insert at k shifting * all the elements from k to end to the right. */ memmove(pool+k+1,pool+k, sizeof(pool[0])*(REDIS_EVICTION_POOL_SIZE-k-1)); } else { /* No free space on right? Insert at k-1 */ k--; /* Shift all elements on the left of k (included) to the * left, so we discard the element with smaller idle time. */ sdsfree(pool[0].key); memmove(pool,pool+1,sizeof(pool[0])*k); } } pool[k].key = sdsdup(key); pool[k].idle = idle; } if (samples != _samples) zfree(samples); } int freeMemoryIfNeeded(void) { size_t mem_used, mem_tofree, mem_freed; int slaves = listLength(server.slaves); mstime_t latency, eviction_latency; /* Remove the size of slaves output buffers and AOF buffer from the * count of used memory. */ mem_used = zmalloc_used_memory(); if (slaves) { listIter li; listNode *ln; listRewind(server.slaves,&li); while((ln = listNext(&li))) { redisClient *slave = listNodeValue(ln); unsigned long obuf_bytes = getClientOutputBufferMemoryUsage(slave); if (obuf_bytes > mem_used) mem_used = 0; else mem_used -= obuf_bytes; } } if (server.aof_state != REDIS_AOF_OFF) { mem_used -= sdslen(server.aof_buf); mem_used -= aofRewriteBufferSize(); } /* Check if we are over the memory limit. */ if (mem_used <= server.maxmemory) return REDIS_OK; if (server.maxmemory_policy == REDIS_MAXMEMORY_NO_EVICTION) return REDIS_ERR; /* We need to free memory, but policy forbids. */ /* Compute how much memory we need to free. */ mem_tofree = mem_used - server.maxmemory; mem_freed = 0; latencyStartMonitor(latency); while (mem_freed < mem_tofree) { int j, k, keys_freed = 0; for (j = 0; j < server.dbnum; j++) { long bestval = 0; /* just to prevent warning */ sds bestkey = NULL; dictEntry *de; redisDb *db = server.db+j; dict *dict; if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU || server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM) { dict = server.db[j].dict; } else { dict = server.db[j].expires; } if (dictSize(dict) == 0) continue; /* volatile-random and allkeys-random policy */ if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM || server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_RANDOM) { de = dictGetRandomKey(dict); bestkey = dictGetKey(de); } /* volatile-lru and allkeys-lru policy */ else if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU || server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU) { struct evictionPoolEntry *pool = db->eviction_pool; while(bestkey == NULL) { evictionPoolPopulate(dict, db->dict, db->eviction_pool); /* Go backward from best to worst element to evict. */ for (k = REDIS_EVICTION_POOL_SIZE-1; k >= 0; k--) { if (pool[k].key == NULL) continue; de = dictFind(dict,pool[k].key); /* Remove the entry from the pool. */ sdsfree(pool[k].key); /* Shift all elements on its right to left. */ memmove(pool+k,pool+k+1, sizeof(pool[0])*(REDIS_EVICTION_POOL_SIZE-k-1)); /* Clear the element on the right which is empty * since we shifted one position to the left. */ pool[REDIS_EVICTION_POOL_SIZE-1].key = NULL; pool[REDIS_EVICTION_POOL_SIZE-1].idle = 0; /* If the key exists, is our pick. Otherwise it is * a ghost and we need to try the next element. */ if (de) { bestkey = dictGetKey(de); break; } else { /* Ghost... */ continue; } } } } /* volatile-ttl */ else if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_TTL) { for (k = 0; k < server.maxmemory_samples; k++) { sds thiskey; long thisval; de = dictGetRandomKey(dict); thiskey = dictGetKey(de); thisval = (long) dictGetVal(de); /* Expire sooner (minor expire unix timestamp) is better * candidate for deletion */ if (bestkey == NULL || thisval < bestval) { bestkey = thiskey; bestval = thisval; } } } /* Finally remove the selected key. */ if (bestkey) { long long delta; robj *keyobj = createStringObject(bestkey,sdslen(bestkey)); propagateExpire(db,keyobj); /* We compute the amount of memory freed by dbDelete() alone. * It is possible that actually the memory needed to propagate * the DEL in AOF and replication link is greater than the one * we are freeing removing the key, but we can't account for * that otherwise we would never exit the loop. * * AOF and Output buffer memory will be freed eventually so * we only care about memory used by the key space. */ delta = (long long) zmalloc_used_memory(); latencyStartMonitor(eviction_latency); dbDelete(db,keyobj); latencyEndMonitor(eviction_latency); latencyAddSampleIfNeeded("eviction-del",eviction_latency); latencyRemoveNestedEvent(latency,eviction_latency); delta -= (long long) zmalloc_used_memory(); mem_freed += delta; server.stat_evictedkeys++; notifyKeyspaceEvent(REDIS_NOTIFY_EVICTED, "evicted", keyobj, db->id); decrRefCount(keyobj); keys_freed++; /* When the memory to free starts to be big enough, we may * start spending so much time here that is impossible to * deliver data to the slaves fast enough, so we force the * transmission here inside the loop. */ if (slaves) flushSlavesOutputBuffers(); } } if (!keys_freed) { latencyEndMonitor(latency); latencyAddSampleIfNeeded("eviction-cycle",latency); return REDIS_ERR; /* nothing to free... */ } } latencyEndMonitor(latency); latencyAddSampleIfNeeded("eviction-cycle",latency); return REDIS_OK; } /* =================================== Main! ================================ */ #ifdef __linux__ int linuxOvercommitMemoryValue(void) { FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r"); char buf[64]; if (!fp) return -1; if (fgets(buf,64,fp) == NULL) { fclose(fp); return -1; } fclose(fp); return atoi(buf); } void linuxMemoryWarnings(void) { if (linuxOvercommitMemoryValue() == 0) { redisLog(REDIS_WARNING,"WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect."); } if (THPIsEnabled()) { redisLog(REDIS_WARNING,"WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled."); } } #endif /* __linux__ */ void createPidFile(void) { /* Try to write the pid file in a best-effort way. */ FILE *fp = fopen(server.pidfile,"w"); if (fp) { fprintf(fp,"%d\n",(int)getpid()); fclose(fp); } } void daemonize(void) { int fd; if (fork() != 0) exit(0); /* parent exits */ setsid(); /* create a new session */ /* Every output goes to /dev/null. If Redis is daemonized but * the 'logfile' is set to 'stdout' in the configuration file * it will not log at all. */ if ((fd = open("/dev/null", O_RDWR, 0)) != -1) { dup2(fd, STDIN_FILENO); dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); if (fd > STDERR_FILENO) close(fd); } } void version(void) { printf("Redis server v=%s sha=%s:%d malloc=%s bits=%d build=%llx\n", REDIS_VERSION, redisGitSHA1(), atoi(redisGitDirty()) > 0, ZMALLOC_LIB, sizeof(long) == 4 ? 32 : 64, (unsigned long long) redisBuildId()); exit(0); } void usage(void) { fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf] [options]\n"); fprintf(stderr," ./redis-server - (read config from stdin)\n"); fprintf(stderr," ./redis-server -v or --version\n"); fprintf(stderr," ./redis-server -h or --help\n"); fprintf(stderr," ./redis-server --test-memory <megabytes>\n\n"); fprintf(stderr,"Examples:\n"); fprintf(stderr," ./redis-server (run the server with default conf)\n"); fprintf(stderr," ./redis-server /etc/redis/6379.conf\n"); fprintf(stderr," ./redis-server --port 7777\n"); fprintf(stderr," ./redis-server --port 7777 --slaveof 127.0.0.1 8888\n"); fprintf(stderr," ./redis-server /etc/myredis.conf --loglevel verbose\n\n"); fprintf(stderr,"Sentinel mode:\n"); fprintf(stderr," ./redis-server /etc/sentinel.conf --sentinel\n"); exit(1); } void redisAsciiArt(void) { #include "asciilogo.h" char *buf = zmalloc(1024*16); char *mode; if (server.cluster_enabled) mode = "cluster"; else if (server.sentinel_mode) mode = "sentinel"; else mode = "standalone"; if (server.syslog_enabled) { redisLog(REDIS_NOTICE, "Redis %s (%s/%d) %s bit, %s mode, port %d, pid %ld ready to start.", REDIS_VERSION, redisGitSHA1(), strtol(redisGitDirty(),NULL,10) > 0, (sizeof(long) == 8) ? "64" : "32", mode, server.port, (long) getpid() ); } else { snprintf(buf,1024*16,ascii_logo, REDIS_VERSION, redisGitSHA1(), strtol(redisGitDirty(),NULL,10) > 0, (sizeof(long) == 8) ? "64" : "32", mode, server.port, (long) getpid() ); redisLogRaw(REDIS_NOTICE|REDIS_LOG_RAW,buf); } zfree(buf); } static void sigShutdownHandler(int sig) { char *msg; switch (sig) { case SIGINT: msg = "Received SIGINT scheduling shutdown..."; break; case SIGTERM: msg = "Received SIGTERM scheduling shutdown..."; break; default: msg = "Received shutdown signal, scheduling shutdown..."; }; /* SIGINT is often delivered via Ctrl+C in an interactive session. * If we receive the signal the second time, we interpret this as * the user really wanting to quit ASAP without waiting to persist * on disk. */ if (server.shutdown_asap && sig == SIGINT) { redisLogFromHandler(REDIS_WARNING, "You insist... exiting now."); rdbRemoveTempFile(getpid()); exit(1); /* Exit with an error since this was not a clean shutdown. */ } else if (server.loading) { exit(0); } redisLogFromHandler(REDIS_WARNING, msg); server.shutdown_asap = 1; } void setupSignalHandlers(void) { struct sigaction act; /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used. * Otherwise, sa_handler is used. */ sigemptyset(&act.sa_mask); act.sa_flags = 0; act.sa_handler = sigShutdownHandler; sigaction(SIGTERM, &act, NULL); sigaction(SIGINT, &act, NULL); #ifdef HAVE_BACKTRACE sigemptyset(&act.sa_mask); act.sa_flags = SA_NODEFER | SA_RESETHAND | SA_SIGINFO; act.sa_sigaction = sigsegvHandler; sigaction(SIGSEGV, &act, NULL); sigaction(SIGBUS, &act, NULL); sigaction(SIGFPE, &act, NULL); sigaction(SIGILL, &act, NULL); #endif return; } void memtest(size_t megabytes, int passes); /* Returns 1 if there is --sentinel among the arguments or if * argv[0] is exactly "redis-sentinel". */ int checkForSentinelMode(int argc, char **argv) { int j; if (strstr(argv[0],"redis-sentinel") != NULL) return 1; for (j = 1; j < argc; j++) if (!strcmp(argv[j],"--sentinel")) return 1; return 0; } /* Function called at startup to load RDB or AOF file in memory. */ void loadDataFromDisk(void) { long long start = ustime(); if (server.aof_state == REDIS_AOF_ON) { if (loadAppendOnlyFile(server.aof_filename) == REDIS_OK) redisLog(REDIS_NOTICE,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start)/1000000); } else { if (rdbLoad(server.rdb_filename) == REDIS_OK) { redisLog(REDIS_NOTICE,"DB loaded from disk: %.3f seconds", (float)(ustime()-start)/1000000); } else if (errno != ENOENT) { redisLog(REDIS_WARNING,"Fatal error loading the DB: %s. Exiting.",strerror(errno)); exit(1); } } } void redisOutOfMemoryHandler(size_t allocation_size) { redisLog(REDIS_WARNING,"Out Of Memory allocating %zu bytes!", allocation_size); redisPanic("Redis aborting for OUT OF MEMORY"); } void redisSetProcTitle(char *title) { #ifdef USE_SETPROCTITLE char *server_mode = ""; if (server.cluster_enabled) server_mode = " [cluster]"; else if (server.sentinel_mode) server_mode = " [sentinel]"; setproctitle("%s %s:%d%s", title, server.bindaddr_count ? server.bindaddr[0] : "*", server.port, server_mode); #else REDIS_NOTUSED(title); #endif } int main(int argc, char **argv) { struct timeval tv; /* We need to initialize our libraries, and the server configuration. */ #ifdef INIT_SETPROCTITLE_REPLACEMENT spt_init(argc, argv); #endif setlocale(LC_COLLATE,""); zmalloc_enable_thread_safeness(); zmalloc_set_oom_handler(redisOutOfMemoryHandler); srand(time(NULL)^getpid()); gettimeofday(&tv,NULL); dictSetHashFunctionSeed(tv.tv_sec^tv.tv_usec^getpid()); server.sentinel_mode = checkForSentinelMode(argc,argv); initServerConfig(); /* We need to init sentinel right now as parsing the configuration file * in sentinel mode will have the effect of populating the sentinel * data structures with master nodes to monitor. */ if (server.sentinel_mode) { initSentinelConfig(); initSentinel(); } if (argc >= 2) { int j = 1; /* First option to parse in argv[] */ sds options = sdsempty(); char *configfile = NULL; /* Handle special options --help and --version */ if (strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--version") == 0) version(); if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) usage(); if (strcmp(argv[1], "--test-memory") == 0) { if (argc == 3) { memtest(atoi(argv[2]),50); exit(0); } else { fprintf(stderr,"Please specify the amount of memory to test in megabytes.\n"); fprintf(stderr,"Example: ./redis-server --test-memory 4096\n\n"); exit(1); } } /* First argument is the config file name? */ if (argv[j][0] != '-' || argv[j][1] != '-') configfile = argv[j++]; /* All the other options are parsed and conceptually appended to the * configuration file. For instance --port 6380 will generate the * string "port 6380\n" to be parsed after the actual file name * is parsed, if any. */ while(j != argc) { if (argv[j][0] == '-' && argv[j][1] == '-') { /* Option name */ if (sdslen(options)) options = sdscat(options,"\n"); options = sdscat(options,argv[j]+2); options = sdscat(options," "); } else { /* Option argument */ options = sdscatrepr(options,argv[j],strlen(argv[j])); options = sdscat(options," "); } j++; } if (server.sentinel_mode && configfile && *configfile == '-') { redisLog(REDIS_WARNING, "Sentinel config from STDIN not allowed."); redisLog(REDIS_WARNING, "Sentinel needs config file on disk to save state. Exiting..."); exit(1); } if (configfile) server.configfile = getAbsolutePath(configfile); resetServerSaveParams(); loadServerConfig(configfile,options); sdsfree(options); } else { redisLog(REDIS_WARNING, "Warning: no config file specified, using the default config. In order to specify a config file use %s /path/to/%s.conf", argv[0], server.sentinel_mode ? "sentinel" : "redis"); } if (server.daemonize) daemonize(); initServer(); if (server.daemonize) createPidFile(); redisSetProcTitle(argv[0]); redisAsciiArt(); checkTcpBacklogSettings(); if (!server.sentinel_mode) { /* Things not needed when running in Sentinel mode. */ redisLog(REDIS_WARNING,"Server started, Redis version " REDIS_VERSION); #ifdef __linux__ linuxMemoryWarnings(); #endif loadDataFromDisk(); if (server.cluster_enabled) { if (verifyClusterConfigWithData() == REDIS_ERR) { redisLog(REDIS_WARNING, "You can't have keys in a DB different than DB 0 when in " "Cluster mode. Exiting."); exit(1); } } if (server.ipfd_count > 0) redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port); if (server.sofd > 0) redisLog(REDIS_NOTICE,"The server is now ready to accept connections at %s", server.unixsocket); } else { sentinelIsRunning(); } /* Warning the user about suspicious maxmemory setting. */ if (server.maxmemory > 0 && server.maxmemory < 1024*1024) { redisLog(REDIS_WARNING,"WARNING: You specified a maxmemory value that is less than 1MB (current value is %llu bytes). Are you sure this is what you really want?", server.maxmemory); } aeSetBeforeSleepProc(server.el,beforeSleep); aeMain(server.el); aeDeleteEventLoop(server.el); return 0; } /* The End */
grepmusic/redis_sorted_set_with_prefix_in_query_for_feed
src/redis.c
C
bsd-3-clause
149,079
from traitlets import Unicode, Bool from textwrap import dedent from .. import utils from . import NbGraderPreprocessor class ClearSolutions(NbGraderPreprocessor): code_stub = Unicode( "# YOUR CODE HERE\nraise NotImplementedError()", config=True, help="The code snippet that will replace code solutions") text_stub = Unicode( "YOUR ANSWER HERE", config=True, help="The text snippet that will replace written solutions") comment_mark = Unicode( "#", config=True, help="The comment mark to prefix solution delimiters") begin_solution_delimeter = Unicode( "## BEGIN SOLUTION", config=True, help="The delimiter marking the beginning of a solution (excluding comment mark)") end_solution_delimeter = Unicode( "## END SOLUTION", config=True, help="The delimiter marking the end of a solution (excluding comment mark)") enforce_metadata = Bool( True, config=True, help=dedent( """ Whether or not to complain if cells containing solutions regions are not marked as solution cells. WARNING: this will potentially cause things to break if you are using the full nbgrader pipeline. ONLY disable this option if you are only ever planning to use nbgrader assign. """ ) ) @property def begin_solution(self): return "{}{}".format(self.comment_mark, self.begin_solution_delimeter) @property def end_solution(self): return "{}{}".format(self.comment_mark, self.end_solution_delimeter) def _replace_solution_region(self, cell): """Find a region in the cell that is delimeted by `self.begin_solution` and `self.end_solution` (e.g. ### BEGIN SOLUTION and ### END SOLUTION). Replace that region either with the code stub or text stub, depending the cell type. This modifies the cell in place, and then returns True if a solution region was replaced, and False otherwise. """ # pull out the cell input/source lines = cell.source.split("\n") if cell.cell_type == "code": stub_lines = self.code_stub.split("\n") else: stub_lines = self.text_stub.split("\n") new_lines = [] in_solution = False replaced_solution = False for line in lines: # begin the solution area if line.strip() == self.begin_solution: # check to make sure this isn't a nested BEGIN # SOLUTION region if in_solution: raise RuntimeError( "encountered nested begin solution statements") in_solution = True replaced_solution = True # replace it with the stub, indented as necessary indent = line[:line.find(self.begin_solution)] for stub_line in stub_lines: new_lines.append(indent + stub_line) # end the solution area elif line.strip() == self.end_solution: in_solution = False # add lines as long as it's not in the solution area elif not in_solution: new_lines.append(line) # we finished going through all the lines, but didn't find a # matching END SOLUTION statment if in_solution: raise RuntimeError("no end solution statement found") # replace the cell source cell.source = "\n".join(new_lines) return replaced_solution def preprocess(self, nb, resources): nb, resources = super(ClearSolutions, self).preprocess(nb, resources) if 'celltoolbar' in nb.metadata: del nb.metadata['celltoolbar'] return nb, resources def preprocess_cell(self, cell, resources, cell_index): # replace solution regions with the relevant stubs replaced_solution = self._replace_solution_region(cell) # determine whether the cell is a solution/grade cell is_solution = utils.is_solution(cell) # check that it is marked as a solution cell if we replaced a solution # region -- if it's not, then this is a problem, because the cell needs # to be given an id if not is_solution and replaced_solution: if self.enforce_metadata: raise RuntimeError( "Solution region detected in a non-solution cell; please make sure " "all solution regions are within solution cells." ) # replace solution cells with the code/text stub -- but not if # we already replaced a solution region, because that means # there are parts of the cells that should be preserved if is_solution and not replaced_solution: if cell.cell_type == 'code': cell.source = self.code_stub else: cell.source = self.text_stub return cell, resources
EdwardJKim/nbgrader
nbgrader/preprocessors/clearsolutions.py
Python
bsd-3-clause
5,142
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; use yii\helpers\ArrayHelper; use kartik\widgets\Select2; // Add upload use yii\helpers\Url; use kartik\widgets\TypeaheadBasic; use kartik\widgets\FileInput; use yii\helpers\VarDumper; use frontend\modules\labstore\models\Labgroup; /* @var $this yii\web\View */ /* @var $model frontend\modules\labstore\models\Labstore */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="sqlscript-form"> <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?> <div class="row"> <div class="col-md-2 col-xs-12"> <?= $form->field($model, 'hn')->textInput(['maxlength' => true]) ?> </div> <div class="col-md-2 col-xs-12"> <?= $form->field($model, 'lab_number')->textInput(['maxlength' => true]) ?> </div> <div class="col-md-2 col-xs-12"> <?= $form->field($model, 'lab_group_id')->widget(Select2::classname(), [ 'data' => ArrayHelper::map(Labgroup::find()->all(), 'lab_group_id', 'lab_group_name'), 'options' => ['placeholder' => 'เลือก..'], 'pluginOptions' => [ 'allowClear' => true ], ]); ?> </div> <div class="col-md-6 col-xs-12"> <?= $form->field($model, 'note')->textInput(['maxlength' => true]) ?> </div> </div> <div class="row"> <div class="col-md-12 col-xs-12"> <?= $form->field($model, 'file')->widget(FileInput::classname(), [ //'options' => ['accept' => 'image/*'], 'pluginOptions' => [ 'initialPreview' => empty($model->file) ? [] : [ Yii::getAlias('@web') . '/labstore/' . $model->file, ], 'allowedFileExtensions' => ['pdf'], 'showPreview' => false, 'showCaption' => true, 'showRemove' => true, 'showUpload' => false ] ]); ?> <p class="help-block"> กฎการตั้งชื่อ ไฟล์ต้องเป็นภาษาอังกฤษตัวพิมพ์เล็กผสมตัวเลขเท่านั้น รูปแบบ : lab_hn_labordernumber ( HN เป็นเลข 7 หลัก , LABORDER NUMBER เป็นเลขที่สั่งแลป ) ตั้งชื่อไฟล์ ตามรูปแบบที่กำหนด (เช่น lab_0000001_1234) รองรับนามสกุล pdf ขนาดไม่เกิน 1 MB </p> </div> </div> <div class="form-group"> <?= Html::submitButton('<i class="glyphicon glyphicon-save"></i> ' . ($model->isNewRecord ? 'จัดเก็บไฟล์' : 'ปรับปรุง'), ['class' => ($model->isNewRecord ? 'btn btn-success' : 'btn btn-primary') . ' btn-lg btn-block']) ?> </div> <?php ActiveForm::end(); ?> </div>
jingjoe/hmis
frontend/modules/labstore/views/labstore/_form.php
PHP
bsd-3-clause
3,159
# coding: utf-8 module Fig; end class Fig::Command; end # One of the main activities Fig should do as part of the current run. # # This exists because the code used to have complicated logic about whether a # package.fig should be read, whether the Package object should be loaded, # should a config be applied, when should some activity happen, etc. Now, we # let the Action object say what it wants in terms of setup and then tell it to # do whatever it needs to. module Fig::Command::Action EXIT_SUCCESS = 0 EXIT_FAILURE = 1 attr_writer :execution_context def primary_option() return options()[0] end def options() raise NotImplementedError end # Is this a special Action that should just be run on its own without looking # at other Actions? Note that anything that returns true won't get an # execution context. def execute_immediately_after_command_line_parse? return false end def descriptor_requirement() raise NotImplementedError end def allow_both_descriptor_and_file?() return false end # Does the action care about command-line options that affect package # contents, i.e. --resource/--archive? def cares_about_asset_options?() return false end def modifies_repository?() raise NotImplementedError end def prepare_repository(repository) return # Nothing by default. end def load_base_package?() raise NotImplementedError end def base_package_can_come_from_descriptor?() return true end # true, false, or nil if don't care. def register_base_package?() raise NotImplementedError end # true, false, or nil if don't care. def apply_config?() raise NotImplementedError end # true, false, or nil if don't care. def apply_base_config?() raise NotImplementedError end def remote_operation_necessary?() return false end def retrieves_should_happen?() return false end # Is this --list-dependencies? def list_dependencies?() return false end # Is this --list-variables? def list_variables?() return false end # Is this a publish action? def publish?() return false end # Answers whether we should reset the environment to nothing, sort of like # the standardized environment that cron(1) creates. At present, we're only # setting this when we're listing variables. One could imagine allowing this # to be set by a command-line option in general; if we do this, the # RuntimeEnvironment class will need to be changed to support deletion of # values from ENV. def reset_environment?() return false end # Slurp data out of command-line options. def configure(options) # Do nothing by default. return end def execute() raise NotImplementedError end end
klimkin/fig
lib/fig/command/action.rb
Ruby
bsd-3-clause
2,794
// @flow import React from "react" import PeopleList from "./PeopleList" import type { WidgetComponentProps } from "../../flow/widgetTypes" const PeopleWidget = ({ widgetInstance: { json: { people, show_all_members_link } // eslint-disable-line camelcase } }: WidgetComponentProps) => ( <PeopleList profiles={people} showAllMembersLink={show_all_members_link} // eslint-disable-line camelcase useDragHandle={true} /> ) export default PeopleWidget
mitodl/open-discussions
static/js/components/widgets/PeopleWidget.js
JavaScript
bsd-3-clause
474
# Implementation of RAKE - Rapid Automtic Keyword Exraction algorithm # as described in: # Rose, S., D. Engel, N. Cramer, and W. Cowley (2010). # Automatic keyword extraction from indi-vidual documents. # In M. W. Berry and J. Kogan (Eds.), Text Mining: Applications and Theory.unknown: John Wiley and Sons, Ltd. import re import operator import os BASE_DIR = (os.path.dirname(os.path.abspath(__file__))) debug = False def is_number(s): try: float(s) if '.' in s else int(s) return True except ValueError: return False def load_stop_words(stop_word_file): """ Utility function to load stop words from a file and return as a list of words @param stop_word_file Path and file name of a file containing stop words. @return list A list of stop words. """ stop_words = [] for line in open(stop_word_file): if line.strip()[0:1] != "#": for word in line.split(): # in case more than one per line stop_words.append(word) return stop_words def separate_words(text, min_word_return_size): """ Utility function to return a list of all words that are have a length greater than a specified number of characters. @param text The text that must be split in to words. @param min_word_return_size The minimum no of characters a word must have to be included. """ splitter = re.compile(r'[^a-zA-Z0-9_\+\-/]') words = [] for single_word in splitter.split(text): current_word = single_word.strip().lower() # leave numbers in phrase, but don't count as words, since they tend to invalidate scores of their phrases if len(current_word) > min_word_return_size and current_word != '' and not is_number(current_word): words.append(current_word) return words def split_sentences(text): """ Utility function to return a list of sentences. @param text The text that must be split in to sentences. """ sentence_delimiters = re.compile(r'[!\?;:\[\]\t\"\(\)]|\s\-\s|[^0-9],[^a-zA-Z0-9]|\.[^a-zA-Z0-9]|\.$') sentences = sentence_delimiters.split(text) return sentences def build_stop_word_regex(stop_word_file_path): stop_word_list = load_stop_words(stop_word_file_path) stop_word_regex_list = [] for word in stop_word_list: word_regex = r'\b'+word+r'(?![\w-])' # added look ahead for hyphen stop_word_regex_list.append(word_regex) stop_word_pattern = re.compile('|'.join(stop_word_regex_list), re.IGNORECASE) return stop_word_pattern def generate_candidate_keywords(sentence_list, stopword_pattern): phrase_list = [] for s in sentence_list: tmp = re.sub(stopword_pattern, '|', s.strip()) phrases = tmp.split("|") for phrase in phrases: phrase = phrase.strip().lower() if phrase != "": phrase_list.append(phrase) return phrase_list def calculate_word_scores(phraseList): word_frequency = {} word_degree = {} for phrase in phraseList: word_list = separate_words(phrase, 0) word_list_length = len(word_list) word_list_degree = word_list_length-1 # if word_list_degree > 3: word_list_degree = 3 #exp. for word in word_list: word_frequency.setdefault(word, 0) word_frequency[word] += 1 word_degree.setdefault(word, 0) word_degree[word] += word_list_degree # orig. # word_degree[word] += 1/(word_list_length*1.0) #exp. for item in word_frequency: word_degree[item] = word_degree[item]+word_frequency[item] # Calculate Word scores = deg(w)/frew(w) word_score = {} for item in word_frequency: word_score.setdefault(item, 0) word_score[item] = word_degree[item]/(word_frequency[item]*1.0) # orig. # word_score[item] = word_frequency[item]/(word_degree[item] * 1.0) #exp. return word_score def generate_candidate_keyword_scores(phrase_list, word_score): keyword_candidates = {} for phrase in phrase_list: keyword_candidates.setdefault(phrase, 0) word_list = separate_words(phrase, 0) candidate_score = 0 for word in word_list: candidate_score += word_score[word] keyword_candidates[phrase] = candidate_score return keyword_candidates class Rake(object): def __init__(self, stop_words_path=os.path.join(BASE_DIR, "SmartStoplist.txt")): self.stop_words_path = stop_words_path self.__stop_words_pattern = build_stop_word_regex(stop_words_path) def run(self, text): sentence_list = split_sentences(text) phrase_list = generate_candidate_keywords(sentence_list, self.__stop_words_pattern) word_scores = calculate_word_scores(phrase_list) keyword_candidates = generate_candidate_keyword_scores(phrase_list, word_scores) sorted_keywords = sorted(keyword_candidates.iteritems(), key=operator.itemgetter(1), reverse=True) return sorted_keywords if __name__ == "__main__": text = "Compatibility of systems of linear constraints over the set of natural numbers. Criteria of compatibility of a system of linear Diophantine equations, strict inequations, and nonstrict inequations are considered. Upper bounds for components of a minimal set of solutions and algorithms of construction of minimal generating sets of solutions for all types of systems are given. These criteria and the corresponding algorithms for constructing a minimal supporting set of solutions can be used in solving all the considered types of systems and systems of mixed types." # Split text into sentences sentenceList = split_sentences(text) # stoppath = "FoxStoplist.txt" #Fox stoplist contains "numbers", so it will not find "natural numbers" like in Table 1.1 stoppath = os.path.join(BASE_DIR, "SmartStoplist.txt") # SMART stoplist misses some of the lower-scoring keywords in Figure 1.5, which means that the top 1/3 cuts off one of the 4.0 score words in Table 1.1 stopwordpattern = build_stop_word_regex(stoppath) # generate candidate keywords phraseList = generate_candidate_keywords(sentenceList, stopwordpattern) # calculate individual word scores wordscores = calculate_word_scores(phraseList) # generate candidate keyword scores keywordcandidates = generate_candidate_keyword_scores(phraseList, wordscores) if debug: print keywordcandidates sortedKeywords = sorted(keywordcandidates.iteritems(), key=operator.itemgetter(1), reverse=True) if debug: print sortedKeywords totalKeywords = len(sortedKeywords) if debug: print totalKeywords print sortedKeywords[0:(totalKeywords/3)] rake = Rake(stoppath) keywords = rake.run(text) print keywords
idf/tagr
rake_app/rake/rake.py
Python
bsd-3-clause
6,809
from django.utils.datastructures import SortedDict from bencode import bencode, bdecode def sort_dict(D): result = SortedDict() for key in sorted(D.keys()): if type(D[key]) is dict: D[key] = sort_dict(D[key]) result[key] = D[key] return result
abshkd/benzene
torrents/utils/__init__.py
Python
bsd-3-clause
254
/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <folly/Conv.h> #include <glog/logging.h> #include <gtest/gtest.h> #include <memory> #include <proxygen/lib/http/codec/compress/HPACKContext.h> #include <proxygen/lib/http/codec/compress/HPACKDecoder.h> #include <proxygen/lib/http/codec/compress/HPACKEncoder.h> #include <proxygen/lib/http/codec/compress/Logging.h> using namespace folly; using namespace proxygen; using namespace std; using namespace testing; class HPACKContextTests : public testing::Test { }; class TestContext : public HPACKContext { public: TestContext(HPACK::MessageType msgType, uint32_t tableSize) : HPACKContext(msgType, tableSize) {} void add(const HPACKHeader& header) { table_.add(header); } }; TEST_F(HPACKContextTests, get_index) { HPACKContext context(HPACK::MessageType::REQ, HPACK::kTableSize); HPACKHeader method(":method", "POST"); // this will get it from the static table CHECK_EQ(context.getIndex(method), 3); } TEST_F(HPACKContextTests, is_static) { TestContext context(HPACK::MessageType::REQ, HPACK::kTableSize); // add 10 headers to the table for (int i = 1; i <= 10; i++) { HPACKHeader header("name" + folly::to<string>(i), "value" + folly::to<string>(i)); context.add(header); } EXPECT_EQ(context.getTable().size(), 10); EXPECT_EQ(context.isStatic(1), false); EXPECT_EQ(context.isStatic(10), false); EXPECT_EQ(context.isStatic(40), true); EXPECT_EQ(context.isStatic(60), true); EXPECT_EQ(context.isStatic(69), true); } TEST_F(HPACKContextTests, static_table) { auto& table = StaticHeaderTable::get(); const HPACKHeader& first = table[1]; const HPACKHeader& methodPost = table[3]; const HPACKHeader& last = table[table.size()]; // there are 60 entries in the spec CHECK_EQ(table.size(), 60); CHECK_EQ(table[3], HPACKHeader(":method", "POST")); CHECK_EQ(table[1].name, ":authority"); CHECK_EQ(table[table.size()].name, "www-authenticate"); } TEST_F(HPACKContextTests, static_index) { TestContext context(HPACK::MessageType::REQ, HPACK::kTableSize); HPACKHeader authority(":authority", ""); EXPECT_EQ(context.getHeader(1), authority); HPACKHeader post(":method", "POST"); EXPECT_EQ(context.getHeader(3), post); HPACKHeader contentLength("content-length", ""); EXPECT_EQ(context.getHeader(27), contentLength); } TEST_F(HPACKContextTests, encoder_multiple_values) { HPACKEncoder encoder(HPACK::MessageType::RESP, true); vector<HPACKHeader> req; req.push_back(HPACKHeader("accept-encoding", "gzip")); req.push_back(HPACKHeader("accept-encoding", "sdch,gzip")); // with the first encode both headers should be in the reference set unique_ptr<IOBuf> encoded = encoder.encode(req); EXPECT_TRUE(encoded->length() > 0); EXPECT_EQ(encoder.getTable().size(), 2); // sending the same request again should lead to an empty encode buffer EXPECT_EQ(encoder.encode(req), nullptr); } TEST_F(HPACKContextTests, decoder_large_header) { // with this size basically the table will not be able to store any entry uint32_t size = 32; HPACKHeader header; HPACKEncoder encoder(HPACK::MessageType::REQ, true, size); HPACKDecoder decoder(HPACK::MessageType::REQ, size); vector<HPACKHeader> headers; headers.push_back(HPACKHeader(":path", "verylargeheader")); // add a static entry headers.push_back(HPACKHeader(":method", "GET")); auto buf = encoder.encode(headers); auto decoded = decoder.decode(buf.get()); EXPECT_EQ(encoder.getTable().size(), 0); EXPECT_EQ(encoder.getTable().referenceSet().size(), 0); EXPECT_EQ(decoder.getTable().size(), 0); EXPECT_EQ(decoder.getTable().referenceSet().size(), 0); } /** * testing invalid memory access in the decoder; it has to always call peek() */ TEST_F(HPACKContextTests, decoder_invalid_peek) { HPACKEncoder encoder(HPACK::MessageType::REQ, true); HPACKDecoder decoder(HPACK::MessageType::REQ); vector<HPACKHeader> headers; headers.push_back(HPACKHeader("x-fb-debug", "test")); unique_ptr<IOBuf> encoded = encoder.encode(headers); unique_ptr<IOBuf> first = IOBuf::create(128); // set a trap for indexed header and don't call append first->writableData()[0] = HPACK::HeaderEncoding::INDEXED; first->appendChain(std::move(encoded)); auto decoded = decoder.decode(first.get()); EXPECT_FALSE(decoder.hasError()); EXPECT_EQ(*decoded, headers); } /** * similar with the one above, but slightly different code paths */ TEST_F(HPACKContextTests, decoder_invalid_literal_peek) { HPACKEncoder encoder(HPACK::MessageType::REQ, true); HPACKDecoder decoder(HPACK::MessageType::REQ); vector<HPACKHeader> headers; headers.push_back(HPACKHeader("x-fb-random", "bla")); unique_ptr<IOBuf> encoded = encoder.encode(headers); unique_ptr<IOBuf> first = IOBuf::create(128); first->writableData()[0] = 0x3F; first->appendChain(std::move(encoded)); auto decoded = decoder.decode(first.get()); EXPECT_FALSE(decoder.hasError()); EXPECT_EQ(*decoded, headers); } /** * testing various error cases in HPACKDecoder::decodeLiterHeader() */ void checkError(const IOBuf* buf, const HPACKDecoder::Error err) { HPACKDecoder decoder(HPACK::MessageType::REQ); auto decoded = decoder.decode(buf); EXPECT_TRUE(decoder.hasError()); EXPECT_EQ(decoder.getError(), err); } TEST_F(HPACKContextTests, decode_errors) { unique_ptr<IOBuf> buf = IOBuf::create(128); // 1. simulate an error decoding the index for an indexed header name // we try to encode index 65 buf->writableData()[0] = 0x3F; buf->append(1); // intentionally omit the second byte checkError(buf.get(), HPACKDecoder::Error::BUFFER_OVERFLOW); // 2. invalid index for indexed header name buf->writableData()[1] = 0xFF; buf->writableData()[2] = 0x7F; buf->append(2); checkError(buf.get(), HPACKDecoder::Error::INVALID_INDEX); // 3. buffer overflow when decoding literal header name buf->writableData()[0] = 0x00; // this will activate the non-indexed branch checkError(buf.get(), HPACKDecoder::Error::BUFFER_OVERFLOW); // 4. buffer overflow when decoding a header value // size for header name size and the actual header name buf->writableData()[1] = 0x01; buf->writableData()[2] = 'h'; checkError(buf.get(), HPACKDecoder::Error::BUFFER_OVERFLOW); // 5. buffer overflow decoding the index of an indexed header buf->writableData()[0] = 0xFF; // first bit is 1 to mark indexed header buf->writableData()[1] = 0x80; // first bit is 1 to continue the // variable-length encoding buf->writableData()[2] = 0x80; checkError(buf.get(), HPACKDecoder::Error::BUFFER_OVERFLOW); }
haspatel/proxygen
proxygen/lib/http/codec/compress/test/HPACKContextTests.cpp
C++
bsd-3-clause
6,951
package LBJ2.nlp; import LBJ2.parse.LineByLine; /** * This parser returns arrays of <code>String</code>s representing the rows * of a file in column format. The input file is assumed to contain fields * of non-whitespace characters separated by any amount of whitespace, one * line of which is usually used to represent a word in a corpus. This * parser breaks a given line into one <code>String</code> per field, * omitting all of the whitespace. They are then returned in an array via * <code>next()</code>. If the input line is empty or contains only * whitespace, a zero length array will be returned. * * @author Nick Rizzolo **/ public class ColumnFormat extends LineByLine { /** * Creates the parser. * * @param file The name of the file to parse. **/ public ColumnFormat(String file) { super(file); } /** * Returns an array of <code>String</code>s representing the information in * the columns of this row. **/ public Object next() { String line = readLine(); if (line == null) return null; if (line.length() == 0) return new String[0]; return line.split("\\s+"); } }
TeamCohen/MinorThird
src/main/java/LBJ2/nlp/ColumnFormat.java
Java
bsd-3-clause
1,159
/* * check_chitcpd.c * * Created on: Jan 11, 2014 * Author: borja */ #include <stdlib.h> #include <check.h> #include "chitcp/chitcpd.h" #include "serverinfo.h" #include "server.h" START_TEST (test_chitcpd_startstop) { int rc; serverinfo_t *si; si = calloc(1, sizeof(serverinfo_t)); si->server_port = chitcp_htons(23301); si->server_socket_path = DEFAULT_CHITCPD_SOCK; rc = chitcpd_server_init(si); ck_assert_msg(rc == 0, "Could not initialize chiTCP daemon."); rc = chitcpd_server_start(si); ck_assert_msg(rc == 0, "Could not start chiTCP daemon."); rc = chitcpd_server_stop(si); ck_assert_msg(rc == 0, "Could not stop chiTCP daemon."); rc = chitcpd_server_wait(si); ck_assert_msg(rc == 0, "Waiting for chiTCP daemon failed."); chitcpd_server_free(si); } END_TEST int main (void) { SRunner *sr; int number_failed; Suite *s; s = suite_create ("chiTCP daemon"); /* Core test case */ TCase *tc_startstop= tcase_create ("Start and stop"); tcase_add_test (tc_startstop, test_chitcpd_startstop); suite_add_tcase (s, tc_startstop); sr = srunner_create (s); srunner_run_all (sr, CK_NORMAL); number_failed = srunner_ntests_failed (sr); srunner_free (sr); return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }
theseoafs/chitcp
tests/check_chitcpd.c
C
bsd-3-clause
1,340
import klampt.math.autodiff.ad as ad import torch,numpy as np class TorchModuleFunction(ad.ADFunctionInterface): """Converts a PyTorch function to a Klamp't autodiff function class.""" def __init__(self,module): self.module=module self._eval_params=[] torch.set_default_dtype(torch.float64) def __str__(self): return str(self.module) def n_in(self,arg): return -1 def n_out(self): return -1 def eval(self,*args): self._eval_params=[] for a in args: if not isinstance(a,np.ndarray): a=np.array([a]) p=torch.Tensor(a) p.requires_grad_(True) self._eval_params.append(p) try: self._eval_result=torch.flatten(self.module(*self._eval_params)) #self._eval_result.forward() except Exception as e: print('Torch error: %s'%str(e)) return self._eval_result.detach().numpy() def derivative(self,arg,*args): #lazily check if forward has been done before if not self._same_param(*args): self.eval(*args) rows=[] for i in range(self._eval_result.shape[0]): if self._eval_params[arg].grad is not None: self._eval_params[arg].grad.zero_() #this is a major performance penalty, torch does not support jacobian #we have to do it row by row self._eval_result[i].backward(retain_graph=True) rows.append(self._eval_params[arg].grad.detach().numpy().flatten()) return np.vstack(rows) def jvp(self,arg,darg,*args): raise NotImplementedError('') def _same_param(self,*args): if not hasattr(self,"_eval_params"): return False if len(self._eval_params)!=len(args): return False for p,a in zip(self._eval_params,args): pn = p.detach().numpy() if not isinstance(a,np.ndarray): a=np.array([a]) if pn.shape != a.shape: return False if (pn!=a).any(): return False return True class ADModule(torch.autograd.Function): """Converts a Klamp't autodiff function call or function instance to a PyTorch Function. The class must be created with the terminal symbols corresponding to the PyTorch arguments to which this is called. """ @staticmethod def forward(ctx,func,terminals,*args): torch.set_default_dtype(torch.float64) if len(args)!=len(terminals): raise ValueError("Function %s expected to have %d arguments, instead got %d"%(str(func),len(terminals),len(args))) if isinstance(func,ad.ADFunctionCall): context={} for t,a in zip(terminals,args): context[t.name]=a.detach().numpy() ret=func.eval(**context) elif isinstance(func,ad.ADFunctionInterface): context=[] for t,a in zip(terminals,args): context.append(a.detach().numpy()) ret=func.eval(*context) else: raise ValueError("f must be a ADFunctionCall or ADFunctionInterface") ctx.saved_state=(func,terminals,context) return torch.Tensor(ret) @staticmethod def backward(ctx,grad): ret = [None,None] func,terminals,context = ctx.saved_state if isinstance(func,ad.ADFunctionCall): for k in range(len(terminals)): if isinstance(terminals[k],ad.ADTerminal): name = terminals[k].name else: name = terminals[k] deriv=torch.Tensor(func.derivative(name,**context)) ret.append(deriv.T@grad) elif isinstance(func,ad.ADFunctionInterface): for k in range(len(terminals)): deriv=torch.Tensor(func.derivative(k,*context)) ret.append(deriv.T@grad) else: raise ValueError("f must be a ADFunctionCall or ADFunctionInterface") return tuple(ret) @staticmethod def check_derivatives_torch(func,terminals,h=1e-6,rtol=1e-2,atol=1e-3): #sample some random parameters of the appropriate length if isinstance(func,ad.ADFunctionInterface): params=[] for i in range(len(terminals)): try: N = func.n_in(i) if N < 0: N = 10 except NotImplementedError: N = 10 params.append(torch.randn(N)) else: N = 10 params = [torch.randn(N) for i in range(len(terminals))] for p in params: p.requires_grad_(True) torch.autograd.gradcheck(ADModule.apply,tuple([func,terminals]+params),eps=h,atol=atol,rtol=rtol,raise_exception=True) def torch_to_ad(module,args): """Converts a PyTorch function applied to args (list of scalars or numpy arrays) to a Klamp't autodiff function call on those arguments.""" wrapper=TorchModuleFunction(module) return wrapper(*args) def ad_to_torch(func,terminals=None): """Converts a Klamp't autodiff function call or function instance to a PyTorch Function. If terminals is provided, this is the list of arguments that PyTorch will expect. Otherwise, the variables in the expression will be automatically determined by the forward traversal order.""" if terminals is None: if isinstance(func,ad.ADFunctionCall): terminals = func.terminals() else: n_args = func.n_args() terminals = [func.argname(i) for i in range(n_args)] else: if isinstance(func,ad.ADFunctionCall): fterminals = func.terminals() if len(terminals) != len(fterminals): raise ValueError("The number of terminals provided is incorrect") for t in terminals: if isinstance(t,ad.ADTerminal): name = t.name else: name = t if name not in fterminals: raise ValueError("Invalid terminal %s, function call %s only has terminals %s"%(name,str(func),str(terminals))) else: try: if len(terminals) != func.n_args(): raise ValueError("Invalid number of terminals, function %s expects %d"%(str(func),func.n_args())) except NotImplementedError: pass return ADModule(func,terminals)
krishauser/Klampt
Python/klampt/math/autodiff/pytorch.py
Python
bsd-3-clause
6,627
<!DOCTYPE html> <html> <meta charset="utf-8"> <title>Date parser test — new Date('x') — 6</title> <script src="../date_test.js"></script> <p>Failed (Script did not run)</p> <script> test_date_invalid("6", "Invalid Date") </script> </html>
operasoftware/presto-testo
core/features/dateParsing/TestCases/individual/SlashSeparator/1044.html
HTML
bsd-3-clause
258
# Copyright 2008-2010 Neil Martinsen-Burrell # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # Copyright 2018 Jo Bovy # # Made small changes to allow this module to be used in Python 3, but only # to be able to read the files used in the mwdust package. Keep the same # license as above """Defines a file-derived class to read/write Fortran unformatted files. The assumption is that a Fortran unformatted file is being written by the Fortran runtime as a sequence of records. Each record consists of an integer (of the default size [usually 32 or 64 bits]) giving the length of the following data in bytes, then the data itself, then the same integer as before. Examples -------- To use the default endian and precision settings, one can just do:: >>> f = FortranFile('filename') >>> x = f.readReals() One can read arrays with varying precisions:: >>> f = FortranFile('filename') >>> x = f.readInts('h') >>> y = f.readInts('q') >>> z = f.readReals('f') Where the format codes are those used by Python's struct module. One can change the default endian-ness and header precision:: >>> f = FortranFile('filename', endian='>', header_prec='l') for a file with little-endian data whose record headers are long integers. """ __docformat__ = "restructuredtext en" import sys _PY3= sys.version > '3' if _PY3: from io import FileIO file= FileIO import numpy class FortranFile(file): """File with methods for dealing with fortran unformatted data files""" def _get_header_length(self): return numpy.dtype(self._header_prec).itemsize _header_length = property(fget=_get_header_length) def _set_endian(self,c): """Set endian to big (c='>') or little (c='<') or native (c='=') :Parameters: `c` : string The endian-ness to use when reading from this file. """ if c in '<>@=': if c == '@': c = '=' self._endian = c else: raise ValueError('Cannot set endian-ness') def _get_endian(self): return self._endian ENDIAN = property(fset=_set_endian, fget=_get_endian, doc="Possible endian values are '<', '>', '@', '='" ) def _set_header_prec(self, prec): if prec in 'hilq': self._header_prec = prec else: raise ValueError('Cannot set header precision') def _get_header_prec(self): return self._header_prec HEADER_PREC = property(fset=_set_header_prec, fget=_get_header_prec, doc="Possible header precisions are 'h', 'i', 'l', 'q'" ) def __init__(self, fname, endian='@', header_prec='i', *args, **kwargs): """Open a Fortran unformatted file for writing. Parameters ---------- endian : character, optional Specify the endian-ness of the file. Possible values are '>', '<', '@' and '='. See the documentation of Python's struct module for their meanings. The deafult is '>' (native byte order) header_prec : character, optional Specify the precision used for the record headers. Possible values are 'h', 'i', 'l' and 'q' with their meanings from Python's struct module. The default is 'i' (the system's default integer). """ file.__init__(self, fname, *args, **kwargs) self.ENDIAN = endian self.HEADER_PREC = header_prec def _read_exactly(self, num_bytes): """Read in exactly num_bytes, raising an error if it can't be done.""" if _PY3: data = b'' else: data = '' while True: l = len(data) if l == num_bytes: return data else: read_data = self.read(num_bytes - l) if read_data == '': raise IOError('Could not read enough data.' ' Wanted %d bytes, got %d.' % (num_bytes, l)) data += read_data def _read_check(self): return numpy.fromstring(self._read_exactly(self._header_length), dtype=self.ENDIAN+self.HEADER_PREC )[0] def _write_check(self, number_of_bytes): """Write the header for the given number of bytes""" self.write(numpy.array(number_of_bytes, dtype=self.ENDIAN+self.HEADER_PREC,).tostring() ) def readRecord(self): """Read a single fortran record""" l = self._read_check() data_str = self._read_exactly(l) check_size = self._read_check() if check_size != l: raise IOError('Error reading record from data file') return data_str def writeRecord(self,s): """Write a record with the given bytes. Parameters ---------- s : the string to write """ length_bytes = len(s) self._write_check(length_bytes) self.write(s) self._write_check(length_bytes) def readString(self): """Read a string.""" return self.readRecord() def writeString(self,s): """Write a string Parameters ---------- s : the string to write """ self.writeRecord(s) _real_precisions = 'df' def readReals(self, prec='f'): """Read in an array of real numbers. Parameters ---------- prec : character, optional Specify the precision of the array using character codes from Python's struct module. Possible values are 'd' and 'f'. """ _numpy_precisions = {'d': numpy.float64, 'f': numpy.float32 } if prec not in self._real_precisions: raise ValueError('Not an appropriate precision') data_str = self.readRecord() return numpy.fromstring(data_str, dtype=self.ENDIAN+prec) def writeReals(self, reals, prec='f'): """Write an array of floats in given precision Parameters ---------- reals : array Data to write prec` : string Character code for the precision to use in writing """ if prec not in self._real_precisions: raise ValueError('Not an appropriate precision') nums = numpy.array(reals, dtype=self.ENDIAN+prec) self.writeRecord(nums.tostring()) _int_precisions = 'hilq' def readInts(self, prec='i'): """Read an array of integers. Parameters ---------- prec : character, optional Specify the precision of the data to be read using character codes from Python's struct module. Possible values are 'h', 'i', 'l' and 'q' """ if prec not in self._int_precisions: raise ValueError('Not an appropriate precision') data_str = self.readRecord() return numpy.fromstring(data_str, dtype=self.ENDIAN+prec) def writeInts(self, ints, prec='i'): """Write an array of integers in given precision Parameters ---------- reals : array Data to write prec : string Character code for the precision to use in writing """ if prec not in self._int_precisions: raise ValueError('Not an appropriate precision') nums = numpy.array(ints, dtype=self.ENDIAN+prec) self.writeRecord(nums.tostring())
jobovy/mwdust
mwdust/util/fortranfile.py
Python
bsd-3-clause
8,822
/* Nuklear - v1.152 - public domain no warrenty implied; use at your own risk. authored from 2015-2016 by Micha Mettke ABOUT: This is a minimal state immediate mode graphical user interface single header toolkit written in ANSI C and licensed under public domain. It was designed as a simple embeddable user interface for application and does not have any dependencies, a default renderbackend or OS window and input handling but instead provides a very modular library approach by using simple input state for input and draw commands describing primitive shapes as output. So instead of providing a layered library that tries to abstract over a number of platform and render backends it only focuses on the actual UI. VALUES: - Immediate mode graphical user interface toolkit - Single header library - Written in C89 (A.K.A. ANSI C or ISO C90) - Small codebase (~17kLOC) - Focus on portability, efficiency and simplicity - No dependencies (not even the standard library if not wanted) - Fully skinnable and customizable - Low memory footprint with total memory control if needed or wanted - UTF-8 support - No global or hidden state - Customizable library modules (you can compile and use only what you need) - Optional font baker and vertex buffer output USAGE: This library is self contained in one single header file and can be used either in header only mode or in implementation mode. The header only mode is used by default when included and allows including this header in other headers and does not contain the actual implementation. The implementation mode requires to define the preprocessor macro NK_IMPLEMENTATION in *one* .c/.cpp file before #includeing this file, e.g.: #define NK_IMPLEMENTATION #include "nuklear.h" Also optionally define the symbols listed in the section "OPTIONAL DEFINES" below in header and implementation mode if you want to use additional functionality or need more control over the library. IMPORTANT: Every time you include "nuklear.h" you have to define the same flags. This is very important not doing it either leads to compiler errors or even worse stack corruptions. FEATURES: - Absolutely no platform dependend code - Memory management control ranging from/to - Ease of use by allocating everything from the standard library - Control every byte of memory inside the library - Font handling control ranging from/to - Use your own font implementation for everything - Use this libraries internal font baking and handling API - Drawing output control ranging from/to - Simple shapes for more high level APIs which already have drawing capabilities - Hardware accessible anti-aliased vertex buffer output - Customizable colors and properties ranging from/to - Simple changes to color by filling a simple color table - Complete control with ability to use skinning to decorate widgets - Bendable UI library with widget ranging from/to - Basic widgets like buttons, checkboxes, slider, ... - Advanced widget like abstract comboboxes, contextual menus,... - Compile time configuration to only compile what you need - Subset which can be used if you do not want to link or use the standard library - Can be easily modified to only update on user input instead of frame updates OPTIONAL DEFINES: NK_PRIVATE If defined declares all functions as static, so they can only be accessed for the file that creates the implementation NK_INCLUDE_FIXED_TYPES If defined it will include header <stdint.h> for fixed sized types otherwise nuklear tries to select the correct type. If that fails it will throw a compiler error and you have to select the correct types yourself. <!> If used needs to be defined for implementation and header <!> NK_INCLUDE_DEFAULT_ALLOCATOR if defined it will include header <stdlib.h> and provide additional functions to use this library without caring for memory allocation control and therefore ease memory management. <!> Adds the standard library with malloc and free so don't define if you don't want to link to the standard library <!> <!> If used needs to be defined for implementation and header <!> NK_INCLUDE_STANDARD_IO if defined it will include header <stdio.h> and provide additional functions depending on file loading. <!> Adds the standard library with fopen, fclose,... so don't define this if you don't want to link to the standard library <!> <!> If used needs to be defined for implementation and header <!> NK_INCLUDE_STANDARD_VARARGS if defined it will include header <stdarg.h> and provide additional functions depending on variable arguments <!> Adds the standard library with va_list and so don't define this if you don't want to link to the standard library<!> <!> If used needs to be defined for implementation and header <!> NK_INCLUDE_VERTEX_BUFFER_OUTPUT Defining this adds a vertex draw command list backend to this library, which allows you to convert queue commands into vertex draw commands. This is mainly if you need a hardware accessible format for OpenGL, DirectX, Vulkan, Metal,... <!> If used needs to be defined for implementation and header <!> NK_INCLUDE_FONT_BAKING Defining this adds the `stb_truetype` and `stb_rect_pack` implementation to this library and provides font baking and rendering. If you already have font handling or do not want to use this font handler you don't have to define it. <!> If used needs to be defined for implementation and header <!> NK_INCLUDE_DEFAULT_FONT Defining this adds the default font: ProggyClean.ttf into this library which can be loaded into a font atlas and allows using this library without having a truetype font <!> Enabling this adds ~12kb to global stack memory <!> <!> If used needs to be defined for implementation and header <!> NK_INCLUDE_COMMAND_USERDATA Defining this adds a userdata pointer into each command. Can be useful for example if you want to provide custom shaders depending on the used widget. Can be combined with the style structures. <!> If used needs to be defined for implementation and header <!> NK_BUTTON_TRIGGER_ON_RELEASE Different platforms require button clicks occuring either on buttons being pressed (up to down) or released (down to up). By default this library will react on buttons being pressed, but if you define this it will only trigger if a button is released. <!> If used it is only required to be defined for the implementation part <!> NK_ASSERT If you don't define this, nuklear will use <assert.h> with assert(). <!> Adds the standard library so define to nothing of not wanted <!> <!> If used needs to be defined for implementation and header <!> NK_BUFFER_DEFAULT_INITIAL_SIZE Initial buffer size allocated by all buffers while using the default allocator functions included by defining NK_INCLUDE_DEFAULT_ALLOCATOR. If you don't want to allocate the default 4k memory then redefine it. <!> If used needs to be defined for implementation and header <!> NK_MAX_NUMBER_BUFFER Maximum buffer size for the conversion buffer between float and string Under normal circumstances this should be more than sufficient. <!> If used needs to be defined for implementation and header <!> NK_INPUT_MAX Defines the max number of bytes which can be added as text input in one frame. Under normal circumstances this should be more than sufficient. <!> If used it is only required to be defined for the implementation part <!> NK_MEMSET You can define this to 'memset' or your own memset implementation replacement. If not nuklear will use its own version. <!> If used it is only required to be defined for the implementation part <!> NK_MEMCOPY You can define this to 'memcpy' or your own memcpy implementation replacement. If not nuklear will use its own version. <!> If used it is only required to be defined for the implementation part <!> NK_SQRT You can define this to 'sqrt' or your own sqrt implementation replacement. If not nuklear will use its own slow and not highly accurate version. <!> If used it is only required to be defined for the implementation part <!> NK_SIN You can define this to 'sinf' or your own sine implementation replacement. If not nuklear will use its own approximation implementation. <!> If used it is only required to be defined for the implementation part <!> NK_COS You can define this to 'cosf' or your own cosine implementation replacement. If not nuklear will use its own approximation implementation. <!> If used it only needs to be define for the implementation not header <!> <!> If used it is only required to be defined for the implementation part <!> NK_STRTOD You can define this to `strtod` or your own string to double conversion implementation replacement. If not defined nuklear will use its own imprecise and possibly unsafe version (does not handle nan or infinity!). <!> If used it is only required to be defined for the implementation part <!> NK_DTOA You can define this to `dtoa` or your own double to string conversion implementation replacement. If not defined nuklear will use its own imprecise and possibly unsafe version (does not handle nan or infinity!). <!> If used it is only required to be defined for the implementation part <!> NK_VSNPRINTF If you define `NK_INCLUDE_STANDARD_VARARGS` as well as `NK_INCLUDE_STANDARD_IO` and want to be safe define this to `vsnprintf` on compilers supporting later versions of C or C++. By default nuklear will check for your stdlib version in C as well as compiler version in C++. if `vsnprintf` is available it will define it to `vsnprintf` directly. If not defined and if you have older versions of C or C++ it will be defined to `vsprintf` which is unsafe. <!> If used it is only required to be defined for the implementation part <!> NK_BYTE NK_INT16 NK_UINT16 NK_INT32 NK_UINT32 NK_SIZE_TYPE NK_POINTER_TYPE If you compile without NK_USE_FIXED_TYPE then a number of standard types will be selected and compile time validated. If they are incorrect you can define the correct types by overloading these type defines. CREDITS: Developed by Micha Mettke and every direct or indirect contributor to the GitHub. Embeds stb_texedit, stb_truetype and stb_rectpack by Sean Barret (public domain) Embeds ProggyClean.ttf font by Tristan Grimmer (MIT license). Big thank you to Omar Cornut (ocornut@github) for his imgui library and giving me the inspiration for this library, Casey Muratori for handmade hero and his original immediate mode graphical user interface idea and Sean Barret for his amazing single header libraries which restored my faith in libraries and brought me to create some of my own. LICENSE: This software is dual-licensed to the public domain and under the following license: you are granted a perpetual, irrevocable license to copy, modify, publish and distribute this file as you see fit. */ #ifndef NK_NUKLEAR_H_ #define NK_NUKLEAR_H_ #ifdef __cplusplus extern "C" { #endif /* * ============================================================== * * CONSTANTS * * =============================================================== */ #define NK_UNDEFINED (-1.0f) #define NK_UTF_INVALID 0xFFFD /* internal invalid utf8 rune */ #define NK_UTF_SIZE 4 /* describes the number of bytes a glyph consists of*/ #ifndef NK_INPUT_MAX #define NK_INPUT_MAX 16 #endif #ifndef NK_MAX_NUMBER_BUFFER #define NK_MAX_NUMBER_BUFFER 64 #endif #ifndef NK_SCROLLBAR_HIDING_TIMEOUT #define NK_SCROLLBAR_HIDING_TIMEOUT 4.0f #endif /* * ============================================================== * * HELPER * * =============================================================== */ #ifdef NK_PRIVATE #define NK_API static #else #define NK_API extern #endif #define NK_INTERN static #define NK_STORAGE static #define NK_GLOBAL static #define NK_FLAG(x) (1 << (x)) #define NK_STRINGIFY(x) #x #define NK_MACRO_STRINGIFY(x) NK_STRINGIFY(x) #define NK_STRING_JOIN_IMMEDIATE(arg1, arg2) arg1 ## arg2 #define NK_STRING_JOIN_DELAY(arg1, arg2) NK_STRING_JOIN_IMMEDIATE(arg1, arg2) #define NK_STRING_JOIN(arg1, arg2) NK_STRING_JOIN_DELAY(arg1, arg2) #ifdef _MSC_VER #define NK_UNIQUE_NAME(name) NK_STRING_JOIN(name,__COUNTER__) #else #define NK_UNIQUE_NAME(name) NK_STRING_JOIN(name,__LINE__) #endif #ifndef NK_STATIC_ASSERT #define NK_STATIC_ASSERT(exp) typedef char NK_UNIQUE_NAME(_dummy_array)[(exp)?1:-1] #endif #ifndef NK_FILE_LINE #ifdef _MSC_VER #define NK_FILE_LINE __FILE__ ":" NK_MACRO_STRINGIFY(__COUNTER__) #else #define NK_FILE_LINE __FILE__ ":" NK_MACRO_STRINGIFY(__LINE__) #endif #endif /* * =============================================================== * * BASIC * * =============================================================== */ #ifdef NK_INCLUDE_FIXED_TYPES #include <stdint.h> #define NK_INT8 int8_t #define NK_UINT8 uint8_t #define NK_INT16 int16_t #define NK_UINT16 uint16_t #define NK_INT32 int32_t #define NK_UINT32 uint32_t #define NK_SIZE_TYPE uintptr_t #define NK_POINTER_TYPE uintptr_t #else #ifndef NK_INT8 #define NK_INT8 char #endif #ifndef NK_UINT8 #define NK_BYTE unsigned char #endif #ifndef NK_INT16 #define NK_INT16 signed char #endif #ifndef NK_UINT16 #define NK_UINT16 unsigned short #endif #ifndef NK_INT32 #define NK_INT32 signed int #endif #ifndef NK_UINT32 #define NK_UINT32 unsigned int #endif #ifndef NK_SIZE_TYPE #if __WIN32 #define NK_SIZE_TYPE __int32 #elif __WIN64 #define NK_SIZE_TYPE __int64 #elif __GNUC__ || __clang__ #if __x86_64__ || __ppc64__ #define NK_SIZE_TYPE unsigned long #else #define NK_SIZE_TYPE unsigned int #endif #else #define NK_SIZE_TYPE unsigned long #endif #endif #ifndef NK_POINTER_TYPE #if __WIN32 #define NK_POINTER_TYPE unsigned __int32 #elif __WIN64 #define NK_POINTER_TYPE unsigned __int64 #elif __GNUC__ || __clang__ #if __x86_64__ || __ppc64__ #define NK_POINTER_TYPE unsigned long #else #define NK_POINTER_TYPE unsigned int #endif #else #define NK_POINTER_TYPE unsigned long #endif #endif #endif typedef NK_INT8 nk_char; typedef NK_UINT8 nk_uchar; typedef NK_UINT8 nk_byte; typedef NK_INT16 nk_short; typedef NK_UINT16 nk_ushort; typedef NK_INT32 nk_int; typedef NK_UINT32 nk_uint; typedef NK_SIZE_TYPE nk_size; typedef NK_POINTER_TYPE nk_ptr; typedef nk_uint nk_hash; typedef nk_uint nk_flags; typedef nk_uint nk_rune; /* Make sure correct type size: * This will fire with a negative subscript error if the type sizes * are set incorrectly by the compiler, and compile out if not */ NK_STATIC_ASSERT(sizeof(nk_short) == 2); NK_STATIC_ASSERT(sizeof(nk_ushort) == 2); NK_STATIC_ASSERT(sizeof(nk_uint) == 4); NK_STATIC_ASSERT(sizeof(nk_int) == 4); NK_STATIC_ASSERT(sizeof(nk_byte) == 1); NK_STATIC_ASSERT(sizeof(nk_flags) >= 4); NK_STATIC_ASSERT(sizeof(nk_rune) >= 4); NK_STATIC_ASSERT(sizeof(nk_size) >= sizeof(void*)); NK_STATIC_ASSERT(sizeof(nk_ptr) >= sizeof(void*)); /* ============================================================================ * * API * * =========================================================================== */ struct nk_buffer; struct nk_allocator; struct nk_command_buffer; struct nk_draw_command; struct nk_convert_config; struct nk_style_item; struct nk_text_edit; struct nk_draw_list; struct nk_user_font; struct nk_panel; struct nk_context; struct nk_draw_vertex_layout_element; enum {nk_false, nk_true}; struct nk_color {nk_byte r,g,b,a;}; struct nk_colorf {float r,g,b,a;}; struct nk_vec2 {float x,y;}; struct nk_vec2i {short x, y;}; struct nk_rect {float x,y,w,h;}; struct nk_recti {short x,y,w,h;}; typedef char nk_glyph[NK_UTF_SIZE]; typedef union {void *ptr; int id;} nk_handle; struct nk_image {nk_handle handle;unsigned short w,h;unsigned short region[4];}; struct nk_cursor {struct nk_image img; struct nk_vec2 size, offset;}; struct nk_scroll {unsigned short x, y;}; enum nk_heading {NK_UP, NK_RIGHT, NK_DOWN, NK_LEFT}; enum nk_button_behavior {NK_BUTTON_DEFAULT, NK_BUTTON_REPEATER}; enum nk_modify {NK_FIXED = nk_false, NK_MODIFIABLE = nk_true}; enum nk_orientation {NK_VERTICAL, NK_HORIZONTAL}; enum nk_collapse_states {NK_MINIMIZED = nk_false, NK_MAXIMIZED = nk_true}; enum nk_show_states {NK_HIDDEN = nk_false, NK_SHOWN = nk_true}; enum nk_chart_type {NK_CHART_LINES, NK_CHART_COLUMN, NK_CHART_MAX}; enum nk_chart_event {NK_CHART_HOVERING = 0x01, NK_CHART_CLICKED = 0x02}; enum nk_color_format {NK_RGB, NK_RGBA}; enum nk_popup_type {NK_POPUP_STATIC, NK_POPUP_DYNAMIC}; enum nk_layout_format {NK_DYNAMIC, NK_STATIC}; enum nk_tree_type {NK_TREE_NODE, NK_TREE_TAB}; enum nk_anti_aliasing {NK_ANTI_ALIASING_OFF, NK_ANTI_ALIASING_ON}; typedef void*(*nk_plugin_alloc)(nk_handle, void *old, nk_size); typedef void (*nk_plugin_free)(nk_handle, void *old); typedef int(*nk_plugin_filter)(const struct nk_text_edit*, nk_rune unicode); typedef void(*nk_plugin_paste)(nk_handle, struct nk_text_edit*); typedef void(*nk_plugin_copy)(nk_handle, const char*, int len); struct nk_allocator { nk_handle userdata; nk_plugin_alloc alloc; nk_plugin_free free; }; struct nk_draw_null_texture { nk_handle texture;/* texture handle to a texture with a white pixel */ struct nk_vec2 uv; /* coordinates to a white pixel in the texture */ }; struct nk_convert_config { float global_alpha; /* global alpha value */ enum nk_anti_aliasing line_AA; /* line anti-aliasing flag can be turned off if you are tight on memory */ enum nk_anti_aliasing shape_AA; /* shape anti-aliasing flag can be turned off if you are tight on memory */ unsigned int circle_segment_count; /* number of segments used for circles: default to 22 */ unsigned int arc_segment_count; /* number of segments used for arcs: default to 22 */ unsigned int curve_segment_count; /* number of segments used for curves: default to 22 */ struct nk_draw_null_texture null; /* handle to texture with a white pixel for shape drawing */ const struct nk_draw_vertex_layout_element *vertex_layout; /* describes the vertex output format and packing */ nk_size vertex_size; /* sizeof one vertex for vertex packing */ nk_size vertex_alignment; /* vertex alignment: Can be optained by NK_ALIGNOF */ }; enum nk_symbol_type { NK_SYMBOL_NONE, NK_SYMBOL_X, NK_SYMBOL_UNDERSCORE, NK_SYMBOL_CIRCLE_SOLID, NK_SYMBOL_CIRCLE_OUTLINE, NK_SYMBOL_RECT_SOLID, NK_SYMBOL_RECT_OUTLINE, NK_SYMBOL_TRIANGLE_UP, NK_SYMBOL_TRIANGLE_DOWN, NK_SYMBOL_TRIANGLE_LEFT, NK_SYMBOL_TRIANGLE_RIGHT, NK_SYMBOL_PLUS, NK_SYMBOL_MINUS, NK_SYMBOL_MAX }; enum nk_keys { NK_KEY_NONE, NK_KEY_SHIFT, NK_KEY_CTRL, NK_KEY_DEL, NK_KEY_ENTER, NK_KEY_TAB, NK_KEY_BACKSPACE, NK_KEY_COPY, NK_KEY_CUT, NK_KEY_PASTE, NK_KEY_UP, NK_KEY_DOWN, NK_KEY_LEFT, NK_KEY_RIGHT, /* Shortcuts: text field */ NK_KEY_TEXT_INSERT_MODE, NK_KEY_TEXT_REPLACE_MODE, NK_KEY_TEXT_RESET_MODE, NK_KEY_TEXT_LINE_START, NK_KEY_TEXT_LINE_END, NK_KEY_TEXT_START, NK_KEY_TEXT_END, NK_KEY_TEXT_UNDO, NK_KEY_TEXT_REDO, NK_KEY_TEXT_WORD_LEFT, NK_KEY_TEXT_WORD_RIGHT, /* Shortcuts: scrollbar */ NK_KEY_SCROLL_START, NK_KEY_SCROLL_END, NK_KEY_SCROLL_DOWN, NK_KEY_SCROLL_UP, NK_KEY_MAX }; enum nk_buttons { NK_BUTTON_LEFT, NK_BUTTON_MIDDLE, NK_BUTTON_RIGHT, NK_BUTTON_MAX }; enum nk_style_colors { NK_COLOR_TEXT, NK_COLOR_WINDOW, NK_COLOR_HEADER, NK_COLOR_BORDER, NK_COLOR_BUTTON, NK_COLOR_BUTTON_HOVER, NK_COLOR_BUTTON_ACTIVE, NK_COLOR_TOGGLE, NK_COLOR_TOGGLE_HOVER, NK_COLOR_TOGGLE_CURSOR, NK_COLOR_SELECT, NK_COLOR_SELECT_ACTIVE, NK_COLOR_SLIDER, NK_COLOR_SLIDER_CURSOR, NK_COLOR_SLIDER_CURSOR_HOVER, NK_COLOR_SLIDER_CURSOR_ACTIVE, NK_COLOR_PROPERTY, NK_COLOR_EDIT, NK_COLOR_EDIT_CURSOR, NK_COLOR_COMBO, NK_COLOR_CHART, NK_COLOR_CHART_COLOR, NK_COLOR_CHART_COLOR_HIGHLIGHT, NK_COLOR_SCROLLBAR, NK_COLOR_SCROLLBAR_CURSOR, NK_COLOR_SCROLLBAR_CURSOR_HOVER, NK_COLOR_SCROLLBAR_CURSOR_ACTIVE, NK_COLOR_TAB_HEADER, NK_COLOR_COUNT }; enum nk_style_cursor { NK_CURSOR_ARROW, NK_CURSOR_TEXT, NK_CURSOR_MOVE, NK_CURSOR_RESIZE_VERTICAL, NK_CURSOR_RESIZE_HORIZONTAL, NK_CURSOR_RESIZE_TOP_LEFT_DOWN_RIGHT, NK_CURSOR_RESIZE_TOP_RIGHT_DOWN_LEFT, NK_CURSOR_COUNT }; enum nk_widget_layout_states { NK_WIDGET_INVALID, /* The widget cannot be seen and is completely out of view */ NK_WIDGET_VALID, /* The widget is completely inside the window and can be updated and drawn */ NK_WIDGET_ROM /* The widget is partially visible and cannot be updated */ }; /* widget states */ enum nk_widget_states { NK_WIDGET_STATE_MODIFIED = NK_FLAG(1), NK_WIDGET_STATE_INACTIVE = NK_FLAG(2), /* widget is neither active nor hovered */ NK_WIDGET_STATE_ENTERED = NK_FLAG(3), /* widget has been hovered on the current frame */ NK_WIDGET_STATE_HOVER = NK_FLAG(4), /* widget is being hovered */ NK_WIDGET_STATE_ACTIVED = NK_FLAG(5),/* widget is currently activated */ NK_WIDGET_STATE_LEFT = NK_FLAG(6), /* widget is from this frame on not hovered anymore */ NK_WIDGET_STATE_HOVERED = NK_WIDGET_STATE_HOVER|NK_WIDGET_STATE_MODIFIED, /* widget is being hovered */ NK_WIDGET_STATE_ACTIVE = NK_WIDGET_STATE_ACTIVED|NK_WIDGET_STATE_MODIFIED /* widget is currently activated */ }; /* text alignment */ enum nk_text_align { NK_TEXT_ALIGN_LEFT = 0x01, NK_TEXT_ALIGN_CENTERED = 0x02, NK_TEXT_ALIGN_RIGHT = 0x04, NK_TEXT_ALIGN_TOP = 0x08, NK_TEXT_ALIGN_MIDDLE = 0x10, NK_TEXT_ALIGN_BOTTOM = 0x20 }; enum nk_text_alignment { NK_TEXT_LEFT = NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_LEFT, NK_TEXT_CENTERED = NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_CENTERED, NK_TEXT_RIGHT = NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_RIGHT }; /* edit flags */ enum nk_edit_flags { NK_EDIT_DEFAULT = 0, NK_EDIT_READ_ONLY = NK_FLAG(0), NK_EDIT_AUTO_SELECT = NK_FLAG(1), NK_EDIT_SIG_ENTER = NK_FLAG(2), NK_EDIT_ALLOW_TAB = NK_FLAG(3), NK_EDIT_NO_CURSOR = NK_FLAG(4), NK_EDIT_SELECTABLE = NK_FLAG(5), NK_EDIT_CLIPBOARD = NK_FLAG(6), NK_EDIT_CTRL_ENTER_NEWLINE = NK_FLAG(7), NK_EDIT_NO_HORIZONTAL_SCROLL = NK_FLAG(8), NK_EDIT_ALWAYS_INSERT_MODE = NK_FLAG(9), NK_EDIT_MULTILINE = NK_FLAG(11), NK_EDIT_GOTO_END_ON_ACTIVATE = NK_FLAG(12) }; enum nk_edit_types { NK_EDIT_SIMPLE = NK_EDIT_ALWAYS_INSERT_MODE, NK_EDIT_FIELD = NK_EDIT_SIMPLE|NK_EDIT_SELECTABLE|NK_EDIT_CLIPBOARD, NK_EDIT_BOX = NK_EDIT_ALWAYS_INSERT_MODE| NK_EDIT_SELECTABLE| NK_EDIT_MULTILINE|NK_EDIT_ALLOW_TAB|NK_EDIT_CLIPBOARD, NK_EDIT_EDITOR = NK_EDIT_SELECTABLE|NK_EDIT_MULTILINE|NK_EDIT_ALLOW_TAB| NK_EDIT_CLIPBOARD }; enum nk_edit_events { NK_EDIT_ACTIVE = NK_FLAG(0), /* edit widget is currently being modified */ NK_EDIT_INACTIVE = NK_FLAG(1), /* edit widget is not active and is not being modified */ NK_EDIT_ACTIVATED = NK_FLAG(2), /* edit widget went from state inactive to state active */ NK_EDIT_DEACTIVATED = NK_FLAG(3), /* edit widget went from state active to state inactive */ NK_EDIT_COMMITED = NK_FLAG(4) /* edit widget has received an enter and lost focus */ }; enum nk_panel_flags { NK_WINDOW_BORDER = NK_FLAG(0), /* Draws a border around the window to visually separate the window * from the background */ NK_WINDOW_MOVABLE = NK_FLAG(1), /* The movable flag indicates that a window can be moved by user input or * by dragging the window header */ NK_WINDOW_SCALABLE = NK_FLAG(2), /* The scalable flag indicates that a window can be scaled by user input * by dragging a scaler icon at the button of the window */ NK_WINDOW_CLOSABLE = NK_FLAG(3), /* adds a closable icon into the header */ NK_WINDOW_MINIMIZABLE = NK_FLAG(4), /* adds a minimize icon into the header */ NK_WINDOW_NO_SCROLLBAR = NK_FLAG(5), /* Removes the scrollbar from the window */ NK_WINDOW_TITLE = NK_FLAG(6), /* Forces a header at the top at the window showing the title */ NK_WINDOW_SCROLL_AUTO_HIDE = NK_FLAG(7), /* Automatically hides the window scrollbar if no user interaction */ NK_WINDOW_BACKGROUND = NK_FLAG(8) /* Always keep window in the background */ }; /* context */ #ifdef NK_INCLUDE_DEFAULT_ALLOCATOR NK_API int nk_init_default(struct nk_context*, const struct nk_user_font*); #endif NK_API int nk_init_fixed(struct nk_context*, void *memory, nk_size size, const struct nk_user_font*); NK_API int nk_init_custom(struct nk_context*, struct nk_buffer *cmds, struct nk_buffer *pool, const struct nk_user_font*); NK_API int nk_init(struct nk_context*, struct nk_allocator*, const struct nk_user_font*); NK_API void nk_clear(struct nk_context*); NK_API void nk_free(struct nk_context*); #ifdef NK_INCLUDE_COMMAND_USERDATA NK_API void nk_set_user_data(struct nk_context*, nk_handle handle); #endif /* window */ NK_API int nk_begin(struct nk_context*, struct nk_panel*, const char *title, struct nk_rect bounds, nk_flags flags); NK_API int nk_begin_titled(struct nk_context*, struct nk_panel*, const char *name, const char *title, struct nk_rect bounds, nk_flags flags); NK_API void nk_end(struct nk_context*); NK_API struct nk_window* nk_window_find(struct nk_context *ctx, const char *name); NK_API struct nk_rect nk_window_get_bounds(const struct nk_context*); NK_API struct nk_vec2 nk_window_get_position(const struct nk_context*); NK_API struct nk_vec2 nk_window_get_size(const struct nk_context*); NK_API float nk_window_get_width(const struct nk_context*); NK_API float nk_window_get_height(const struct nk_context*); NK_API struct nk_panel* nk_window_get_panel(struct nk_context*); NK_API struct nk_rect nk_window_get_content_region(struct nk_context*); NK_API struct nk_vec2 nk_window_get_content_region_min(struct nk_context*); NK_API struct nk_vec2 nk_window_get_content_region_max(struct nk_context*); NK_API struct nk_vec2 nk_window_get_content_region_size(struct nk_context*); NK_API struct nk_command_buffer* nk_window_get_canvas(struct nk_context*); NK_API int nk_window_has_focus(const struct nk_context*); NK_API int nk_window_is_collapsed(struct nk_context*, const char*); NK_API int nk_window_is_closed(struct nk_context*, const char*); NK_API int nk_window_is_hidden(struct nk_context*, const char*); NK_API int nk_window_is_active(struct nk_context*, const char*); NK_API int nk_window_is_hovered(struct nk_context*); NK_API int nk_window_is_any_hovered(struct nk_context*); NK_API int nk_item_is_any_active(struct nk_context*); NK_API void nk_window_set_bounds(struct nk_context*, struct nk_rect); NK_API void nk_window_set_position(struct nk_context*, struct nk_vec2); NK_API void nk_window_set_size(struct nk_context*, struct nk_vec2); NK_API void nk_window_set_focus(struct nk_context*, const char *name); NK_API void nk_window_close(struct nk_context *ctx, const char *name); NK_API void nk_window_collapse(struct nk_context*, const char *name, enum nk_collapse_states); NK_API void nk_window_collapse_if(struct nk_context*, const char *name, enum nk_collapse_states, int cond); NK_API void nk_window_show(struct nk_context*, const char *name, enum nk_show_states); NK_API void nk_window_show_if(struct nk_context*, const char *name, enum nk_show_states, int cond); /* Layout */ NK_API void nk_layout_row_dynamic(struct nk_context*, float height, int cols); NK_API void nk_layout_row_static(struct nk_context*, float height, int item_width, int cols); NK_API void nk_layout_row_begin(struct nk_context*, enum nk_layout_format, float row_height, int cols); NK_API void nk_layout_row_push(struct nk_context*, float value); NK_API void nk_layout_row_end(struct nk_context*); NK_API void nk_layout_row(struct nk_context*, enum nk_layout_format, float height, int cols, const float *ratio); NK_API void nk_layout_space_begin(struct nk_context*, enum nk_layout_format, float height, int widget_count); NK_API void nk_layout_space_push(struct nk_context*, struct nk_rect); NK_API void nk_layout_space_end(struct nk_context*); NK_API struct nk_rect nk_layout_space_bounds(struct nk_context*); NK_API struct nk_vec2 nk_layout_space_to_screen(struct nk_context*, struct nk_vec2); NK_API struct nk_vec2 nk_layout_space_to_local(struct nk_context*, struct nk_vec2); NK_API struct nk_rect nk_layout_space_rect_to_screen(struct nk_context*, struct nk_rect); NK_API struct nk_rect nk_layout_space_rect_to_local(struct nk_context*, struct nk_rect); NK_API float nk_layout_ratio_from_pixel(struct nk_context*, float pixel_width); /* Layout: Group */ NK_API int nk_group_begin(struct nk_context*, struct nk_panel*, const char *title, nk_flags); NK_API void nk_group_end(struct nk_context*); /* Layout: Tree */ #define nk_tree_push(ctx, type, title, state) nk_tree_push_hashed(ctx, type, title, state, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),__LINE__) #define nk_tree_push_id(ctx, type, title, state, id) nk_tree_push_hashed(ctx, type, title, state, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),id) NK_API int nk_tree_push_hashed(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed); #define nk_tree_image_push(ctx, type, img, title, state) nk_tree_image_push_hashed(ctx, type, img, title, state, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),__LINE__) #define nk_tree_image_push_id(ctx, type, img, title, state, id) nk_tree_image_push_hashed(ctx, type, img, title, state, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),id) NK_API int nk_tree_image_push_hashed(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed); NK_API void nk_tree_pop(struct nk_context*); /* Widgets */ NK_API void nk_text(struct nk_context*, const char*, int, nk_flags); NK_API void nk_text_colored(struct nk_context*, const char*, int, nk_flags, struct nk_color); NK_API void nk_text_wrap(struct nk_context*, const char*, int); NK_API void nk_text_wrap_colored(struct nk_context*, const char*, int, struct nk_color); NK_API void nk_label(struct nk_context*, const char*, nk_flags align); NK_API void nk_label_colored(struct nk_context*, const char*, nk_flags align, struct nk_color); NK_API void nk_label_wrap(struct nk_context*, const char*); NK_API void nk_label_colored_wrap(struct nk_context*, const char*, struct nk_color); NK_API void nk_image(struct nk_context*, struct nk_image); #ifdef NK_INCLUDE_STANDARD_VARARGS NK_API void nk_labelf(struct nk_context*, nk_flags, const char*, ...); NK_API void nk_labelf_colored(struct nk_context*, nk_flags align, struct nk_color, const char*,...); NK_API void nk_labelf_wrap(struct nk_context*, const char*,...); NK_API void nk_labelf_colored_wrap(struct nk_context*, struct nk_color, const char*,...); NK_API void nk_value_bool(struct nk_context*, const char *prefix, int); NK_API void nk_value_int(struct nk_context*, const char *prefix, int); NK_API void nk_value_uint(struct nk_context*, const char *prefix, unsigned int); NK_API void nk_value_float(struct nk_context*, const char *prefix, float); NK_API void nk_value_color_byte(struct nk_context*, const char *prefix, struct nk_color); NK_API void nk_value_color_float(struct nk_context*, const char *prefix, struct nk_color); NK_API void nk_value_color_hex(struct nk_context*, const char *prefix, struct nk_color); #endif /* Widgets: Buttons */ NK_API int nk_button_text(struct nk_context*, const char *title, int len); NK_API int nk_button_label(struct nk_context*, const char *title); NK_API int nk_button_color(struct nk_context*, struct nk_color); NK_API int nk_button_symbol(struct nk_context*, enum nk_symbol_type); NK_API int nk_button_image(struct nk_context*, struct nk_image img); NK_API int nk_button_symbol_label(struct nk_context*, enum nk_symbol_type, const char*, nk_flags text_alignment); NK_API int nk_button_symbol_text(struct nk_context*, enum nk_symbol_type, const char*, int, nk_flags alignment); NK_API int nk_button_image_label(struct nk_context*, struct nk_image img, const char*, nk_flags text_alignment); NK_API int nk_button_image_text(struct nk_context*, struct nk_image img, const char*, int, nk_flags alignment); NK_API void nk_button_set_behavior(struct nk_context*, enum nk_button_behavior); NK_API int nk_button_push_behavior(struct nk_context*, enum nk_button_behavior); NK_API int nk_button_pop_behavior(struct nk_context*); /* Widgets: Checkbox */ NK_API int nk_check_label(struct nk_context*, const char*, int active); NK_API int nk_check_text(struct nk_context*, const char*, int,int active); NK_API unsigned nk_check_flags_label(struct nk_context*, const char*, unsigned int flags, unsigned int value); NK_API unsigned nk_check_flags_text(struct nk_context*, const char*, int, unsigned int flags, unsigned int value); NK_API int nk_checkbox_label(struct nk_context*, const char*, int *active); NK_API int nk_checkbox_text(struct nk_context*, const char*, int, int *active); NK_API int nk_checkbox_flags_label(struct nk_context*, const char*, unsigned int *flags, unsigned int value); NK_API int nk_checkbox_flags_text(struct nk_context*, const char*, int, unsigned int *flags, unsigned int value); /* Widgets: Radio */ NK_API int nk_radio_label(struct nk_context*, const char*, int *active); NK_API int nk_radio_text(struct nk_context*, const char*, int, int *active); NK_API int nk_option_label(struct nk_context*, const char*, int active); NK_API int nk_option_text(struct nk_context*, const char*, int, int active); /* Widgets: Selectable */ NK_API int nk_selectable_label(struct nk_context*, const char*, nk_flags align, int *value); NK_API int nk_selectable_text(struct nk_context*, const char*, int, nk_flags align, int *value); NK_API int nk_selectable_image_label(struct nk_context*,struct nk_image, const char*, nk_flags align, int *value); NK_API int nk_selectable_image_text(struct nk_context*,struct nk_image, const char*, int, nk_flags align, int *value); NK_API int nk_select_label(struct nk_context*, const char*, nk_flags align, int value); NK_API int nk_select_text(struct nk_context*, const char*, int, nk_flags align, int value); NK_API int nk_select_image_label(struct nk_context*, struct nk_image,const char*, nk_flags align, int value); NK_API int nk_select_image_text(struct nk_context*, struct nk_image,const char*, int, nk_flags align, int value); /* Widgets: Slider */ NK_API float nk_slide_float(struct nk_context*, float min, float val, float max, float step); NK_API int nk_slide_int(struct nk_context*, int min, int val, int max, int step); NK_API int nk_slider_float(struct nk_context*, float min, float *val, float max, float step); NK_API int nk_slider_int(struct nk_context*, int min, int *val, int max, int step); /* Widgets: Progressbar */ NK_API int nk_progress(struct nk_context*, nk_size *cur, nk_size max, int modifyable); NK_API nk_size nk_prog(struct nk_context*, nk_size cur, nk_size max, int modifyable); /* Widgets: Color picker */ NK_API struct nk_color nk_color_picker(struct nk_context*, struct nk_color, enum nk_color_format); NK_API int nk_color_pick(struct nk_context*, struct nk_color*, enum nk_color_format); /* Widgets: Property */ NK_API void nk_property_int(struct nk_context*, const char *name, int min, int *val, int max, int step, float inc_per_pixel); NK_API void nk_property_float(struct nk_context*, const char *name, float min, float *val, float max, float step, float inc_per_pixel); NK_API void nk_property_double(struct nk_context*, const char *name, double min, double *val, double max, double step, float inc_per_pixel); NK_API int nk_propertyi(struct nk_context*, const char *name, int min, int val, int max, int step, float inc_per_pixel); NK_API float nk_propertyf(struct nk_context*, const char *name, float min, float val, float max, float step, float inc_per_pixel); NK_API double nk_propertyd(struct nk_context*, const char *name, double min, double val, double max, double step, float inc_per_pixel); /* Widgets: TextEdit */ NK_API nk_flags nk_edit_string(struct nk_context*, nk_flags, char *buffer, int *len, int max, nk_plugin_filter); NK_API nk_flags nk_edit_buffer(struct nk_context*, nk_flags, struct nk_text_edit*, nk_plugin_filter); NK_API nk_flags nk_edit_string_zero_terminated(struct nk_context*, nk_flags, char *buffer, int max, nk_plugin_filter); /* Chart */ NK_API int nk_chart_begin(struct nk_context*, enum nk_chart_type, int num, float min, float max); NK_API int nk_chart_begin_colored(struct nk_context*, enum nk_chart_type, struct nk_color, struct nk_color active, int num, float min, float max); NK_API void nk_chart_add_slot(struct nk_context *ctx, const enum nk_chart_type, int count, float min_value, float max_value); NK_API void nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type, struct nk_color, struct nk_color active, int count, float min_value, float max_value); NK_API nk_flags nk_chart_push(struct nk_context*, float); NK_API nk_flags nk_chart_push_slot(struct nk_context*, float, int); NK_API void nk_chart_end(struct nk_context*); NK_API void nk_plot(struct nk_context*, enum nk_chart_type, const float *values, int count, int offset); NK_API void nk_plot_function(struct nk_context*, enum nk_chart_type, void *userdata, float(*value_getter)(void* user, int index), int count, int offset); /* Popups */ NK_API int nk_popup_begin(struct nk_context*, struct nk_panel*, enum nk_popup_type, const char*, nk_flags, struct nk_rect bounds); NK_API void nk_popup_close(struct nk_context*); NK_API void nk_popup_end(struct nk_context*); /* Combobox */ NK_API int nk_combo(struct nk_context*, const char **items, int count, int selected, int item_height, struct nk_vec2 size); NK_API int nk_combo_separator(struct nk_context*, const char *items_separated_by_separator, int separator, int selected, int count, int item_height, struct nk_vec2 size); NK_API int nk_combo_string(struct nk_context*, const char *items_separated_by_zeros, int selected, int count, int item_height, struct nk_vec2 size); NK_API int nk_combo_callback(struct nk_context*, void(*item_getter)(void*, int, const char**), void *userdata, int selected, int count, int item_height, struct nk_vec2 size); NK_API void nk_combobox(struct nk_context*, const char **items, int count, int *selected, int item_height, struct nk_vec2 size); NK_API void nk_combobox_string(struct nk_context*, const char *items_separated_by_zeros, int *selected, int count, int item_height, struct nk_vec2 size); NK_API void nk_combobox_separator(struct nk_context*, const char *items_separated_by_separator, int separator,int *selected, int count, int item_height, struct nk_vec2 size); NK_API void nk_combobox_callback(struct nk_context*, void(*item_getter)(void*, int, const char**), void*, int *selected, int count, int item_height, struct nk_vec2 size); /* Combobox: abstract */ NK_API int nk_combo_begin_text(struct nk_context*, struct nk_panel*, const char *selected, int, struct nk_vec2 size); NK_API int nk_combo_begin_label(struct nk_context*, struct nk_panel*, const char *selected, struct nk_vec2 size); NK_API int nk_combo_begin_color(struct nk_context*, struct nk_panel*, struct nk_color color, struct nk_vec2 size); NK_API int nk_combo_begin_symbol(struct nk_context*, struct nk_panel*, enum nk_symbol_type, struct nk_vec2 size); NK_API int nk_combo_begin_symbol_label(struct nk_context*, struct nk_panel*, const char *selected, enum nk_symbol_type, struct nk_vec2 size); NK_API int nk_combo_begin_symbol_text(struct nk_context*, struct nk_panel*, const char *selected, int, enum nk_symbol_type, struct nk_vec2 size); NK_API int nk_combo_begin_image(struct nk_context*, struct nk_panel*, struct nk_image img, struct nk_vec2 size); NK_API int nk_combo_begin_image_label(struct nk_context*, struct nk_panel*, const char *selected, struct nk_image, struct nk_vec2 size); NK_API int nk_combo_begin_image_text(struct nk_context*, struct nk_panel*, const char *selected, int, struct nk_image, struct nk_vec2 size); NK_API int nk_combo_item_label(struct nk_context*, const char*, nk_flags alignment); NK_API int nk_combo_item_text(struct nk_context*, const char*,int, nk_flags alignment); NK_API int nk_combo_item_image_label(struct nk_context*, struct nk_image, const char*, nk_flags alignment); NK_API int nk_combo_item_image_text(struct nk_context*, struct nk_image, const char*, int,nk_flags alignment); NK_API int nk_combo_item_symbol_label(struct nk_context*, enum nk_symbol_type, const char*, nk_flags alignment); NK_API int nk_combo_item_symbol_text(struct nk_context*, enum nk_symbol_type, const char*, int, nk_flags alignment); NK_API void nk_combo_close(struct nk_context*); NK_API void nk_combo_end(struct nk_context*); /* Contextual */ NK_API int nk_contextual_begin(struct nk_context*, struct nk_panel*, nk_flags, struct nk_vec2, struct nk_rect trigger_bounds); NK_API int nk_contextual_item_text(struct nk_context*, const char*, int,nk_flags align); NK_API int nk_contextual_item_label(struct nk_context*, const char*, nk_flags align); NK_API int nk_contextual_item_image_label(struct nk_context*, struct nk_image, const char*, nk_flags alignment); NK_API int nk_contextual_item_image_text(struct nk_context*, struct nk_image, const char*, int len, nk_flags alignment); NK_API int nk_contextual_item_symbol_label(struct nk_context*, enum nk_symbol_type, const char*, nk_flags alignment); NK_API int nk_contextual_item_symbol_text(struct nk_context*, enum nk_symbol_type, const char*, int, nk_flags alignment); NK_API void nk_contextual_close(struct nk_context*); NK_API void nk_contextual_end(struct nk_context*); /* Tooltip */ NK_API void nk_tooltip(struct nk_context*, const char*); NK_API int nk_tooltip_begin(struct nk_context*, struct nk_panel*, float width); NK_API void nk_tooltip_end(struct nk_context*); /* Menu */ NK_API void nk_menubar_begin(struct nk_context*); NK_API void nk_menubar_end(struct nk_context*); NK_API int nk_menu_begin_text(struct nk_context*, struct nk_panel*, const char* title, int title_len, nk_flags align, struct nk_vec2 size); NK_API int nk_menu_begin_label(struct nk_context*, struct nk_panel*, const char*, nk_flags align, struct nk_vec2 size); NK_API int nk_menu_begin_image(struct nk_context*, struct nk_panel*, const char*, struct nk_image, struct nk_vec2 size); NK_API int nk_menu_begin_image_text(struct nk_context*, struct nk_panel*, const char*, int,nk_flags align,struct nk_image, struct nk_vec2 size); NK_API int nk_menu_begin_image_label(struct nk_context*, struct nk_panel*, const char*, nk_flags align,struct nk_image, struct nk_vec2 size); NK_API int nk_menu_begin_symbol(struct nk_context*, struct nk_panel*, const char*, enum nk_symbol_type, struct nk_vec2 size); NK_API int nk_menu_begin_symbol_text(struct nk_context*, struct nk_panel*, const char*, int,nk_flags align,enum nk_symbol_type, struct nk_vec2 size); NK_API int nk_menu_begin_symbol_label(struct nk_context*, struct nk_panel*, const char*, nk_flags align,enum nk_symbol_type, struct nk_vec2 size); NK_API int nk_menu_item_text(struct nk_context*, const char*, int,nk_flags align); NK_API int nk_menu_item_label(struct nk_context*, const char*, nk_flags alignment); NK_API int nk_menu_item_image_label(struct nk_context*, struct nk_image, const char*, nk_flags alignment); NK_API int nk_menu_item_image_text(struct nk_context*, struct nk_image, const char*, int len, nk_flags alignment); NK_API int nk_menu_item_symbol_text(struct nk_context*, enum nk_symbol_type, const char*, int, nk_flags alignment); NK_API int nk_menu_item_symbol_label(struct nk_context*, enum nk_symbol_type, const char*, nk_flags alignment); NK_API void nk_menu_close(struct nk_context*); NK_API void nk_menu_end(struct nk_context*); /* Drawing*/ #define nk_foreach(c, ctx) for((c)=nk__begin(ctx); (c)!=0; (c)=nk__next(ctx, c)) #ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT NK_API void nk_convert(struct nk_context*, struct nk_buffer *cmds, struct nk_buffer *vertices, struct nk_buffer *elements, const struct nk_convert_config*); #define nk_draw_foreach(cmd,ctx, b) for((cmd)=nk__draw_begin(ctx, b); (cmd)!=0; (cmd)=nk__draw_next(cmd, b, ctx)) #define nk_draw_foreach_bounded(cmd,from,to) for((cmd)=(from); (cmd) && (to) && (cmd)>=to; --(cmd)) NK_API const struct nk_draw_command* nk__draw_begin(const struct nk_context*, const struct nk_buffer*); NK_API const struct nk_draw_command* nk__draw_end(const struct nk_context*, const struct nk_buffer*); NK_API const struct nk_draw_command* nk__draw_next(const struct nk_draw_command*, const struct nk_buffer*, const struct nk_context*); #endif /* User Input */ NK_API void nk_input_begin(struct nk_context*); NK_API void nk_input_motion(struct nk_context*, int x, int y); NK_API void nk_input_key(struct nk_context*, enum nk_keys, int down); NK_API void nk_input_button(struct nk_context*, enum nk_buttons, int x, int y, int down); NK_API void nk_input_scroll(struct nk_context*, float y); NK_API void nk_input_char(struct nk_context*, char); NK_API void nk_input_glyph(struct nk_context*, const nk_glyph); NK_API void nk_input_unicode(struct nk_context*, nk_rune); NK_API void nk_input_end(struct nk_context*); /* Style */ NK_API void nk_style_default(struct nk_context*); NK_API void nk_style_from_table(struct nk_context*, const struct nk_color*); NK_API void nk_style_load_cursor(struct nk_context*, enum nk_style_cursor, const struct nk_cursor*); NK_API void nk_style_load_all_cursors(struct nk_context*, struct nk_cursor*); NK_API const char* nk_style_get_color_by_name(enum nk_style_colors); NK_API void nk_style_set_font(struct nk_context*, const struct nk_user_font*); NK_API int nk_style_set_cursor(struct nk_context*, enum nk_style_cursor); NK_API void nk_style_show_cursor(struct nk_context*); NK_API void nk_style_hide_cursor(struct nk_context*); /* Style: stack */ NK_API int nk_style_push_font(struct nk_context*, struct nk_user_font*); NK_API int nk_style_push_float(struct nk_context*, float*, float); NK_API int nk_style_push_vec2(struct nk_context*, struct nk_vec2*, struct nk_vec2); NK_API int nk_style_push_style_item(struct nk_context*, struct nk_style_item*, struct nk_style_item); NK_API int nk_style_push_flags(struct nk_context*, nk_flags*, nk_flags); NK_API int nk_style_push_color(struct nk_context*, struct nk_color*, struct nk_color); NK_API int nk_style_pop_font(struct nk_context*); NK_API int nk_style_pop_float(struct nk_context*); NK_API int nk_style_pop_vec2(struct nk_context*); NK_API int nk_style_pop_style_item(struct nk_context*); NK_API int nk_style_pop_flags(struct nk_context*); NK_API int nk_style_pop_color(struct nk_context*); /* Utilities */ NK_API struct nk_rect nk_widget_bounds(struct nk_context*); NK_API struct nk_vec2 nk_widget_position(struct nk_context*); NK_API struct nk_vec2 nk_widget_size(struct nk_context*); NK_API float nk_widget_width(struct nk_context*); NK_API float nk_widget_height(struct nk_context*); NK_API int nk_widget_is_hovered(struct nk_context*); NK_API int nk_widget_is_mouse_clicked(struct nk_context*, enum nk_buttons); NK_API int nk_widget_has_mouse_click_down(struct nk_context*, enum nk_buttons, int down); NK_API void nk_spacing(struct nk_context*, int cols); /* base widget function */ NK_API enum nk_widget_layout_states nk_widget(struct nk_rect*, const struct nk_context*); NK_API enum nk_widget_layout_states nk_widget_fitting(struct nk_rect*, struct nk_context*, struct nk_vec2); /* color (conversion user --> nuklear) */ NK_API struct nk_color nk_rgb(int r, int g, int b); NK_API struct nk_color nk_rgb_iv(const int *rgb); NK_API struct nk_color nk_rgb_bv(const nk_byte* rgb); NK_API struct nk_color nk_rgb_f(float r, float g, float b); NK_API struct nk_color nk_rgb_fv(const float *rgb); NK_API struct nk_color nk_rgb_hex(const char *rgb); NK_API struct nk_color nk_rgba(int r, int g, int b, int a); NK_API struct nk_color nk_rgba_u32(nk_uint); NK_API struct nk_color nk_rgba_iv(const int *rgba); NK_API struct nk_color nk_rgba_bv(const nk_byte *rgba); NK_API struct nk_color nk_rgba_f(float r, float g, float b, float a); NK_API struct nk_color nk_rgba_fv(const float *rgba); NK_API struct nk_color nk_rgba_hex(const char *rgb); NK_API struct nk_color nk_hsv(int h, int s, int v); NK_API struct nk_color nk_hsv_iv(const int *hsv); NK_API struct nk_color nk_hsv_bv(const nk_byte *hsv); NK_API struct nk_color nk_hsv_f(float h, float s, float v); NK_API struct nk_color nk_hsv_fv(const float *hsv); NK_API struct nk_color nk_hsva(int h, int s, int v, int a); NK_API struct nk_color nk_hsva_iv(const int *hsva); NK_API struct nk_color nk_hsva_bv(const nk_byte *hsva); NK_API struct nk_color nk_hsva_f(float h, float s, float v, float a); NK_API struct nk_color nk_hsva_fv(const float *hsva); /* color (conversion nuklear --> user) */ NK_API void nk_color_f(float *r, float *g, float *b, float *a, struct nk_color); NK_API void nk_color_fv(float *rgba_out, struct nk_color); NK_API void nk_color_d(double *r, double *g, double *b, double *a, struct nk_color); NK_API void nk_color_dv(double *rgba_out, struct nk_color); NK_API nk_uint nk_color_u32(struct nk_color); NK_API void nk_color_hex_rgba(char *output, struct nk_color); NK_API void nk_color_hex_rgb(char *output, struct nk_color); NK_API void nk_color_hsv_i(int *out_h, int *out_s, int *out_v, struct nk_color); NK_API void nk_color_hsv_b(nk_byte *out_h, nk_byte *out_s, nk_byte *out_v, struct nk_color); NK_API void nk_color_hsv_iv(int *hsv_out, struct nk_color); NK_API void nk_color_hsv_bv(nk_byte *hsv_out, struct nk_color); NK_API void nk_color_hsv_f(float *out_h, float *out_s, float *out_v, struct nk_color); NK_API void nk_color_hsv_fv(float *hsv_out, struct nk_color); NK_API void nk_color_hsva_i(int *h, int *s, int *v, int *a, struct nk_color); NK_API void nk_color_hsva_b(nk_byte *h, nk_byte *s, nk_byte *v, nk_byte *a, struct nk_color); NK_API void nk_color_hsva_iv(int *hsva_out, struct nk_color); NK_API void nk_color_hsva_bv(nk_byte *hsva_out, struct nk_color); NK_API void nk_color_hsva_f(float *out_h, float *out_s, float *out_v, float *out_a, struct nk_color); NK_API void nk_color_hsva_fv(float *hsva_out, struct nk_color); /* image */ NK_API nk_handle nk_handle_ptr(void*); NK_API nk_handle nk_handle_id(int); NK_API struct nk_image nk_image_handle(nk_handle); NK_API struct nk_image nk_image_ptr(void*); NK_API struct nk_image nk_image_id(int); NK_API int nk_image_is_subimage(const struct nk_image* img); NK_API struct nk_image nk_subimage_ptr(void*, unsigned short w, unsigned short h, struct nk_rect sub_region); NK_API struct nk_image nk_subimage_id(int, unsigned short w, unsigned short h, struct nk_rect sub_region); NK_API struct nk_image nk_subimage_handle(nk_handle, unsigned short w, unsigned short h, struct nk_rect sub_region); /* math */ NK_API nk_hash nk_murmur_hash(const void *key, int len, nk_hash seed); NK_API void nk_triangle_from_direction(struct nk_vec2 *result, struct nk_rect r, float pad_x, float pad_y, enum nk_heading); NK_API struct nk_vec2 nk_vec2(float x, float y); NK_API struct nk_vec2 nk_vec2i(int x, int y); NK_API struct nk_vec2 nk_vec2v(const float *xy); NK_API struct nk_vec2 nk_vec2iv(const int *xy); NK_API struct nk_rect nk_get_null_rect(void); NK_API struct nk_rect nk_rect(float x, float y, float w, float h); NK_API struct nk_rect nk_recti(int x, int y, int w, int h); NK_API struct nk_rect nk_recta(struct nk_vec2 pos, struct nk_vec2 size); NK_API struct nk_rect nk_rectv(const float *xywh); NK_API struct nk_rect nk_rectiv(const int *xywh); NK_API struct nk_vec2 nk_rect_pos(struct nk_rect); NK_API struct nk_vec2 nk_rect_size(struct nk_rect); /* string*/ NK_API int nk_strlen(const char *str); NK_API int nk_stricmp(const char *s1, const char *s2); NK_API int nk_stricmpn(const char *s1, const char *s2, int n); NK_API int nk_strtoi(const char *str, char **endptr); NK_API float nk_strtof(const char *str, char **endptr); NK_API double nk_strtod(const char *str, char **endptr); NK_API int nk_strfilter(const char *text, const char *regexp); NK_API int nk_strmatch_fuzzy_string(char const *str, char const *pattern, int *out_score); NK_API int nk_strmatch_fuzzy_text(const char *txt, int txt_len, const char *pattern, int *out_score); /* UTF-8 */ NK_API int nk_utf_decode(const char*, nk_rune*, int); NK_API int nk_utf_encode(nk_rune, char*, int); NK_API int nk_utf_len(const char*, int byte_len); NK_API const char* nk_utf_at(const char *buffer, int length, int index, nk_rune *unicode, int *len); /* ============================================================== * * MEMORY BUFFER * * ===============================================================*/ /* A basic (double)-buffer with linear allocation and resetting as only freeing policy. The buffer's main purpose is to control all memory management inside the GUI toolkit and still leave memory control as much as possible in the hand of the user while also making sure the library is easy to use if not as much control is needed. In general all memory inside this library can be provided from the user in three different ways. The first way and the one providing most control is by just passing a fixed size memory block. In this case all control lies in the hand of the user since he can exactly control where the memory comes from and how much memory the library should consume. Of course using the fixed size API removes the ability to automatically resize a buffer if not enough memory is provided so you have to take over the resizing. While being a fixed sized buffer sounds quite limiting, it is very effective in this library since the actual memory consumption is quite stable and has a fixed upper bound for a lot of cases. If you don't want to think about how much memory the library should allocate at all time or have a very dynamic UI with unpredictable memory consumption habits but still want control over memory allocation you can use the dynamic allocator based API. The allocator consists of two callbacks for allocating and freeing memory and optional userdata so you can plugin your own allocator. The final and easiest way can be used by defining NK_INCLUDE_DEFAULT_ALLOCATOR which uses the standard library memory allocation functions malloc and free and takes over complete control over memory in this library. */ struct nk_memory_status { void *memory; unsigned int type; nk_size size; nk_size allocated; nk_size needed; nk_size calls; }; enum nk_allocation_type { NK_BUFFER_FIXED, NK_BUFFER_DYNAMIC }; enum nk_buffer_allocation_type { NK_BUFFER_FRONT, NK_BUFFER_BACK, NK_BUFFER_MAX }; struct nk_buffer_marker { int active; nk_size offset; }; struct nk_memory {void *ptr;nk_size size;}; struct nk_buffer { struct nk_buffer_marker marker[NK_BUFFER_MAX]; /* buffer marker to free a buffer to a certain offset */ struct nk_allocator pool; /* allocator callback for dynamic buffers */ enum nk_allocation_type type; /* memory management type */ struct nk_memory memory; /* memory and size of the current memory block */ float grow_factor; /* growing factor for dynamic memory management */ nk_size allocated; /* total amount of memory allocated */ nk_size needed; /* totally consumed memory given that enough memory is present */ nk_size calls; /* number of allocation calls */ nk_size size; /* current size of the buffer */ }; #ifdef NK_INCLUDE_DEFAULT_ALLOCATOR NK_API void nk_buffer_init_default(struct nk_buffer*); #endif NK_API void nk_buffer_init(struct nk_buffer*, const struct nk_allocator*, nk_size size); NK_API void nk_buffer_init_fixed(struct nk_buffer*, void *memory, nk_size size); NK_API void nk_buffer_info(struct nk_memory_status*, struct nk_buffer*); NK_API void nk_buffer_push(struct nk_buffer*, enum nk_buffer_allocation_type type, const void *memory, nk_size size, nk_size align); NK_API void nk_buffer_mark(struct nk_buffer*, enum nk_buffer_allocation_type type); NK_API void nk_buffer_reset(struct nk_buffer*, enum nk_buffer_allocation_type type); NK_API void nk_buffer_clear(struct nk_buffer*); NK_API void nk_buffer_free(struct nk_buffer*); NK_API void *nk_buffer_memory(struct nk_buffer*); NK_API const void *nk_buffer_memory_const(const struct nk_buffer*); NK_API nk_size nk_buffer_total(struct nk_buffer*); /* ============================================================== * * STRING * * ===============================================================*/ /* Basic string buffer which is only used in context with the text editor * to manage and manipulate dynamic or fixed size string content. This is _NOT_ * the default string handling method.*/ struct nk_str { struct nk_buffer buffer; int len; /* in codepoints/runes/glyphs */ }; #ifdef NK_INCLUDE_DEFAULT_ALLOCATOR NK_API void nk_str_init_default(struct nk_str*); #endif NK_API void nk_str_init(struct nk_str*, const struct nk_allocator*, nk_size size); NK_API void nk_str_init_fixed(struct nk_str*, void *memory, nk_size size); NK_API void nk_str_clear(struct nk_str*); NK_API void nk_str_free(struct nk_str*); NK_API int nk_str_append_text_char(struct nk_str*, const char*, int); NK_API int nk_str_append_str_char(struct nk_str*, const char*); NK_API int nk_str_append_text_utf8(struct nk_str*, const char*, int); NK_API int nk_str_append_str_utf8(struct nk_str*, const char*); NK_API int nk_str_append_text_runes(struct nk_str*, const nk_rune*, int); NK_API int nk_str_append_str_runes(struct nk_str*, const nk_rune*); NK_API int nk_str_insert_at_char(struct nk_str*, int pos, const char*, int); NK_API int nk_str_insert_at_rune(struct nk_str*, int pos, const char*, int); NK_API int nk_str_insert_text_char(struct nk_str*, int pos, const char*, int); NK_API int nk_str_insert_str_char(struct nk_str*, int pos, const char*); NK_API int nk_str_insert_text_utf8(struct nk_str*, int pos, const char*, int); NK_API int nk_str_insert_str_utf8(struct nk_str*, int pos, const char*); NK_API int nk_str_insert_text_runes(struct nk_str*, int pos, const nk_rune*, int); NK_API int nk_str_insert_str_runes(struct nk_str*, int pos, const nk_rune*); NK_API void nk_str_remove_chars(struct nk_str*, int len); NK_API void nk_str_remove_runes(struct nk_str *str, int len); NK_API void nk_str_delete_chars(struct nk_str*, int pos, int len); NK_API void nk_str_delete_runes(struct nk_str*, int pos, int len); NK_API char *nk_str_at_char(struct nk_str*, int pos); NK_API char *nk_str_at_rune(struct nk_str*, int pos, nk_rune *unicode, int *len); NK_API nk_rune nk_str_rune_at(const struct nk_str*, int pos); NK_API const char *nk_str_at_char_const(const struct nk_str*, int pos); NK_API const char *nk_str_at_const(const struct nk_str*, int pos, nk_rune *unicode, int *len); NK_API char *nk_str_get(struct nk_str*); NK_API const char *nk_str_get_const(const struct nk_str*); NK_API int nk_str_len(struct nk_str*); NK_API int nk_str_len_char(struct nk_str*); /*=============================================================== * * TEXT EDITOR * * ===============================================================*/ /* Editing text in this library is handled by either `nk_edit_string` or * `nk_edit_buffer`. But like almost everything in this library there are multiple * ways of doing it and a balance between control and ease of use with memory * as well as functionality controlled by flags. * * This library generally allows three different levels of memory control: * First of is the most basic way of just providing a simple char array with * string length. This method is probably the easiest way of handling simple * user text input. Main upside is complete control over memory while the biggest * downside in comparsion with the other two approaches is missing undo/redo. * * For UIs that require undo/redo the second way was created. It is based on * a fixed size nk_text_edit struct, which has an internal undo/redo stack. * This is mainly useful if you want something more like a text editor but don't want * to have a dynamically growing buffer. * * The final way is using a dynamically growing nk_text_edit struct, which * has both a default version if you don't care where memory comes from and an * allocator version if you do. While the text editor is quite powerful for its * complexity I would not recommend editing gigabytes of data with it. * It is rather designed for uses cases which make sense for a GUI library not for * an full blown text editor. */ #ifndef NK_TEXTEDIT_UNDOSTATECOUNT #define NK_TEXTEDIT_UNDOSTATECOUNT 99 #endif #ifndef NK_TEXTEDIT_UNDOCHARCOUNT #define NK_TEXTEDIT_UNDOCHARCOUNT 999 #endif struct nk_text_edit; struct nk_clipboard { nk_handle userdata; nk_plugin_paste paste; nk_plugin_copy copy; }; struct nk_text_undo_record { int where; short insert_length; short delete_length; short char_storage; }; struct nk_text_undo_state { struct nk_text_undo_record undo_rec[NK_TEXTEDIT_UNDOSTATECOUNT]; nk_rune undo_char[NK_TEXTEDIT_UNDOCHARCOUNT]; short undo_point; short redo_point; short undo_char_point; short redo_char_point; }; enum nk_text_edit_type { NK_TEXT_EDIT_SINGLE_LINE, NK_TEXT_EDIT_MULTI_LINE }; enum nk_text_edit_mode { NK_TEXT_EDIT_MODE_VIEW, NK_TEXT_EDIT_MODE_INSERT, NK_TEXT_EDIT_MODE_REPLACE }; struct nk_text_edit { struct nk_clipboard clip; struct nk_str string; nk_plugin_filter filter; struct nk_vec2 scrollbar; int cursor; int select_start; int select_end; unsigned char mode; unsigned char cursor_at_end_of_line; unsigned char initialized; unsigned char has_preferred_x; unsigned char single_line; unsigned char active; unsigned char padding1; float preferred_x; struct nk_text_undo_state undo; }; /* filter function */ NK_API int nk_filter_default(const struct nk_text_edit*, nk_rune unicode); NK_API int nk_filter_ascii(const struct nk_text_edit*, nk_rune unicode); NK_API int nk_filter_float(const struct nk_text_edit*, nk_rune unicode); NK_API int nk_filter_decimal(const struct nk_text_edit*, nk_rune unicode); NK_API int nk_filter_hex(const struct nk_text_edit*, nk_rune unicode); NK_API int nk_filter_oct(const struct nk_text_edit*, nk_rune unicode); NK_API int nk_filter_binary(const struct nk_text_edit*, nk_rune unicode); /* text editor */ #ifdef NK_INCLUDE_DEFAULT_ALLOCATOR NK_API void nk_textedit_init_default(struct nk_text_edit*); #endif NK_API void nk_textedit_init(struct nk_text_edit*, struct nk_allocator*, nk_size size); NK_API void nk_textedit_init_fixed(struct nk_text_edit*, void *memory, nk_size size); NK_API void nk_textedit_free(struct nk_text_edit*); NK_API void nk_textedit_text(struct nk_text_edit*, const char*, int total_len); NK_API void nk_textedit_delete(struct nk_text_edit*, int where, int len); NK_API void nk_textedit_delete_selection(struct nk_text_edit*); NK_API void nk_textedit_select_all(struct nk_text_edit*); NK_API int nk_textedit_cut(struct nk_text_edit*); NK_API int nk_textedit_paste(struct nk_text_edit*, char const*, int len); NK_API void nk_textedit_undo(struct nk_text_edit*); NK_API void nk_textedit_redo(struct nk_text_edit*); /* =============================================================== * * FONT * * ===============================================================*/ /* Font handling in this library was designed to be quite customizable and lets you decide what you want to use and what you want to provide. In this sense there are four different degrees between control and ease of use and two different drawing APIs to provide for. So first of the easiest way to do font handling is by just providing a `nk_user_font` struct which only requires the height in pixel of the used font and a callback to calculate the width of a string. This way of handling fonts is best fitted for using the normal draw shape command API were you do all the text drawing yourself and the library does not require any kind of deeper knowledge about which font handling mechanism you use. While the first approach works fine if you don't want to use the optional vertex buffer output it is not enough if you do. To get font handling working for these cases you have to provide two additional parameters inside the `nk_user_font`. First a texture atlas handle used to draw text as subimages of a bigger font atlas texture and a callback to query a character's glyph information (offset, size, ...). So it is still possible to provide your own font and use the vertex buffer output. The final approach if you do not have a font handling functionality or don't want to use it in this library is by using the optional font baker. This API is divided into a high- and low-level API with different priorities between ease of use and control. Both API's can be used to create a font and font atlas texture and can even be used with or without the vertex buffer output. So it still uses the `nk_user_font` struct and the two different approaches previously stated still work. Now to the difference between the low level API and the high level API. The low level API provides a lot of control over the baking process of the font and provides total control over memory. It consists of a number of functions that need to be called from begin to end and each step requires some additional configuration, so it is a lot more complex than the high-level API. If you don't want to do all the work required for using the low-level API you can use the font atlas API. It provides the same functionality as the low-level API but takes away some configuration and all of memory control and in term provides a easier to use API. */ struct nk_user_font_glyph; typedef float(*nk_text_width_f)(nk_handle, float h, const char*, int len); typedef void(*nk_query_font_glyph_f)(nk_handle handle, float font_height, struct nk_user_font_glyph *glyph, nk_rune codepoint, nk_rune next_codepoint); #ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT struct nk_user_font_glyph { struct nk_vec2 uv[2]; /* texture coordinates */ struct nk_vec2 offset; /* offset between top left and glyph */ float width, height; /* size of the glyph */ float xadvance; /* offset to the next glyph */ }; #endif struct nk_user_font { nk_handle userdata; /* user provided font handle */ float height; /* max height of the font */ nk_text_width_f width; /* font string width in pixel callback */ #ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT nk_query_font_glyph_f query; /* font glyph callback to query drawing info */ nk_handle texture; /* texture handle to the used font atlas or texture */ #endif }; #ifdef NK_INCLUDE_FONT_BAKING enum nk_font_coord_type { NK_COORD_UV, /* texture coordinates inside font glyphs are clamped between 0-1 */ NK_COORD_PIXEL /* texture coordinates inside font glyphs are in absolute pixel */ }; struct nk_baked_font { float height; /* height of the font */ float ascent, descent; /* font glyphs ascent and descent */ nk_rune glyph_offset; /* glyph array offset inside the font glyph baking output array */ nk_rune glyph_count; /* number of glyphs of this font inside the glyph baking array output */ const nk_rune *ranges; /* font codepoint ranges as pairs of (from/to) and 0 as last element */ }; struct nk_font_config { struct nk_font_config *next; /* NOTE: only used internally */ void *ttf_blob; /* pointer to loaded TTF file memory block. * NOTE: not needed for nk_font_atlas_add_from_memory and nk_font_atlas_add_from_file. */ nk_size ttf_size; /* size of the loaded TTF file memory block * NOTE: not needed for nk_font_atlas_add_from_memory and nk_font_atlas_add_from_file. */ unsigned char ttf_data_owned_by_atlas; /* used inside font atlas: default to: 0*/ unsigned char merge_mode; /* merges this font into the last font */ unsigned char pixel_snap; /* align every character to pixel boundary (if true set oversample (1,1)) */ unsigned char oversample_v, oversample_h; /* rasterize at hight quality for sub-pixel position */ unsigned char padding[3]; float size; /* baked pixel height of the font */ enum nk_font_coord_type coord_type; /* texture coordinate format with either pixel or UV coordinates */ struct nk_vec2 spacing; /* extra pixel spacing between glyphs */ const nk_rune *range; /* list of unicode ranges (2 values per range, zero terminated) */ struct nk_baked_font *font; /* font to setup in the baking process: NOTE: not needed for font atlas */ nk_rune fallback_glyph; /* fallback glyph to use if a given rune is not found */ }; struct nk_font_glyph { nk_rune codepoint; float xadvance; float x0, y0, x1, y1, w, h; float u0, v0, u1, v1; }; struct nk_font { struct nk_font *next; struct nk_user_font handle; struct nk_baked_font info; float scale; struct nk_font_glyph *glyphs; const struct nk_font_glyph *fallback; nk_rune fallback_codepoint; nk_handle texture; struct nk_font_config *config; }; enum nk_font_atlas_format { NK_FONT_ATLAS_ALPHA8, NK_FONT_ATLAS_RGBA32 }; struct nk_font_atlas { void *pixel; int tex_width; int tex_height; struct nk_allocator permanent; struct nk_allocator temporary; struct nk_recti custom; struct nk_cursor cursors[NK_CURSOR_COUNT]; int glyph_count; struct nk_font_glyph *glyphs; struct nk_font *default_font; struct nk_font *fonts; struct nk_font_config *config; int font_num; }; /* some language glyph codepoint ranges */ NK_API const nk_rune *nk_font_default_glyph_ranges(void); NK_API const nk_rune *nk_font_chinese_glyph_ranges(void); NK_API const nk_rune *nk_font_cyrillic_glyph_ranges(void); NK_API const nk_rune *nk_font_korean_glyph_ranges(void); #ifdef NK_INCLUDE_DEFAULT_ALLOCATOR NK_API void nk_font_atlas_init_default(struct nk_font_atlas*); #endif NK_API void nk_font_atlas_init(struct nk_font_atlas*, struct nk_allocator*); NK_API void nk_font_atlas_init_custom(struct nk_font_atlas*, struct nk_allocator *persistent, struct nk_allocator *transient); NK_API void nk_font_atlas_begin(struct nk_font_atlas*); NK_API struct nk_font_config nk_font_config(float pixel_height); NK_API struct nk_font *nk_font_atlas_add(struct nk_font_atlas*, const struct nk_font_config*); #ifdef NK_INCLUDE_DEFAULT_FONT NK_API struct nk_font* nk_font_atlas_add_default(struct nk_font_atlas*, float height, const struct nk_font_config*); #endif NK_API struct nk_font* nk_font_atlas_add_from_memory(struct nk_font_atlas *atlas, void *memory, nk_size size, float height, const struct nk_font_config *config); #ifdef NK_INCLUDE_STANDARD_IO NK_API struct nk_font* nk_font_atlas_add_from_file(struct nk_font_atlas *atlas, const char *file_path, float height, const struct nk_font_config*); #endif NK_API struct nk_font *nk_font_atlas_add_compressed(struct nk_font_atlas*, void *memory, nk_size size, float height, const struct nk_font_config*); NK_API struct nk_font* nk_font_atlas_add_compressed_base85(struct nk_font_atlas*, const char *data, float height, const struct nk_font_config *config); NK_API const void* nk_font_atlas_bake(struct nk_font_atlas*, int *width, int *height, enum nk_font_atlas_format); NK_API void nk_font_atlas_end(struct nk_font_atlas*, nk_handle tex, struct nk_draw_null_texture*); NK_API void nk_font_atlas_clear(struct nk_font_atlas*); NK_API const struct nk_font_glyph* nk_font_find_glyph(struct nk_font*, nk_rune unicode); #endif /* =============================================================== * * DRAWING * * ===============================================================*/ /* This library was designed to be render backend agnostic so it does not draw anything to screen. Instead all drawn shapes, widgets are made of, are buffered into memory and make up a command queue. Each frame therefore fills the command buffer with draw commands that then need to be executed by the user and his own render backend. After that the command buffer needs to be cleared and a new frame can be started. It is probably important to note that the command buffer is the main drawing API and the optional vertex buffer API only takes this format and converts it into a hardware accessible format. Draw commands are divided into filled shapes and shape outlines but only filled shapes as well as line, curves and scissor are required to be provided. All other shape drawing commands can be used but are not required. This was done to allow the maximum number of render backends to be able to use this library without you having to do additional work. */ enum nk_command_type { NK_COMMAND_NOP, NK_COMMAND_SCISSOR, NK_COMMAND_LINE, NK_COMMAND_CURVE, NK_COMMAND_RECT, NK_COMMAND_RECT_FILLED, NK_COMMAND_RECT_MULTI_COLOR, NK_COMMAND_CIRCLE, NK_COMMAND_CIRCLE_FILLED, NK_COMMAND_ARC, NK_COMMAND_ARC_FILLED, NK_COMMAND_TRIANGLE, NK_COMMAND_TRIANGLE_FILLED, NK_COMMAND_POLYGON, NK_COMMAND_POLYGON_FILLED, NK_COMMAND_POLYLINE, NK_COMMAND_TEXT, NK_COMMAND_IMAGE }; /* command base and header of every command inside the buffer */ struct nk_command { enum nk_command_type type; nk_size next; #ifdef NK_INCLUDE_COMMAND_USERDATA nk_handle userdata; #endif }; struct nk_command_scissor { struct nk_command header; short x, y; unsigned short w, h; }; struct nk_command_line { struct nk_command header; unsigned short line_thickness; struct nk_vec2i begin; struct nk_vec2i end; struct nk_color color; }; struct nk_command_curve { struct nk_command header; unsigned short line_thickness; struct nk_vec2i begin; struct nk_vec2i end; struct nk_vec2i ctrl[2]; struct nk_color color; }; struct nk_command_rect { struct nk_command header; unsigned short rounding; unsigned short line_thickness; short x, y; unsigned short w, h; struct nk_color color; }; struct nk_command_rect_filled { struct nk_command header; unsigned short rounding; short x, y; unsigned short w, h; struct nk_color color; }; struct nk_command_rect_multi_color { struct nk_command header; short x, y; unsigned short w, h; struct nk_color left; struct nk_color top; struct nk_color bottom; struct nk_color right; }; struct nk_command_triangle { struct nk_command header; unsigned short line_thickness; struct nk_vec2i a; struct nk_vec2i b; struct nk_vec2i c; struct nk_color color; }; struct nk_command_triangle_filled { struct nk_command header; struct nk_vec2i a; struct nk_vec2i b; struct nk_vec2i c; struct nk_color color; }; struct nk_command_circle { struct nk_command header; short x, y; unsigned short line_thickness; unsigned short w, h; struct nk_color color; }; struct nk_command_circle_filled { struct nk_command header; short x, y; unsigned short w, h; struct nk_color color; }; struct nk_command_arc { struct nk_command header; short cx, cy; unsigned short r; unsigned short line_thickness; float a[2]; struct nk_color color; }; struct nk_command_arc_filled { struct nk_command header; short cx, cy; unsigned short r; float a[2]; struct nk_color color; }; struct nk_command_polygon { struct nk_command header; struct nk_color color; unsigned short line_thickness; unsigned short point_count; struct nk_vec2i points[1]; }; struct nk_command_polygon_filled { struct nk_command header; struct nk_color color; unsigned short point_count; struct nk_vec2i points[1]; }; struct nk_command_polyline { struct nk_command header; struct nk_color color; unsigned short line_thickness; unsigned short point_count; struct nk_vec2i points[1]; }; struct nk_command_image { struct nk_command header; short x, y; unsigned short w, h; struct nk_image img; struct nk_color col; }; struct nk_command_text { struct nk_command header; const struct nk_user_font *font; struct nk_color background; struct nk_color foreground; short x, y; unsigned short w, h; float height; int length; char string[1]; }; enum nk_command_clipping { NK_CLIPPING_OFF = nk_false, NK_CLIPPING_ON = nk_true }; struct nk_command_buffer { struct nk_buffer *base; struct nk_rect clip; int use_clipping; nk_handle userdata; nk_size begin, end, last; }; /* shape outlines */ NK_API void nk_stroke_line(struct nk_command_buffer *b, float x0, float y0, float x1, float y1, float line_thickness, struct nk_color); NK_API void nk_stroke_curve(struct nk_command_buffer*, float, float, float, float, float, float, float, float, float line_thickness, struct nk_color); NK_API void nk_stroke_rect(struct nk_command_buffer*, struct nk_rect, float rounding, float line_thickness, struct nk_color); NK_API void nk_stroke_circle(struct nk_command_buffer*, struct nk_rect, float line_thickness, struct nk_color); NK_API void nk_stroke_arc(struct nk_command_buffer*, float cx, float cy, float radius, float a_min, float a_max, float line_thickness, struct nk_color); NK_API void nk_stroke_triangle(struct nk_command_buffer*, float, float, float, float, float, float, float line_thichness, struct nk_color); NK_API void nk_stroke_polyline(struct nk_command_buffer*, float *points, int point_count, float line_thickness, struct nk_color col); NK_API void nk_stroke_polygon(struct nk_command_buffer*, float*, int point_count, float line_thickness, struct nk_color); /* filled shades */ NK_API void nk_fill_rect(struct nk_command_buffer*, struct nk_rect, float rounding, struct nk_color); NK_API void nk_fill_rect_multi_color(struct nk_command_buffer*, struct nk_rect, struct nk_color left, struct nk_color top, struct nk_color right, struct nk_color bottom); NK_API void nk_fill_circle(struct nk_command_buffer*, struct nk_rect, struct nk_color); NK_API void nk_fill_arc(struct nk_command_buffer*, float cx, float cy, float radius, float a_min, float a_max, struct nk_color); NK_API void nk_fill_triangle(struct nk_command_buffer*, float x0, float y0, float x1, float y1, float x2, float y2, struct nk_color); NK_API void nk_fill_polygon(struct nk_command_buffer*, float*, int point_count, struct nk_color); /* misc */ NK_API void nk_push_scissor(struct nk_command_buffer*, struct nk_rect); NK_API void nk_draw_image(struct nk_command_buffer*, struct nk_rect, const struct nk_image*, struct nk_color); NK_API void nk_draw_text(struct nk_command_buffer*, struct nk_rect, const char *text, int len, const struct nk_user_font*, struct nk_color, struct nk_color); NK_API const struct nk_command* nk__next(struct nk_context*, const struct nk_command*); NK_API const struct nk_command* nk__begin(struct nk_context*); /* =============================================================== * * INPUT * * ===============================================================*/ struct nk_mouse_button { int down; unsigned int clicked; struct nk_vec2 clicked_pos; }; struct nk_mouse { struct nk_mouse_button buttons[NK_BUTTON_MAX]; struct nk_vec2 pos; struct nk_vec2 prev; struct nk_vec2 delta; float scroll_delta; unsigned char grab; unsigned char grabbed; unsigned char ungrab; }; struct nk_key { int down; unsigned int clicked; }; struct nk_keyboard { struct nk_key keys[NK_KEY_MAX]; char text[NK_INPUT_MAX]; int text_len; }; struct nk_input { struct nk_keyboard keyboard; struct nk_mouse mouse; }; NK_API int nk_input_has_mouse_click(const struct nk_input*, enum nk_buttons); NK_API int nk_input_has_mouse_click_in_rect(const struct nk_input*, enum nk_buttons, struct nk_rect); NK_API int nk_input_has_mouse_click_down_in_rect(const struct nk_input*, enum nk_buttons, struct nk_rect, int down); NK_API int nk_input_is_mouse_click_in_rect(const struct nk_input*, enum nk_buttons, struct nk_rect); NK_API int nk_input_is_mouse_click_down_in_rect(const struct nk_input *i, enum nk_buttons id, struct nk_rect b, int down); NK_API int nk_input_any_mouse_click_in_rect(const struct nk_input*, struct nk_rect); NK_API int nk_input_is_mouse_prev_hovering_rect(const struct nk_input*, struct nk_rect); NK_API int nk_input_is_mouse_hovering_rect(const struct nk_input*, struct nk_rect); NK_API int nk_input_mouse_clicked(const struct nk_input*, enum nk_buttons, struct nk_rect); NK_API int nk_input_is_mouse_down(const struct nk_input*, enum nk_buttons); NK_API int nk_input_is_mouse_pressed(const struct nk_input*, enum nk_buttons); NK_API int nk_input_is_mouse_released(const struct nk_input*, enum nk_buttons); NK_API int nk_input_is_key_pressed(const struct nk_input*, enum nk_keys); NK_API int nk_input_is_key_released(const struct nk_input*, enum nk_keys); NK_API int nk_input_is_key_down(const struct nk_input*, enum nk_keys); /* =============================================================== * * DRAW LIST * * ===============================================================*/ #ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT /* The optional vertex buffer draw list provides a 2D drawing context with antialiasing functionality which takes basic filled or outlined shapes or a path and outputs vertexes, elements and draw commands. The actual draw list API is not required to be used directly while using this library since converting the default library draw command output is done by just calling `nk_convert` but I decided to still make this library accessible since it can be useful. The draw list is based on a path buffering and polygon and polyline rendering API which allows a lot of ways to draw 2D content to screen. In fact it is probably more powerful than needed but allows even more crazy things than this library provides by default. */ typedef nk_ushort nk_draw_index; enum nk_draw_list_stroke { NK_STROKE_OPEN = nk_false, /* build up path has no connection back to the beginning */ NK_STROKE_CLOSED = nk_true /* build up path has a connection back to the beginning */ }; enum nk_draw_vertex_layout_attribute { NK_VERTEX_POSITION, NK_VERTEX_COLOR, NK_VERTEX_TEXCOORD, NK_VERTEX_ATTRIBUTE_COUNT }; enum nk_draw_vertex_layout_format { NK_FORMAT_SCHAR, NK_FORMAT_SSHORT, NK_FORMAT_SINT, NK_FORMAT_UCHAR, NK_FORMAT_USHORT, NK_FORMAT_UINT, NK_FORMAT_FLOAT, NK_FORMAT_DOUBLE, NK_FORMAT_COLOR_BEGIN, NK_FORMAT_R8G8B8 = NK_FORMAT_COLOR_BEGIN, NK_FORMAT_R16G15B16, NK_FORMAT_R32G32B32, NK_FORMAT_R8G8B8A8, NK_FORMAT_R16G15B16A16, NK_FORMAT_R32G32B32A32, NK_FORMAT_R32G32B32A32_FLOAT, NK_FORMAT_R32G32B32A32_DOUBLE, NK_FORMAT_RGB32, NK_FORMAT_RGBA32, NK_FORMAT_COLOR_END = NK_FORMAT_RGBA32, NK_FORMAT_COUNT }; #define NK_VERTEX_LAYOUT_END NK_VERTEX_ATTRIBUTE_COUNT,NK_FORMAT_COUNT,0 struct nk_draw_vertex_layout_element { enum nk_draw_vertex_layout_attribute attribute; enum nk_draw_vertex_layout_format format; nk_size offset; }; struct nk_draw_command { unsigned int elem_count; /* number of elements in the current draw batch */ struct nk_rect clip_rect; /* current screen clipping rectangle */ nk_handle texture; /* current texture to set */ #ifdef NK_INCLUDE_COMMAND_USERDATA nk_handle userdata; #endif }; struct nk_draw_list { struct nk_convert_config config; struct nk_rect clip_rect; struct nk_buffer *buffer; struct nk_buffer *vertices; struct nk_buffer *elements; unsigned int element_count; unsigned int vertex_count; nk_size cmd_offset; unsigned int cmd_count; unsigned int path_count; unsigned int path_offset; struct nk_vec2 circle_vtx[12]; #ifdef NK_INCLUDE_COMMAND_USERDATA nk_handle userdata; #endif }; /* draw list */ NK_API void nk_draw_list_init(struct nk_draw_list*); NK_API void nk_draw_list_setup(struct nk_draw_list *canvas, const struct nk_convert_config *config, struct nk_buffer *cmds, struct nk_buffer *vertices, struct nk_buffer *elements); NK_API void nk_draw_list_clear(struct nk_draw_list*); /* drawing */ #define nk_draw_list_foreach(cmd, can, b) for((cmd)=nk__draw_list_begin(can, b); (cmd)!=0; (cmd)=nk__draw_list_next(cmd, b, can)) NK_API const struct nk_draw_command* nk__draw_list_begin(const struct nk_draw_list*, const struct nk_buffer*); NK_API const struct nk_draw_command* nk__draw_list_next(const struct nk_draw_command*, const struct nk_buffer*, const struct nk_draw_list*); NK_API const struct nk_draw_command* nk__draw_list_end(const struct nk_draw_list*, const struct nk_buffer*); NK_API void nk_draw_list_clear(struct nk_draw_list *list); /* path */ NK_API void nk_draw_list_path_clear(struct nk_draw_list*); NK_API void nk_draw_list_path_line_to(struct nk_draw_list *list, struct nk_vec2 pos); NK_API void nk_draw_list_path_arc_to_fast(struct nk_draw_list*, struct nk_vec2 center, float radius, int a_min, int a_max); NK_API void nk_draw_list_path_arc_to(struct nk_draw_list*, struct nk_vec2 center, float radius, float a_min, float a_max, unsigned int segments); NK_API void nk_draw_list_path_rect_to(struct nk_draw_list*, struct nk_vec2 a, struct nk_vec2 b, float rounding); NK_API void nk_draw_list_path_curve_to(struct nk_draw_list*, struct nk_vec2 p2, struct nk_vec2 p3, struct nk_vec2 p4, unsigned int num_segments); NK_API void nk_draw_list_path_fill(struct nk_draw_list*, struct nk_color); NK_API void nk_draw_list_path_stroke(struct nk_draw_list*, struct nk_color, enum nk_draw_list_stroke closed, float thickness); /* stroke */ NK_API void nk_draw_list_stroke_line(struct nk_draw_list*, struct nk_vec2 a, struct nk_vec2 b, struct nk_color, float thickness); NK_API void nk_draw_list_stroke_rect(struct nk_draw_list*, struct nk_rect rect, struct nk_color, float rounding, float thickness); NK_API void nk_draw_list_stroke_triangle(struct nk_draw_list*, struct nk_vec2 a, struct nk_vec2 b, struct nk_vec2 c, struct nk_color, float thickness); NK_API void nk_draw_list_stroke_circle(struct nk_draw_list*, struct nk_vec2 center, float radius, struct nk_color, unsigned int segs, float thickness); NK_API void nk_draw_list_stroke_curve(struct nk_draw_list*, struct nk_vec2 p0, struct nk_vec2 cp0, struct nk_vec2 cp1, struct nk_vec2 p1, struct nk_color, unsigned int segments, float thickness); NK_API void nk_draw_list_stroke_poly_line(struct nk_draw_list*, const struct nk_vec2 *pnts, const unsigned int cnt, struct nk_color, enum nk_draw_list_stroke, float thickness, enum nk_anti_aliasing); /* fill */ NK_API void nk_draw_list_fill_rect(struct nk_draw_list*, struct nk_rect rect, struct nk_color, float rounding); NK_API void nk_draw_list_fill_rect_multi_color(struct nk_draw_list *list, struct nk_rect rect, struct nk_color left, struct nk_color top, struct nk_color right, struct nk_color bottom); NK_API void nk_draw_list_fill_triangle(struct nk_draw_list*, struct nk_vec2 a, struct nk_vec2 b, struct nk_vec2 c, struct nk_color); NK_API void nk_draw_list_fill_circle(struct nk_draw_list*, struct nk_vec2 center, float radius, struct nk_color col, unsigned int segs); NK_API void nk_draw_list_fill_poly_convex(struct nk_draw_list*, const struct nk_vec2 *points, const unsigned int count, struct nk_color, enum nk_anti_aliasing); /* misc */ NK_API void nk_draw_list_add_image(struct nk_draw_list*, struct nk_image texture, struct nk_rect rect, struct nk_color); NK_API void nk_draw_list_add_text(struct nk_draw_list*, const struct nk_user_font*, struct nk_rect, const char *text, int len, float font_height, struct nk_color); #ifdef NK_INCLUDE_COMMAND_USERDATA NK_API void nk_draw_list_push_userdata(struct nk_draw_list*, nk_handle userdata); #endif #endif /* =============================================================== * * GUI * * ===============================================================*/ enum nk_style_item_type { NK_STYLE_ITEM_COLOR, NK_STYLE_ITEM_IMAGE }; union nk_style_item_data { struct nk_image image; struct nk_color color; }; struct nk_style_item { enum nk_style_item_type type; union nk_style_item_data data; }; struct nk_style_text { struct nk_color color; struct nk_vec2 padding; }; struct nk_style_button { /* background */ struct nk_style_item normal; struct nk_style_item hover; struct nk_style_item active; struct nk_color border_color; /* text */ struct nk_color text_background; struct nk_color text_normal; struct nk_color text_hover; struct nk_color text_active; nk_flags text_alignment; /* properties */ float border; float rounding; struct nk_vec2 padding; struct nk_vec2 image_padding; struct nk_vec2 touch_padding; /* optional user callbacks */ nk_handle userdata; void(*draw_begin)(struct nk_command_buffer*, nk_handle userdata); void(*draw_end)(struct nk_command_buffer*, nk_handle userdata); }; struct nk_style_toggle { /* background */ struct nk_style_item normal; struct nk_style_item hover; struct nk_style_item active; struct nk_color border_color; /* cursor */ struct nk_style_item cursor_normal; struct nk_style_item cursor_hover; /* text */ struct nk_color text_normal; struct nk_color text_hover; struct nk_color text_active; struct nk_color text_background; nk_flags text_alignment; /* properties */ struct nk_vec2 padding; struct nk_vec2 touch_padding; float spacing; float border; /* optional user callbacks */ nk_handle userdata; void(*draw_begin)(struct nk_command_buffer*, nk_handle); void(*draw_end)(struct nk_command_buffer*, nk_handle); }; struct nk_style_selectable { /* background (inactive) */ struct nk_style_item normal; struct nk_style_item hover; struct nk_style_item pressed; /* background (active) */ struct nk_style_item normal_active; struct nk_style_item hover_active; struct nk_style_item pressed_active; /* text color (inactive) */ struct nk_color text_normal; struct nk_color text_hover; struct nk_color text_pressed; /* text color (active) */ struct nk_color text_normal_active; struct nk_color text_hover_active; struct nk_color text_pressed_active; struct nk_color text_background; nk_flags text_alignment; /* properties */ float rounding; struct nk_vec2 padding; struct nk_vec2 touch_padding; struct nk_vec2 image_padding; /* optional user callbacks */ nk_handle userdata; void(*draw_begin)(struct nk_command_buffer*, nk_handle); void(*draw_end)(struct nk_command_buffer*, nk_handle); }; struct nk_style_slider { /* background */ struct nk_style_item normal; struct nk_style_item hover; struct nk_style_item active; struct nk_color border_color; /* background bar */ struct nk_color bar_normal; struct nk_color bar_hover; struct nk_color bar_active; struct nk_color bar_filled; /* cursor */ struct nk_style_item cursor_normal; struct nk_style_item cursor_hover; struct nk_style_item cursor_active; /* properties */ float border; float rounding; float bar_height; struct nk_vec2 padding; struct nk_vec2 spacing; struct nk_vec2 cursor_size; /* optional buttons */ int show_buttons; struct nk_style_button inc_button; struct nk_style_button dec_button; enum nk_symbol_type inc_symbol; enum nk_symbol_type dec_symbol; /* optional user callbacks */ nk_handle userdata; void(*draw_begin)(struct nk_command_buffer*, nk_handle); void(*draw_end)(struct nk_command_buffer*, nk_handle); }; struct nk_style_progress { /* background */ struct nk_style_item normal; struct nk_style_item hover; struct nk_style_item active; struct nk_color border_color; /* cursor */ struct nk_style_item cursor_normal; struct nk_style_item cursor_hover; struct nk_style_item cursor_active; struct nk_color cursor_border_color; /* properties */ float rounding; float border; float cursor_border; float cursor_rounding; struct nk_vec2 padding; /* optional user callbacks */ nk_handle userdata; void(*draw_begin)(struct nk_command_buffer*, nk_handle); void(*draw_end)(struct nk_command_buffer*, nk_handle); }; struct nk_style_scrollbar { /* background */ struct nk_style_item normal; struct nk_style_item hover; struct nk_style_item active; struct nk_color border_color; /* cursor */ struct nk_style_item cursor_normal; struct nk_style_item cursor_hover; struct nk_style_item cursor_active; struct nk_color cursor_border_color; /* properties */ float border; float rounding; float border_cursor; float rounding_cursor; struct nk_vec2 padding; /* optional buttons */ int show_buttons; struct nk_style_button inc_button; struct nk_style_button dec_button; enum nk_symbol_type inc_symbol; enum nk_symbol_type dec_symbol; /* optional user callbacks */ nk_handle userdata; void(*draw_begin)(struct nk_command_buffer*, nk_handle); void(*draw_end)(struct nk_command_buffer*, nk_handle); }; struct nk_style_edit { /* background */ struct nk_style_item normal; struct nk_style_item hover; struct nk_style_item active; struct nk_color border_color; struct nk_style_scrollbar scrollbar; /* cursor */ struct nk_color cursor_normal; struct nk_color cursor_hover; struct nk_color cursor_text_normal; struct nk_color cursor_text_hover; /* text (unselected) */ struct nk_color text_normal; struct nk_color text_hover; struct nk_color text_active; /* text (selected) */ struct nk_color selected_normal; struct nk_color selected_hover; struct nk_color selected_text_normal; struct nk_color selected_text_hover; /* properties */ float border; float rounding; float cursor_size; struct nk_vec2 scrollbar_size; struct nk_vec2 padding; float row_padding; }; struct nk_style_property { /* background */ struct nk_style_item normal; struct nk_style_item hover; struct nk_style_item active; struct nk_color border_color; /* text */ struct nk_color label_normal; struct nk_color label_hover; struct nk_color label_active; /* symbols */ enum nk_symbol_type sym_left; enum nk_symbol_type sym_right; /* properties */ float border; float rounding; struct nk_vec2 padding; struct nk_style_edit edit; struct nk_style_button inc_button; struct nk_style_button dec_button; /* optional user callbacks */ nk_handle userdata; void(*draw_begin)(struct nk_command_buffer*, nk_handle); void(*draw_end)(struct nk_command_buffer*, nk_handle); }; struct nk_style_chart { /* colors */ struct nk_style_item background; struct nk_color border_color; struct nk_color selected_color; struct nk_color color; /* properties */ float border; float rounding; struct nk_vec2 padding; }; struct nk_style_combo { /* background */ struct nk_style_item normal; struct nk_style_item hover; struct nk_style_item active; struct nk_color border_color; /* label */ struct nk_color label_normal; struct nk_color label_hover; struct nk_color label_active; /* symbol */ struct nk_color symbol_normal; struct nk_color symbol_hover; struct nk_color symbol_active; /* button */ struct nk_style_button button; enum nk_symbol_type sym_normal; enum nk_symbol_type sym_hover; enum nk_symbol_type sym_active; /* properties */ float border; float rounding; struct nk_vec2 content_padding; struct nk_vec2 button_padding; struct nk_vec2 spacing; }; struct nk_style_tab { /* background */ struct nk_style_item background; struct nk_color border_color; struct nk_color text; /* button */ struct nk_style_button tab_maximize_button; struct nk_style_button tab_minimize_button; struct nk_style_button node_maximize_button; struct nk_style_button node_minimize_button; enum nk_symbol_type sym_minimize; enum nk_symbol_type sym_maximize; /* properties */ float border; float rounding; float indent; struct nk_vec2 padding; struct nk_vec2 spacing; }; enum nk_style_header_align { NK_HEADER_LEFT, NK_HEADER_RIGHT }; struct nk_style_window_header { /* background */ struct nk_style_item normal; struct nk_style_item hover; struct nk_style_item active; /* button */ struct nk_style_button close_button; struct nk_style_button minimize_button; enum nk_symbol_type close_symbol; enum nk_symbol_type minimize_symbol; enum nk_symbol_type maximize_symbol; /* title */ struct nk_color label_normal; struct nk_color label_hover; struct nk_color label_active; /* properties */ enum nk_style_header_align align; struct nk_vec2 padding; struct nk_vec2 label_padding; struct nk_vec2 spacing; }; struct nk_style_window { struct nk_style_window_header header; struct nk_style_item fixed_background; struct nk_color background; struct nk_color border_color; struct nk_color popup_border_color; struct nk_color combo_border_color; struct nk_color contextual_border_color; struct nk_color menu_border_color; struct nk_color group_border_color; struct nk_color tooltip_border_color; struct nk_style_item scaler; float border; float combo_border; float contextual_border; float menu_border; float group_border; float tooltip_border; float popup_border; float rounding; struct nk_vec2 spacing; struct nk_vec2 scrollbar_size; struct nk_vec2 min_size; struct nk_vec2 padding; struct nk_vec2 group_padding; struct nk_vec2 popup_padding; struct nk_vec2 combo_padding; struct nk_vec2 contextual_padding; struct nk_vec2 menu_padding; struct nk_vec2 tooltip_padding; }; struct nk_style { const struct nk_user_font *font; const struct nk_cursor *cursors[NK_CURSOR_COUNT]; const struct nk_cursor *cursor_active; struct nk_cursor *cursor_last; int cursor_visible; struct nk_style_text text; struct nk_style_button button; struct nk_style_button contextual_button; struct nk_style_button menu_button; struct nk_style_toggle option; struct nk_style_toggle checkbox; struct nk_style_selectable selectable; struct nk_style_slider slider; struct nk_style_progress progress; struct nk_style_property property; struct nk_style_edit edit; struct nk_style_chart chart; struct nk_style_scrollbar scrollh; struct nk_style_scrollbar scrollv; struct nk_style_tab tab; struct nk_style_combo combo; struct nk_style_window window; }; NK_API struct nk_style_item nk_style_item_image(struct nk_image img); NK_API struct nk_style_item nk_style_item_color(struct nk_color); NK_API struct nk_style_item nk_style_item_hide(void); /*============================================================== * PANEL * =============================================================*/ #ifndef NK_CHART_MAX_SLOT #define NK_CHART_MAX_SLOT 4 #endif enum nk_panel_type { NK_PANEL_WINDOW = NK_FLAG(0), NK_PANEL_GROUP = NK_FLAG(1), NK_PANEL_POPUP = NK_FLAG(2), NK_PANEL_CONTEXTUAL = NK_FLAG(4), NK_PANEL_COMBO = NK_FLAG(5), NK_PANEL_MENU = NK_FLAG(6), NK_PANEL_TOOLTIP = NK_FLAG(7) }; enum nk_panel_set { NK_PANEL_SET_NONBLOCK = NK_PANEL_CONTEXTUAL|NK_PANEL_COMBO|NK_PANEL_MENU|NK_PANEL_TOOLTIP, NK_PANEL_SET_POPUP = NK_PANEL_SET_NONBLOCK|NK_PANEL_POPUP, NK_PANEL_SET_SUB = NK_PANEL_SET_POPUP|NK_PANEL_GROUP }; struct nk_chart_slot { enum nk_chart_type type; struct nk_color color; struct nk_color highlight; float min, max, range; int count; struct nk_vec2 last; int index; }; struct nk_chart { struct nk_chart_slot slots[NK_CHART_MAX_SLOT]; int slot; float x, y, w, h; }; struct nk_row_layout { int type; int index; float height; int columns; const float *ratio; float item_width, item_height; float item_offset; float filled; struct nk_rect item; int tree_depth; }; struct nk_popup_buffer { nk_size begin; nk_size parent; nk_size last; nk_size end; int active; }; struct nk_menu_state { float x, y, w, h; struct nk_scroll offset; }; struct nk_panel { enum nk_panel_type type; nk_flags flags; struct nk_rect bounds; struct nk_scroll *offset; float at_x, at_y, max_x; float footer_height; float header_height; float border; unsigned int has_scrolling; struct nk_rect clip; struct nk_menu_state menu; struct nk_row_layout row; struct nk_chart chart; struct nk_popup_buffer popup_buffer; struct nk_command_buffer *buffer; struct nk_panel *parent; }; /*============================================================== * WINDOW * =============================================================*/ #ifndef NK_WINDOW_MAX_NAME #define NK_WINDOW_MAX_NAME 64 #endif struct nk_table; enum nk_window_flags { NK_WINDOW_PRIVATE = NK_FLAG(10), NK_WINDOW_DYNAMIC = NK_WINDOW_PRIVATE, /* special window type growing up in height while being filled to a certain maximum height */ NK_WINDOW_ROM = NK_FLAG(11), /* sets the window into a read only mode and does not allow input changes */ NK_WINDOW_HIDDEN = NK_FLAG(12), /* Hides the window and stops any window interaction and drawing */ NK_WINDOW_CLOSED = NK_FLAG(13), /* Directly closes and frees the window at the end of the frame */ NK_WINDOW_MINIMIZED = NK_FLAG(14), /* marks the window as minimized */ NK_WINDOW_REMOVE_ROM = NK_FLAG(15) /* Removes the read only mode at the end of the window */ }; struct nk_popup_state { struct nk_window *win; enum nk_panel_type type; nk_hash name; int active; unsigned combo_count; unsigned con_count, con_old; unsigned active_con; struct nk_rect header; }; struct nk_edit_state { nk_hash name; unsigned int seq; unsigned int old; int active, prev; int cursor; int sel_start; int sel_end; struct nk_scroll scrollbar; unsigned char mode; unsigned char single_line; }; struct nk_property_state { int active, prev; char buffer[NK_MAX_NUMBER_BUFFER]; int length; int cursor; nk_hash name; unsigned int seq; unsigned int old; int state; }; struct nk_window { unsigned int seq; nk_hash name; char name_string[NK_WINDOW_MAX_NAME]; nk_flags flags; struct nk_rect bounds; struct nk_scroll scrollbar; struct nk_command_buffer buffer; struct nk_panel *layout; float scrollbar_hiding_timer; /* persistent widget state */ struct nk_property_state property; struct nk_popup_state popup; struct nk_edit_state edit; unsigned int scrolled; struct nk_table *tables; unsigned short table_count; unsigned short table_size; /* window list hooks */ struct nk_window *next; struct nk_window *prev; struct nk_window *parent; }; /*============================================================== * STACK * =============================================================*/ #ifndef NK_BUTTON_BEHAVIOR_STACK_SIZE #define NK_BUTTON_BEHAVIOR_STACK_SIZE 8 #endif #ifndef NK_FONT_STACK_SIZE #define NK_FONT_STACK_SIZE 8 #endif #ifndef NK_STYLE_ITEM_STACK_SIZE #define NK_STYLE_ITEM_STACK_SIZE 16 #endif #ifndef NK_FLOAT_STACK_SIZE #define NK_FLOAT_STACK_SIZE 32 #endif #ifndef NK_VECTOR_STACK_SIZE #define NK_VECTOR_STACK_SIZE 16 #endif #ifndef NK_FLAGS_STACK_SIZE #define NK_FLAGS_STACK_SIZE 32 #endif #ifndef NK_COLOR_STACK_SIZE #define NK_COLOR_STACK_SIZE 32 #endif #define NK_CONFIGURATION_STACK_TYPE(prefix, name, type)\ struct nk_config_stack_##name##_element {\ prefix##_##type *address;\ prefix##_##type old_value;\ } #define NK_CONFIG_STACK(type,size)\ struct nk_config_stack_##type {\ int head;\ struct nk_config_stack_##type##_element elements[size];\ } #define nk_float float NK_CONFIGURATION_STACK_TYPE(struct nk, style_item, style_item); NK_CONFIGURATION_STACK_TYPE(nk ,float, float); NK_CONFIGURATION_STACK_TYPE(struct nk, vec2, vec2); NK_CONFIGURATION_STACK_TYPE(nk ,flags, flags); NK_CONFIGURATION_STACK_TYPE(struct nk, color, color); NK_CONFIGURATION_STACK_TYPE(const struct nk, user_font, user_font*); NK_CONFIGURATION_STACK_TYPE(enum nk, button_behavior, button_behavior); NK_CONFIG_STACK(style_item, NK_STYLE_ITEM_STACK_SIZE); NK_CONFIG_STACK(float, NK_FLOAT_STACK_SIZE); NK_CONFIG_STACK(vec2, NK_VECTOR_STACK_SIZE); NK_CONFIG_STACK(flags, NK_FLAGS_STACK_SIZE); NK_CONFIG_STACK(color, NK_COLOR_STACK_SIZE); NK_CONFIG_STACK(user_font, NK_FONT_STACK_SIZE); NK_CONFIG_STACK(button_behavior, NK_BUTTON_BEHAVIOR_STACK_SIZE); struct nk_configuration_stacks { struct nk_config_stack_style_item style_items; struct nk_config_stack_float floats; struct nk_config_stack_vec2 vectors; struct nk_config_stack_flags flags; struct nk_config_stack_color colors; struct nk_config_stack_user_font fonts; struct nk_config_stack_button_behavior button_behaviors; }; /*============================================================== * CONTEXT * =============================================================*/ #define NK_VALUE_PAGE_CAPACITY ((sizeof(struct nk_window) / sizeof(nk_uint)) / 2) struct nk_table { unsigned int seq; nk_hash keys[NK_VALUE_PAGE_CAPACITY]; nk_uint values[NK_VALUE_PAGE_CAPACITY]; struct nk_table *next, *prev; }; union nk_page_data { struct nk_table tbl; struct nk_window win; }; struct nk_page_element { union nk_page_data data; struct nk_page_element *next; struct nk_page_element *prev; }; struct nk_page { unsigned size; struct nk_page *next; struct nk_page_element win[1]; }; struct nk_pool { struct nk_allocator alloc; enum nk_allocation_type type; unsigned int page_count; struct nk_page *pages; struct nk_page_element *freelist; unsigned capacity; nk_size size; nk_size cap; }; struct nk_context { /* public: can be accessed freely */ struct nk_input input; struct nk_style style; struct nk_buffer memory; struct nk_clipboard clip; nk_flags last_widget_state; float delta_time_seconds; enum nk_button_behavior button_behavior; struct nk_configuration_stacks stacks; /* private: should only be accessed if you know what you are doing */ #ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT struct nk_draw_list draw_list; #endif #ifdef NK_INCLUDE_COMMAND_USERDATA nk_handle userdata; #endif /* text editor objects are quite big because of an internal * undo/redo stack. Therefore does not make sense to have one for * each window for temporary use cases, so I only provide *one* instance * for all windows. This works because the content is cleared anyway */ struct nk_text_edit text_edit; /* draw buffer used for overlay drawing operation like cursor */ struct nk_command_buffer overlay; /* windows */ int build; int use_pool; struct nk_pool pool; struct nk_window *begin; struct nk_window *end; struct nk_window *active; struct nk_window *current; struct nk_page_element *freelist; unsigned int count; unsigned int seq; }; /* ============================================================== * MATH * =============================================================== */ #define NK_MIN(a,b) ((a) < (b) ? (a) : (b)) #define NK_MAX(a,b) ((a) < (b) ? (b) : (a)) #define NK_CLAMP(i,v,x) (NK_MAX(NK_MIN(v,x), i)) #define NK_PI 3.141592654f #define NK_UTF_INVALID 0xFFFD #define NK_MAX_FLOAT_PRECISION 2 #define NK_UNUSED(x) ((void)(x)) #define NK_SATURATE(x) (NK_MAX(0, NK_MIN(1.0f, x))) #define NK_LEN(a) (sizeof(a)/sizeof(a)[0]) #define NK_ABS(a) (((a) < 0) ? -(a) : (a)) #define NK_BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b)) #define NK_INBOX(px, py, x, y, w, h)\ (NK_BETWEEN(px,x,x+w) && NK_BETWEEN(py,y,y+h)) #define NK_INTERSECT(x0, y0, w0, h0, x1, y1, w1, h1) \ (!(((x1 > (x0 + w0)) || ((x1 + w1) < x0) || (y1 > (y0 + h0)) || (y1 + h1) < y0))) #define NK_CONTAINS(x, y, w, h, bx, by, bw, bh)\ (NK_INBOX(x,y, bx, by, bw, bh) && NK_INBOX(x+w,y+h, bx, by, bw, bh)) #define nk_vec2_sub(a, b) nk_vec2((a).x - (b).x, (a).y - (b).y) #define nk_vec2_add(a, b) nk_vec2((a).x + (b).x, (a).y + (b).y) #define nk_vec2_len_sqr(a) ((a).x*(a).x+(a).y*(a).y) #define nk_vec2_muls(a, t) nk_vec2((a).x * (t), (a).y * (t)) #define nk_ptr_add(t, p, i) ((t*)((void*)((nk_byte*)(p) + (i)))) #define nk_ptr_add_const(t, p, i) ((const t*)((const void*)((const nk_byte*)(p) + (i)))) #define nk_zero_struct(s) nk_zero(&s, sizeof(s)) /* ============================================================== * ALIGNMENT * =============================================================== */ /* Pointer to Integer type conversion for pointer alignment */ #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC*/ # define NK_UINT_TO_PTR(x) ((void*)(__PTRDIFF_TYPE__)(x)) # define NK_PTR_TO_UINT(x) ((nk_size)(__PTRDIFF_TYPE__)(x)) #elif !defined(__GNUC__) /* works for compilers other than LLVM */ # define NK_UINT_TO_PTR(x) ((void*)&((char*)0)[x]) # define NK_PTR_TO_UINT(x) ((nk_size)(((char*)x)-(char*)0)) #elif defined(NK_USE_FIXED_TYPES) /* used if we have <stdint.h> */ # define NK_UINT_TO_PTR(x) ((void*)(uintptr_t)(x)) # define NK_PTR_TO_UINT(x) ((uintptr_t)(x)) #else /* generates warning but works */ # define NK_UINT_TO_PTR(x) ((void*)(x)) # define NK_PTR_TO_UINT(x) ((nk_size)(x)) #endif #define NK_ALIGN_PTR(x, mask)\ (NK_UINT_TO_PTR((NK_PTR_TO_UINT((nk_byte*)(x) + (mask-1)) & ~(mask-1)))) #define NK_ALIGN_PTR_BACK(x, mask)\ (NK_UINT_TO_PTR((NK_PTR_TO_UINT((nk_byte*)(x)) & ~(mask-1)))) #define NK_OFFSETOF(st,m) ((nk_ptr)&(((st*)0)->m)) #define NK_CONTAINER_OF(ptr,type,member)\ (type*)((void*)((char*)(1 ? (ptr): &((type*)0)->member) - NK_OFFSETOF(type, member))) #ifdef __cplusplus } #endif #ifdef __cplusplus template<typename T> struct nk_alignof; template<typename T, int size_diff> struct nk_helper{enum {value = size_diff};}; template<typename T> struct nk_helper<T,0>{enum {value = nk_alignof<T>::value};}; template<typename T> struct nk_alignof{struct Big {T x; char c;}; enum { diff = sizeof(Big) - sizeof(T), value = nk_helper<Big, diff>::value};}; #define NK_ALIGNOF(t) (nk_alignof<t>::value); #elif defined(_MSC_VER) #define NK_ALIGNOF(t) (__alignof(t)) #else #define NK_ALIGNOF(t) ((char*)(&((struct {char c; t _h;}*)0)->_h) - (char*)0) #endif #endif /* NK_H_ */ /* * ============================================================== * * IMPLEMENTATION * * =============================================================== */ #ifdef NK_IMPLEMENTATION #ifndef NK_POOL_DEFAULT_CAPACITY #define NK_POOL_DEFAULT_CAPACITY 16 #endif #ifndef NK_DEFAULT_COMMAND_BUFFER_SIZE #define NK_DEFAULT_COMMAND_BUFFER_SIZE (4*1024) #endif #ifndef NK_BUFFER_DEFAULT_INITIAL_SIZE #define NK_BUFFER_DEFAULT_INITIAL_SIZE (4*1024) #endif /* standard library headers */ #ifdef NK_INCLUDE_DEFAULT_ALLOCATOR #include <stdlib.h> /* malloc, free */ #endif #ifdef NK_INCLUDE_STANDARD_IO #include <stdio.h> /* fopen, fclose,... */ #endif #ifdef NK_INCLUDE_STANDARD_VARARGS #include <stdarg.h> /* valist, va_start, va_end, ... */ #endif #ifndef NK_ASSERT #include <assert.h> #define NK_ASSERT(expr) assert(expr) #endif #ifndef NK_MEMSET #define NK_MEMSET nk_memset #endif #ifndef NK_MEMCPY #define NK_MEMCPY nk_memcopy #endif #ifndef NK_SQRT #define NK_SQRT nk_sqrt #endif #ifndef NK_SIN #define NK_SIN nk_sin #endif #ifndef NK_COS #define NK_COS nk_cos #endif #ifndef NK_STRTOD #define NK_STRTOD nk_strtod #endif #ifndef NK_DTOA #define NK_DTOA nk_dtoa #endif #define NK_DEFAULT (-1) #ifndef NK_VSNPRINTF /* If your compiler does support `vsnprintf` I would highly recommend * defining this to vsnprintf instead since `vsprintf` is basically * unbelievable unsafe and should *NEVER* be used. But I have to support * it since C89 only provides this unsafe version. */ #if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) ||\ (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ (defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200112L)) ||\ (defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE >= 500)) ||\ defined(_ISOC99_SOURCE) || defined(_BSD_SOURCE) #define NK_VSNPRINTF(s,n,f,a) vsnprintf(s,n,f,a) #else #define NK_VSNPRINTF(s,n,f,a) vsprintf(s,f,a) #endif #endif #define NK_SCHAR_MIN (-127) #define NK_SCHAR_MAX 127 #define NK_UCHAR_MIN 0 #define NK_UCHAR_MAX 256 #define NK_SSHORT_MIN (-32767) #define NK_SSHORT_MAX 32767 #define NK_USHORT_MIN 0 #define NK_USHORT_MAX 65535 #define NK_SINT_MIN (-2147483647) #define NK_SINT_MAX 2147483647 #define NK_UINT_MIN 0 #define NK_UINT_MAX 4294967295 /* Make sure correct type size: * This will fire with a negative subscript error if the type sizes * are set incorrectly by the compiler, and compile out if not */ NK_STATIC_ASSERT(sizeof(nk_size) >= sizeof(void*)); NK_STATIC_ASSERT(sizeof(nk_ptr) == sizeof(void*)); NK_STATIC_ASSERT(sizeof(nk_flags) >= 4); NK_STATIC_ASSERT(sizeof(nk_rune) >= 4); NK_STATIC_ASSERT(sizeof(nk_ushort) == 2); NK_STATIC_ASSERT(sizeof(nk_short) == 2); NK_STATIC_ASSERT(sizeof(nk_uint) == 4); NK_STATIC_ASSERT(sizeof(nk_int) == 4); NK_STATIC_ASSERT(sizeof(nk_byte) == 1); NK_GLOBAL const struct nk_rect nk_null_rect = {-8192.0f, -8192.0f, 16384, 16384}; #define NK_FLOAT_PRECISION 0.00000000000001 NK_GLOBAL const struct nk_color nk_red = {255,0,0,255}; NK_GLOBAL const struct nk_color nk_green = {0,255,0,255}; NK_GLOBAL const struct nk_color nk_blue = {0,0,255,255}; NK_GLOBAL const struct nk_color nk_white = {255,255,255,255}; NK_GLOBAL const struct nk_color nk_black = {0,0,0,255}; NK_GLOBAL const struct nk_color nk_yellow = {255,255,0,255}; /* * ============================================================== * * MATH * * =============================================================== */ /* Since nuklear is supposed to work on all systems providing floating point math without any dependencies I also had to implement my own math functions for sqrt, sin and cos. Since the actual highly accurate implementations for the standard library functions are quite complex and I do not need high precision for my use cases I use approximations. Sqrt ---- For square root nuklear uses the famous fast inverse square root: https://en.wikipedia.org/wiki/Fast_inverse_square_root with slightly tweaked magic constant. While on todays hardware it is probably not faster it is still fast and accurate enough for nuklear's use cases. IMPORTANT: this requires float format IEEE 754 Sine/Cosine ----------- All constants inside both function are generated Remez's minimax approximations for value range 0...2*PI. The reason why I decided to approximate exactly that range is that nuklear only needs sine and cosine to generate circles which only requires that exact range. In addition I used Remez instead of Taylor for additional precision: www.lolengine.net/blog/2011/12/21/better-function-approximatations. The tool I used to generate constants for both sine and cosine (it can actually approximate a lot more functions) can be found here: www.lolengine.net/wiki/oss/lolremez */ NK_INTERN float nk_inv_sqrt(float number) { float x2; const float threehalfs = 1.5f; union {nk_uint i; float f;} conv = {0}; conv.f = number; x2 = number * 0.5f; conv.i = 0x5f375A84 - (conv.i >> 1); conv.f = conv.f * (threehalfs - (x2 * conv.f * conv.f)); return conv.f; } NK_INTERN float nk_sqrt(float x) { return x * nk_inv_sqrt(x); } NK_INTERN float nk_sin(float x) { NK_STORAGE const float a0 = +1.91059300966915117e-31f; NK_STORAGE const float a1 = +1.00086760103908896f; NK_STORAGE const float a2 = -1.21276126894734565e-2f; NK_STORAGE const float a3 = -1.38078780785773762e-1f; NK_STORAGE const float a4 = -2.67353392911981221e-2f; NK_STORAGE const float a5 = +2.08026600266304389e-2f; NK_STORAGE const float a6 = -3.03996055049204407e-3f; NK_STORAGE const float a7 = +1.38235642404333740e-4f; return a0 + x*(a1 + x*(a2 + x*(a3 + x*(a4 + x*(a5 + x*(a6 + x*a7)))))); } NK_INTERN float nk_cos(float x) { NK_STORAGE const float a0 = +1.00238601909309722f; NK_STORAGE const float a1 = -3.81919947353040024e-2f; NK_STORAGE const float a2 = -3.94382342128062756e-1f; NK_STORAGE const float a3 = -1.18134036025221444e-1f; NK_STORAGE const float a4 = +1.07123798512170878e-1f; NK_STORAGE const float a5 = -1.86637164165180873e-2f; NK_STORAGE const float a6 = +9.90140908664079833e-4f; NK_STORAGE const float a7 = -5.23022132118824778e-14f; return a0 + x*(a1 + x*(a2 + x*(a3 + x*(a4 + x*(a5 + x*(a6 + x*a7)))))); } NK_INTERN nk_uint nk_round_up_pow2(nk_uint v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } NK_API struct nk_rect nk_get_null_rect(void) { return nk_null_rect; } NK_API struct nk_rect nk_rect(float x, float y, float w, float h) { struct nk_rect r; r.x = x, r.y = y; r.w = w, r.h = h; return r; } NK_API struct nk_rect nk_recti(int x, int y, int w, int h) { struct nk_rect r; r.x = (float)x; r.y = (float)y; r.w = (float)w; r.h = (float)h; return r; } NK_API struct nk_rect nk_recta(struct nk_vec2 pos, struct nk_vec2 size) { return nk_rect(pos.x, pos.y, size.x, size.y); } NK_API struct nk_rect nk_rectv(const float *r) { return nk_rect(r[0], r[1], r[2], r[3]); } NK_API struct nk_rect nk_rectiv(const int *r) { return nk_recti(r[0], r[1], r[2], r[3]); } NK_API struct nk_vec2 nk_rect_pos(struct nk_rect r) { struct nk_vec2 ret; ret.x = r.x; ret.y = r.y; return ret; } NK_API struct nk_vec2 nk_rect_size(struct nk_rect r) { struct nk_vec2 ret; ret.x = r.w; ret.y = r.h; return ret; } NK_INTERN struct nk_rect nk_shrink_rect(struct nk_rect r, float amount) { struct nk_rect res; r.w = NK_MAX(r.w, 2 * amount); r.h = NK_MAX(r.h, 2 * amount); res.x = r.x + amount; res.y = r.y + amount; res.w = r.w - 2 * amount; res.h = r.h - 2 * amount; return res; } NK_INTERN struct nk_rect nk_pad_rect(struct nk_rect r, struct nk_vec2 pad) { r.w = NK_MAX(r.w, 2 * pad.x); r.h = NK_MAX(r.h, 2 * pad.y); r.x += pad.x; r.y += pad.y; r.w -= 2 * pad.x; r.h -= 2 * pad.y; return r; } NK_API struct nk_vec2 nk_vec2(float x, float y) { struct nk_vec2 ret; ret.x = x; ret.y = y; return ret; } NK_API struct nk_vec2 nk_vec2i(int x, int y) { struct nk_vec2 ret; ret.x = (float)x; ret.y = (float)y; return ret; } NK_API struct nk_vec2 nk_vec2v(const float *v) { return nk_vec2(v[0], v[1]); } NK_API struct nk_vec2 nk_vec2iv(const int *v) { return nk_vec2i(v[0], v[1]); } /* * ============================================================== * * UTIL * * =============================================================== */ NK_INTERN int nk_str_match_here(const char *regexp, const char *text); NK_INTERN int nk_str_match_star(int c, const char *regexp, const char *text); NK_INTERN int nk_is_lower(int c) {return (c >= 'a' && c <= 'z') || (c >= 0xE0 && c <= 0xFF);} NK_INTERN int nk_is_upper(int c){return (c >= 'A' && c <= 'Z') || (c >= 0xC0 && c <= 0xDF);} NK_INTERN int nk_to_upper(int c) {return (c >= 'a' && c <= 'z') ? (c - ('a' - 'A')) : c;} NK_INTERN int nk_to_lower(int c) {return (c >= 'A' && c <= 'Z') ? (c - ('a' + 'A')) : c;} NK_INTERN void* nk_memcopy(void *dst0, const void *src0, nk_size length) { nk_ptr t; char *dst = (char*)dst0; const char *src = (const char*)src0; if (length == 0 || dst == src) goto done; #define nk_word int #define nk_wsize sizeof(nk_word) #define nk_wmask (nk_wsize-1) #define NK_TLOOP(s) if (t) NK_TLOOP1(s) #define NK_TLOOP1(s) do { s; } while (--t) if (dst < src) { t = (nk_ptr)src; /* only need low bits */ if ((t | (nk_ptr)dst) & nk_wmask) { if ((t ^ (nk_ptr)dst) & nk_wmask || length < nk_wsize) t = length; else t = nk_wsize - (t & nk_wmask); length -= t; NK_TLOOP1(*dst++ = *src++); } t = length / nk_wsize; NK_TLOOP(*(nk_word*)(void*)dst = *(const nk_word*)(const void*)src; src += nk_wsize; dst += nk_wsize); t = length & nk_wmask; NK_TLOOP(*dst++ = *src++); } else { src += length; dst += length; t = (nk_ptr)src; if ((t | (nk_ptr)dst) & nk_wmask) { if ((t ^ (nk_ptr)dst) & nk_wmask || length <= nk_wsize) t = length; else t &= nk_wmask; length -= t; NK_TLOOP1(*--dst = *--src); } t = length / nk_wsize; NK_TLOOP(src -= nk_wsize; dst -= nk_wsize; *(nk_word*)(void*)dst = *(const nk_word*)(const void*)src); t = length & nk_wmask; NK_TLOOP(*--dst = *--src); } #undef nk_word #undef nk_wsize #undef nk_wmask #undef NK_TLOOP #undef NK_TLOOP1 done: return (dst0); } NK_INTERN void nk_memset(void *ptr, int c0, nk_size size) { #define nk_word unsigned #define nk_wsize sizeof(nk_word) #define nk_wmask (nk_wsize - 1) nk_byte *dst = (nk_byte*)ptr; unsigned c = 0; nk_size t = 0; if ((c = (nk_byte)c0) != 0) { c = (c << 8) | c; /* at least 16-bits */ if (sizeof(unsigned int) > 2) c = (c << 16) | c; /* at least 32-bits*/ } /* too small of a word count */ dst = (nk_byte*)ptr; if (size < 3 * nk_wsize) { while (size--) *dst++ = (nk_byte)c0; return; } /* align destination */ if ((t = NK_PTR_TO_UINT(dst) & nk_wmask) != 0) { t = nk_wsize -t; size -= t; do { *dst++ = (nk_byte)c0; } while (--t != 0); } /* fill word */ t = size / nk_wsize; do { *(nk_word*)((void*)dst) = c; dst += nk_wsize; } while (--t != 0); /* fill trailing bytes */ t = (size & nk_wmask); if (t != 0) { do { *dst++ = (nk_byte)c0; } while (--t != 0); } #undef nk_word #undef nk_wsize #undef nk_wmask } NK_INTERN void nk_zero(void *ptr, nk_size size) { NK_ASSERT(ptr); NK_MEMSET(ptr, 0, size); } NK_API int nk_strlen(const char *str) { int siz = 0; NK_ASSERT(str); while (str && *str++ != '\0') siz++; return siz; } NK_API int nk_strtoi(const char *str, char **endptr) { int neg = 1; const char *p = str; int value = 0; NK_ASSERT(str); if (!str) return 0; /* skip whitespace */ while (*p == ' ') p++; if (*p == '-') { neg = -1; p++; } while (*p && *p >= '0' && *p <= '9') { value = value * 10 + (int) (*p - '0'); p++; } if (endptr) *endptr = (char*)p; return neg*value; } NK_API double nk_strtod(const char *str, char **endptr) { double m; double neg = 1.0; const char *p = str; double value = 0; double number = 0; NK_ASSERT(str); if (!str) return 0; /* skip whitespace */ while (*p == ' ') p++; if (*p == '-') { neg = -1.0; p++; } while (*p && *p != '.' && *p != 'e') { value = value * 10.0 + (double) (*p - '0'); p++; } if (*p == '.') { p++; for(m = 0.1; *p && *p != 'e'; p++ ) { value = value + (double) (*p - '0') * m; m *= 0.1; } } if (*p == 'e') { int i, pow, div; p++; if (*p == '-') { div = nk_true; p++; } else if (*p == '+') { div = nk_false; p++; } else div = nk_false; for (pow = 0; *p; p++) pow = pow * 10 + (int) (*p - '0'); for (m = 1.0, i = 0; i < pow; i++) m *= 10.0; if (div) value /= m; else value *= m; } number = value * neg; if (endptr) *endptr = (char*)p; return number; } NK_API float nk_strtof(const char *str, char **endptr) { float float_value; double double_value; double_value = NK_STRTOD(str, endptr); float_value = (float)double_value; return float_value; } NK_API int nk_stricmp(const char *s1, const char *s2) { nk_int c1,c2,d; do { c1 = *s1++; c2 = *s2++; d = c1 - c2; while (d) { if (c1 <= 'Z' && c1 >= 'A') { d += ('a' - 'A'); if (!d) break; } if (c2 <= 'Z' && c2 >= 'A') { d -= ('a' - 'A'); if (!d) break; } return ((d >= 0) << 1) - 1; } } while (c1); return 0; } NK_API int nk_stricmpn(const char *s1, const char *s2, int n) { int c1,c2,d; NK_ASSERT(n >= 0); do { c1 = *s1++; c2 = *s2++; if (!n--) return 0; d = c1 - c2; while (d) { if (c1 <= 'Z' && c1 >= 'A') { d += ('a' - 'A'); if (!d) break; } if (c2 <= 'Z' && c2 >= 'A') { d -= ('a' - 'A'); if (!d) break; } return ((d >= 0) << 1) - 1; } } while (c1); return 0; } NK_INTERN int nk_str_match_here(const char *regexp, const char *text) { if (regexp[0] == '\0') return 1; if (regexp[1] == '*') return nk_str_match_star(regexp[0], regexp+2, text); if (regexp[0] == '$' && regexp[1] == '\0') return *text == '\0'; if (*text!='\0' && (regexp[0]=='.' || regexp[0]==*text)) return nk_str_match_here(regexp+1, text+1); return 0; } NK_INTERN int nk_str_match_star(int c, const char *regexp, const char *text) { do {/* a '* matches zero or more instances */ if (nk_str_match_here(regexp, text)) return 1; } while (*text != '\0' && (*text++ == c || c == '.')); return 0; } NK_API int nk_strfilter(const char *text, const char *regexp) { /* c matches any literal character c . matches any single character ^ matches the beginning of the input string $ matches the end of the input string * matches zero or more occurrences of the previous character*/ if (regexp[0] == '^') return nk_str_match_here(regexp+1, text); do { /* must look even if string is empty */ if (nk_str_match_here(regexp, text)) return 1; } while (*text++ != '\0'); return 0; } NK_API int nk_strmatch_fuzzy_text(const char *str, int str_len, const char *pattern, int *out_score) { /* Returns true if each character in pattern is found sequentially within str * if found then outScore is also set. Score value has no intrinsic meaning. * Range varies with pattern. Can only compare scores with same search pattern. */ /* ------- scores --------- */ /* bonus for adjacent matches */ #define NK_ADJACENCY_BONUS 5 /* bonus if match occurs after a separator */ #define NK_SEPARATOR_BONUS 10 /* bonus if match is uppercase and prev is lower */ #define NK_CAMEL_BONUS 10 /* penalty applied for every letter in str before the first match */ #define NK_LEADING_LETTER_PENALTY (-3) /* maximum penalty for leading letters */ #define NK_MAX_LEADING_LETTER_PENALTY (-9) /* penalty for every letter that doesn't matter */ #define NK_UNMATCHED_LETTER_PENALTY (-1) /* loop variables */ int score = 0; char const * pattern_iter = pattern; int str_iter = 0; int prev_matched = nk_false; int prev_lower = nk_false; /* true so if first letter match gets separator bonus*/ int prev_separator = nk_true; /* use "best" matched letter if multiple string letters match the pattern */ char const * best_letter = 0; int best_letter_score = 0; /* loop over strings */ NK_ASSERT(str); NK_ASSERT(pattern); if (!str || !str_len || !pattern) return 0; while (str_iter < str_len) { const char pattern_letter = *pattern_iter; const char str_letter = str[str_iter]; int next_match = *pattern_iter != '\0' && nk_to_lower(pattern_letter) == nk_to_lower(str_letter); int rematch = best_letter && nk_to_lower(*best_letter) == nk_to_lower(str_letter); int advanced = next_match && best_letter; int pattern_repeat = best_letter && *pattern_iter != '\0'; pattern_repeat = pattern_repeat && nk_to_lower(*best_letter) == nk_to_lower(pattern_letter); if (advanced || pattern_repeat) { score += best_letter_score; best_letter = 0; best_letter_score = 0; } if (next_match || rematch) { int new_score = 0; /* Apply penalty for each letter before the first pattern match */ if (pattern_iter == pattern) { int count = (int)(&str[str_iter] - str); int penalty = NK_LEADING_LETTER_PENALTY * count; if (penalty < NK_MAX_LEADING_LETTER_PENALTY) penalty = NK_MAX_LEADING_LETTER_PENALTY; score += penalty; } /* apply bonus for consecutive bonuses */ if (prev_matched) new_score += NK_ADJACENCY_BONUS; /* apply bonus for matches after a separator */ if (prev_separator) new_score += NK_SEPARATOR_BONUS; /* apply bonus across camel case boundaries */ if (prev_lower && nk_is_upper(str_letter)) new_score += NK_CAMEL_BONUS; /* update pattern iter IFF the next pattern letter was matched */ if (next_match) ++pattern_iter; /* update best letter in str which may be for a "next" letter or a rematch */ if (new_score >= best_letter_score) { /* apply penalty for now skipped letter */ if (best_letter != 0) score += NK_UNMATCHED_LETTER_PENALTY; best_letter = &str[str_iter]; best_letter_score = new_score; } prev_matched = nk_true; } else { score += NK_UNMATCHED_LETTER_PENALTY; prev_matched = nk_false; } /* separators should be more easily defined */ prev_lower = nk_is_lower(str_letter) != 0; prev_separator = str_letter == '_' || str_letter == ' '; ++str_iter; } /* apply score for last match */ if (best_letter) score += best_letter_score; /* did not match full pattern */ if (*pattern_iter != '\0') return nk_false; if (out_score) *out_score = score; return nk_true; } NK_API int nk_strmatch_fuzzy_string(char const *str, char const *pattern, int *out_score) {return nk_strmatch_fuzzy_text(str, nk_strlen(str), pattern, out_score);} NK_INTERN int nk_string_float_limit(char *string, int prec) { int dot = 0; char *c = string; while (*c) { if (*c == '.') { dot = 1; c++; continue; } if (dot == (prec+1)) { *c = 0; break; } if (dot > 0) dot++; c++; } return (int)(c - string); } NK_INTERN double nk_pow(double x, int n) { /* check the sign of n */ double r = 1; int plus = n >= 0; n = (plus) ? n : -n; while (n > 0) { if ((n & 1) == 1) r *= x; n /= 2; x *= x; } return plus ? r : 1.0 / r; } NK_INTERN int nk_ifloord(double x) { x = (double)((int)x - ((x < 0.0) ? 1 : 0)); return (int)x; } NK_INTERN int nk_ifloorf(float x) { x = (float)((int)x - ((x < 0.0f) ? 1 : 0)); return (int)x; } NK_INTERN int nk_iceilf(float x) { if (x >= 0) { int i = (int)x; return i; } else { int t = (int)x; float r = x - (float)t; return (r > 0.0f) ? t+1: t; } } NK_INTERN int nk_log10(double n) { int neg; int ret; int exp = 0; neg = (n < 0) ? 1 : 0; ret = (neg) ? (int)-n : (int)n; while ((ret / 10) > 0) { ret /= 10; exp++; } if (neg) exp = -exp; return exp; } NK_INTERN void nk_strrev_ascii(char *s) { int len = nk_strlen(s); int end = len / 2; int i = 0; char t; for (; i < end; ++i) { t = s[i]; s[i] = s[len - 1 - i]; s[len -1 - i] = t; } } NK_INTERN char* nk_itoa(char *s, long n) { long i = 0; if (n == 0) { s[i++] = '0'; s[i] = 0; return s; } if (n < 0) { s[i++] = '-'; n = -n; } while (n > 0) { s[i++] = (char)('0' + (n % 10)); n /= 10; } s[i] = 0; if (s[0] == '-') ++s; nk_strrev_ascii(s); return s; } NK_INTERN char* nk_dtoa(char *s, double n) { int useExp = 0; int digit = 0, m = 0, m1 = 0; char *c = s; int neg = 0; NK_ASSERT(s); if (!s) return 0; if (n == 0.0) { s[0] = '0'; s[1] = '\0'; return s; } neg = (n < 0); if (neg) n = -n; /* calculate magnitude */ m = nk_log10(n); useExp = (m >= 14 || (neg && m >= 9) || m <= -9); if (neg) *(c++) = '-'; /* set up for scientific notation */ if (useExp) { if (m < 0) m -= 1; n = n / (double)nk_pow(10.0, m); m1 = m; m = 0; } if (m < 1.0) { m = 0; } /* convert the number */ while (n > NK_FLOAT_PRECISION || m >= 0) { double weight = nk_pow(10.0, m); if (weight > 0) { double t = (double)n / weight; digit = nk_ifloord(t); n -= ((double)digit * weight); *(c++) = (char)('0' + (char)digit); } if (m == 0 && n > 0) *(c++) = '.'; m--; } if (useExp) { /* convert the exponent */ int i, j; *(c++) = 'e'; if (m1 > 0) { *(c++) = '+'; } else { *(c++) = '-'; m1 = -m1; } m = 0; while (m1 > 0) { *(c++) = (char)('0' + (char)(m1 % 10)); m1 /= 10; m++; } c -= m; for (i = 0, j = m-1; i<j; i++, j--) { /* swap without temporary */ c[i] ^= c[j]; c[j] ^= c[i]; c[i] ^= c[j]; } c += m; } *(c) = '\0'; return s; } #ifdef NK_INCLUDE_STANDARD_VARARGS static int nk_vsnprintf(char *buf, int buf_size, const char *fmt, va_list args) { enum nk_arg_type { NK_ARG_TYPE_CHAR, NK_ARG_TYPE_SHORT, NK_ARG_TYPE_DEFAULT, NK_ARG_TYPE_LONG }; enum nk_arg_flags { NK_ARG_FLAG_LEFT = 0x01, NK_ARG_FLAG_PLUS = 0x02, NK_ARG_FLAG_SPACE = 0x04, NK_ARG_FLAG_NUM = 0x10, NK_ARG_FLAG_ZERO = 0x20 }; char number_buffer[NK_MAX_NUMBER_BUFFER]; enum nk_arg_type arg_type = NK_ARG_TYPE_DEFAULT; int precision = NK_DEFAULT; int width = NK_DEFAULT; nk_flags flag = 0; int len = 0; const char *iter = fmt; int result = -1; NK_ASSERT(buf); NK_ASSERT(buf_size); if (!buf || !buf_size || !fmt) return 0; for (iter = fmt; *iter && len < buf_size; iter++) { /* copy all non-format characters */ while (*iter && (*iter != '%') && (len < buf_size)) buf[len++] = *iter++; if (!(*iter) || len >= buf_size) break; iter++; /* flag arguments */ while (*iter) { if (*iter == '-') flag |= NK_ARG_FLAG_LEFT; else if (*iter == '+') flag |= NK_ARG_FLAG_PLUS; else if (*iter == ' ') flag |= NK_ARG_FLAG_SPACE; else if (*iter == '#') flag |= NK_ARG_FLAG_NUM; else if (*iter == '0') flag |= NK_ARG_FLAG_ZERO; else break; iter++; } /* width argument */ width = NK_DEFAULT; if (*iter >= '1' && *iter <= '9') { char *end; width = nk_strtoi(iter, &end); if (end == iter) width = -1; else iter = end; } else if (*iter == '*') { width = va_arg(args, int); iter++; } /* precision argument */ precision = NK_DEFAULT; if (*iter == '.') { iter++; if (*iter == '*') { precision = va_arg(args, int); iter++; } else { char *end; precision = nk_strtoi(iter, &end); if (end == iter) precision = -1; else iter = end; } } /* length modifier */ if (*iter == 'h') { if (*(iter+1) == 'h') { arg_type = NK_ARG_TYPE_CHAR; iter++; } else arg_type = NK_ARG_TYPE_SHORT; iter++; } else if (*iter == 'l') { arg_type = NK_ARG_TYPE_LONG; iter++; } else arg_type = NK_ARG_TYPE_DEFAULT; /* specifier */ if (*iter == '%') { NK_ASSERT(arg_type == NK_ARG_TYPE_DEFAULT); NK_ASSERT(precision == NK_DEFAULT); NK_ASSERT(width == NK_DEFAULT); if (len < buf_size) buf[len++] = '%'; } else if (*iter == 's') { /* string */ const char *str = va_arg(args, const char*); NK_ASSERT(str != buf && "buffer and argument are not allowed to overlap!"); NK_ASSERT(arg_type == NK_ARG_TYPE_DEFAULT); NK_ASSERT(precision == NK_DEFAULT); NK_ASSERT(width == NK_DEFAULT); if (str == buf) return -1; while (str && *str && len < buf_size) buf[len++] = *str++; } else if (*iter == 'n') { /* current length callback */ signed int *n = va_arg(args, int*); NK_ASSERT(arg_type == NK_ARG_TYPE_DEFAULT); NK_ASSERT(precision == NK_DEFAULT); NK_ASSERT(width == NK_DEFAULT); if (n) *n = len; } else if (*iter == 'c' || *iter == 'i' || *iter == 'd') { /* signed integer */ long value = 0; const char *num_iter; int num_len, num_print, padding; int cur_precision = NK_MAX(precision, 1); int cur_width = NK_MAX(width, 0); /* retrieve correct value type */ if (arg_type == NK_ARG_TYPE_CHAR) value = (signed char)va_arg(args, int); else if (arg_type == NK_ARG_TYPE_SHORT) value = (signed short)va_arg(args, int); else if (arg_type == NK_ARG_TYPE_LONG) value = va_arg(args, signed long); else if (*iter == 'c') value = (unsigned char)va_arg(args, int); else value = va_arg(args, signed int); /* convert number to string */ nk_itoa(number_buffer, value); num_len = nk_strlen(number_buffer); padding = NK_MAX(cur_width - NK_MAX(cur_precision, num_len), 0); if ((flag & NK_ARG_FLAG_PLUS) || (flag & NK_ARG_FLAG_SPACE)) padding = NK_MAX(padding-1, 0); /* fill left padding up to a total of `width` characters */ if (!(flag & NK_ARG_FLAG_LEFT)) { while (padding-- > 0 && (len < buf_size)) { if ((flag & NK_ARG_FLAG_ZERO) && (precision == NK_DEFAULT)) buf[len++] = '0'; else buf[len++] = ' '; } } /* copy string value representation into buffer */ if ((flag & NK_ARG_FLAG_PLUS) && value >= 0 && len < buf_size) buf[len++] = '+'; else if ((flag & NK_ARG_FLAG_SPACE) && value >= 0 && len < buf_size) buf[len++] = ' '; /* fill up to precision number of digits with '0' */ num_print = NK_MAX(cur_precision, num_len); while (precision && (num_print > num_len) && (len < buf_size)) { buf[len++] = '0'; num_print--; } /* copy string value representation into buffer */ num_iter = number_buffer; while (precision && *num_iter && len < buf_size) buf[len++] = *num_iter++; /* fill right padding up to width characters */ if (flag & NK_ARG_FLAG_LEFT) { while ((padding-- > 0) && (len < buf_size)) buf[len++] = ' '; } } else if (*iter == 'o' || *iter == 'x' || *iter == 'X' || *iter == 'u') { /* unsigned integer */ unsigned long value = 0; int num_len = 0, num_print, padding = 0; int cur_precision = NK_MAX(precision, 1); int cur_width = NK_MAX(width, 0); unsigned int base = (*iter == 'o') ? 8: (*iter == 'u')? 10: 16; /* print oct/hex/dec value */ const char *upper_output_format = "0123456789ABCDEF"; const char *lower_output_format = "0123456789abcdef"; const char *output_format = (*iter == 'x') ? lower_output_format: upper_output_format; /* retrieve correct value type */ if (arg_type == NK_ARG_TYPE_CHAR) value = (unsigned char)va_arg(args, int); else if (arg_type == NK_ARG_TYPE_SHORT) value = (unsigned short)va_arg(args, int); else if (arg_type == NK_ARG_TYPE_LONG) value = va_arg(args, unsigned long); else value = va_arg(args, unsigned int); do { /* convert decimal number into hex/oct number */ int digit = output_format[value % base]; if (num_len < NK_MAX_NUMBER_BUFFER) number_buffer[num_len++] = (char)digit; value /= base; } while (value > 0); num_print = NK_MAX(cur_precision, num_len); padding = NK_MAX(cur_width - NK_MAX(cur_precision, num_len), 0); if (flag & NK_ARG_FLAG_NUM) padding = NK_MAX(padding-1, 0); /* fill left padding up to a total of `width` characters */ if (!(flag & NK_ARG_FLAG_LEFT)) { while ((padding-- > 0) && (len < buf_size)) { if ((flag & NK_ARG_FLAG_ZERO) && (precision == NK_DEFAULT)) buf[len++] = '0'; else buf[len++] = ' '; } } /* fill up to precision number of digits */ if (num_print && (flag & NK_ARG_FLAG_NUM)) { if ((*iter == 'o') && (len < buf_size)) { buf[len++] = '0'; } else if ((*iter == 'x') && ((len+1) < buf_size)) { buf[len++] = '0'; buf[len++] = 'x'; } else if ((*iter == 'X') && ((len+1) < buf_size)) { buf[len++] = '0'; buf[len++] = 'X'; } } while (precision && (num_print > num_len) && (len < buf_size)) { buf[len++] = '0'; num_print--; } /* reverse number direction */ while (num_len > 0) { if (precision && (len < buf_size)) buf[len++] = number_buffer[num_len-1]; num_len--; } /* fill right padding up to width characters */ if (flag & NK_ARG_FLAG_LEFT) { while ((padding-- > 0) && (len < buf_size)) buf[len++] = ' '; } } else if (*iter == 'f') { /* floating point */ const char *num_iter; int cur_precision = (precision < 0) ? 6: precision; int prefix, cur_width = NK_MAX(width, 0); double value = va_arg(args, double); int num_len = 0, frac_len = 0, dot = 0; int padding = 0; NK_ASSERT(arg_type == NK_ARG_TYPE_DEFAULT); NK_DTOA(number_buffer, value); num_len = nk_strlen(number_buffer); /* calculate padding */ num_iter = number_buffer; while (*num_iter && *num_iter != '.') num_iter++; prefix = (*num_iter == '.')?(int)(num_iter - number_buffer)+1:0; padding = NK_MAX(cur_width - (prefix + NK_MIN(cur_precision, num_len - prefix)) , 0); if ((flag & NK_ARG_FLAG_PLUS) || (flag & NK_ARG_FLAG_SPACE)) padding = NK_MAX(padding-1, 0); /* fill left padding up to a total of `width` characters */ if (!(flag & NK_ARG_FLAG_LEFT)) { while (padding-- > 0 && (len < buf_size)) { if (flag & NK_ARG_FLAG_ZERO) buf[len++] = '0'; else buf[len++] = ' '; } } /* copy string value representation into buffer */ num_iter = number_buffer; if ((flag & NK_ARG_FLAG_PLUS) && (value >= 0) && (len < buf_size)) buf[len++] = '+'; else if ((flag & NK_ARG_FLAG_SPACE) && (value >= 0) && (len < buf_size)) buf[len++] = ' '; while (*num_iter) { if (dot) frac_len++; if (len < buf_size) buf[len++] = *num_iter; if (*num_iter == '.') dot = 1; if (frac_len >= cur_precision) break; num_iter++; } /* fill number up to precision */ while (frac_len < cur_precision) { if (!dot && len < buf_size) { buf[len++] = '.'; dot = 1; } if (len < buf_size) buf[len++] = '0'; frac_len++; } /* fill right padding up to width characters */ if (flag & NK_ARG_FLAG_LEFT) { while ((padding-- > 0) && (len < buf_size)) buf[len++] = ' '; } } else { /* Specifier not supported: g,G,e,E,p,z */ NK_ASSERT(0 && "specifier is not supported!"); return result; } } buf[(len >= buf_size)?(buf_size-1):len] = 0; result = (len >= buf_size)?-1:len; return result; } NK_INTERN int nk_strfmt(char *buf, int buf_size, const char *fmt, va_list args) { int result = -1; NK_ASSERT(buf); NK_ASSERT(buf_size); if (!buf || !buf_size || !fmt) return 0; #ifdef NK_INCLUDE_STANDARD_IO result = NK_VSNPRINTF(buf, (nk_size)buf_size, fmt, args); result = (result >= buf_size) ? -1: result; buf[buf_size-1] = 0; #else result = nk_vsnprintf(buf, buf_size, fmt, args); #endif return result; } #endif NK_API nk_hash nk_murmur_hash(const void * key, int len, nk_hash seed) { /* 32-Bit MurmurHash3: https://code.google.com/p/smhasher/wiki/MurmurHash3*/ #define NK_ROTL(x,r) ((x) << (r) | ((x) >> (32 - r))) union {const nk_uint *i; const nk_byte *b;} conv = {0}; const nk_byte *data = (const nk_byte*)key; const int nblocks = len/4; nk_uint h1 = seed; const nk_uint c1 = 0xcc9e2d51; const nk_uint c2 = 0x1b873593; const nk_byte *tail; const nk_uint *blocks; nk_uint k1; int i; /* body */ if (!key) return 0; conv.b = (data + nblocks*4); blocks = (const nk_uint*)conv.i; for (i = -nblocks; i; ++i) { k1 = blocks[i]; k1 *= c1; k1 = NK_ROTL(k1,15); k1 *= c2; h1 ^= k1; h1 = NK_ROTL(h1,13); h1 = h1*5+0xe6546b64; } /* tail */ tail = (const nk_byte*)(data + nblocks*4); k1 = 0; switch (len & 3) { case 3: k1 ^= (nk_uint)(tail[2] << 16); case 2: k1 ^= (nk_uint)(tail[1] << 8u); case 1: k1 ^= tail[0]; k1 *= c1; k1 = NK_ROTL(k1,15); k1 *= c2; h1 ^= k1; default: break; } /* finalization */ h1 ^= (nk_uint)len; /* fmix32 */ h1 ^= h1 >> 16; h1 *= 0x85ebca6b; h1 ^= h1 >> 13; h1 *= 0xc2b2ae35; h1 ^= h1 >> 16; #undef NK_ROTL return h1; } #ifdef NK_INCLUDE_STANDARD_IO NK_INTERN char* nk_file_load(const char* path, nk_size* siz, struct nk_allocator *alloc) { char *buf; FILE *fd; long ret; NK_ASSERT(path); NK_ASSERT(siz); NK_ASSERT(alloc); if (!path || !siz || !alloc) return 0; fd = fopen(path, "rb"); if (!fd) return 0; fseek(fd, 0, SEEK_END); ret = ftell(fd); if (ret < 0) { fclose(fd); return 0; } *siz = (nk_size)ret; fseek(fd, 0, SEEK_SET); buf = (char*)alloc->alloc(alloc->userdata,0, *siz); NK_ASSERT(buf); if (!buf) { fclose(fd); return 0; } *siz = (nk_size)fread(buf, *siz, 1, fd); fclose(fd); return buf; } #endif /* * ============================================================== * * COLOR * * =============================================================== */ NK_INTERN int nk_parse_hex(const char *p, int length) { int i = 0; int len = 0; while (len < length) { i <<= 4; if (p[len] >= 'a' && p[len] <= 'f') i += ((p[len] - 'a') + 10); else if (p[len] >= 'A' && p[len] <= 'F') i += ((p[len] - 'A') + 10); else i += (p[len] - '0'); len++; } return i; } NK_API struct nk_color nk_rgba(int r, int g, int b, int a) { struct nk_color ret; ret.r = (nk_byte)NK_CLAMP(0, r, 255); ret.g = (nk_byte)NK_CLAMP(0, g, 255); ret.b = (nk_byte)NK_CLAMP(0, b, 255); ret.a = (nk_byte)NK_CLAMP(0, a, 255); return ret; } NK_API struct nk_color nk_rgb_hex(const char *rgb) { struct nk_color col; const char *c = rgb; if (*c == '#') c++; col.r = (nk_byte)nk_parse_hex(c, 2); col.g = (nk_byte)nk_parse_hex(c+2, 2); col.b = (nk_byte)nk_parse_hex(c+4, 2); col.a = 255; return col; } NK_API struct nk_color nk_rgba_hex(const char *rgb) { struct nk_color col; const char *c = rgb; if (*c == '#') c++; col.r = (nk_byte)nk_parse_hex(c, 2); col.g = (nk_byte)nk_parse_hex(c+2, 2); col.b = (nk_byte)nk_parse_hex(c+4, 2); col.a = (nk_byte)nk_parse_hex(c+6, 2); return col; } NK_API void nk_color_hex_rgba(char *output, struct nk_color col) { #define NK_TO_HEX(i) ((i) <= 9 ? '0' + (i): 'A' - 10 + (i)) output[0] = (char)NK_TO_HEX((col.r & 0x0F)); output[1] = (char)NK_TO_HEX((col.r & 0xF0) >> 4); output[2] = (char)NK_TO_HEX((col.g & 0x0F)); output[3] = (char)NK_TO_HEX((col.g & 0xF0) >> 4); output[4] = (char)NK_TO_HEX((col.b & 0x0F)); output[5] = (char)NK_TO_HEX((col.b & 0xF0) >> 4); output[6] = (char)NK_TO_HEX((col.a & 0x0F)); output[7] = (char)NK_TO_HEX((col.a & 0xF0) >> 4); output[8] = '\0'; #undef NK_TO_HEX } NK_API void nk_color_hex_rgb(char *output, struct nk_color col) { #define NK_TO_HEX(i) ((i) <= 9 ? '0' + (i): 'A' - 10 + (i)) output[0] = (char)NK_TO_HEX((col.r & 0x0F)); output[1] = (char)NK_TO_HEX((col.r & 0xF0) >> 4); output[2] = (char)NK_TO_HEX((col.g & 0x0F)); output[3] = (char)NK_TO_HEX((col.g & 0xF0) >> 4); output[4] = (char)NK_TO_HEX((col.b & 0x0F)); output[5] = (char)NK_TO_HEX((col.b & 0xF0) >> 4); output[6] = '\0'; #undef NK_TO_HEX } NK_API struct nk_color nk_rgba_iv(const int *c) { return nk_rgba(c[0], c[1], c[2], c[3]); } NK_API struct nk_color nk_rgba_bv(const nk_byte *c) { return nk_rgba(c[0], c[1], c[2], c[3]); } NK_API struct nk_color nk_rgb(int r, int g, int b) { struct nk_color ret; ret.r = (nk_byte)NK_CLAMP(0, r, 255); ret.g = (nk_byte)NK_CLAMP(0, g, 255); ret.b = (nk_byte)NK_CLAMP(0, b, 255); ret.a = (nk_byte)255; return ret; } NK_API struct nk_color nk_rgb_iv(const int *c) { return nk_rgb(c[0], c[1], c[2]); } NK_API struct nk_color nk_rgb_bv(const nk_byte* c) { return nk_rgb(c[0], c[1], c[2]); } NK_API struct nk_color nk_rgba_u32(nk_uint in) { struct nk_color ret; ret.r = (in & 0xFF); ret.g = ((in >> 8) & 0xFF); ret.b = ((in >> 16) & 0xFF); ret.a = (nk_byte)((in >> 24) & 0xFF); return ret; } NK_API struct nk_color nk_rgba_f(float r, float g, float b, float a) { struct nk_color ret; ret.r = (nk_byte)(NK_SATURATE(r) * 255.0f); ret.g = (nk_byte)(NK_SATURATE(g) * 255.0f); ret.b = (nk_byte)(NK_SATURATE(b) * 255.0f); ret.a = (nk_byte)(NK_SATURATE(a) * 255.0f); return ret; } NK_API struct nk_color nk_rgba_fv(const float *c) { return nk_rgba_f(c[0], c[1], c[2], c[3]); } NK_API struct nk_color nk_rgb_f(float r, float g, float b) { struct nk_color ret; ret.r = (nk_byte)(NK_SATURATE(r) * 255.0f); ret.g = (nk_byte)(NK_SATURATE(g) * 255.0f); ret.b = (nk_byte)(NK_SATURATE(b) * 255.0f); ret.a = 255; return ret; } NK_API struct nk_color nk_rgb_fv(const float *c) { return nk_rgb_f(c[0], c[1], c[2]); } NK_API struct nk_color nk_hsv(int h, int s, int v) { return nk_hsva(h, s, v, 255); } NK_API struct nk_color nk_hsv_iv(const int *c) { return nk_hsv(c[0], c[1], c[2]); } NK_API struct nk_color nk_hsv_bv(const nk_byte *c) { return nk_hsv(c[0], c[1], c[2]); } NK_API struct nk_color nk_hsv_f(float h, float s, float v) { return nk_hsva_f(h, s, v, 1.0f); } NK_API struct nk_color nk_hsv_fv(const float *c) { return nk_hsv_f(c[0], c[1], c[2]); } NK_API struct nk_color nk_hsva(int h, int s, int v, int a) { float hf = ((float)NK_CLAMP(0, h, 255)) / 255.0f; float sf = ((float)NK_CLAMP(0, s, 255)) / 255.0f; float vf = ((float)NK_CLAMP(0, v, 255)) / 255.0f; float af = ((float)NK_CLAMP(0, a, 255)) / 255.0f; return nk_hsva_f(hf, sf, vf, af); } NK_API struct nk_color nk_hsva_iv(const int *c) { return nk_hsva(c[0], c[1], c[2], c[3]); } NK_API struct nk_color nk_hsva_bv(const nk_byte *c) { return nk_hsva(c[0], c[1], c[2], c[3]); } NK_API struct nk_color nk_hsva_f(float h, float s, float v, float a) { struct nk_colorf out = {0,0,0,0}; float p, q, t, f; int i; if (s <= 0.0f) { out.r = v; out.g = v; out.b = v; return nk_rgb_f(out.r, out.g, out.b); } h = h / (60.0f/360.0f); i = (int)h; f = h - (float)i; p = v * (1.0f - s); q = v * (1.0f - (s * f)); t = v * (1.0f - s * (1.0f - f)); switch (i) { case 0: out.r = v; out.g = t; out.b = p; break; case 1: out.r = q; out.g = v; out.b = p; break; case 2: out.r = p; out.g = v; out.b = t; break; case 4: out.r = t; out.g = p; out.b = v; break; case 5: default: out.r = v; out.g = p; out.b = q; break; } return nk_rgba_f(out.r, out.g, out.b, a); } NK_API struct nk_color nk_hsva_fv(const float *c) { return nk_hsva_f(c[0], c[1], c[2], c[3]); } NK_API nk_uint nk_color_u32(struct nk_color in) { nk_uint out = (nk_uint)in.r; out |= ((nk_uint)in.g << 8); out |= ((nk_uint)in.b << 16); out |= ((nk_uint)in.a << 24); return out; } NK_API void nk_color_f(float *r, float *g, float *b, float *a, struct nk_color in) { NK_STORAGE const float s = 1.0f/255.0f; *r = (float)in.r * s; *g = (float)in.g * s; *b = (float)in.b * s; *a = (float)in.a * s; } NK_API void nk_color_fv(float *c, struct nk_color in) { nk_color_f(&c[0], &c[1], &c[2], &c[3], in); } NK_API void nk_color_d(double *r, double *g, double *b, double *a, struct nk_color in) { NK_STORAGE const double s = 1.0/255.0; *r = (double)in.r * s; *g = (double)in.g * s; *b = (double)in.b * s; *a = (double)in.a * s; } NK_API void nk_color_dv(double *c, struct nk_color in) { nk_color_d(&c[0], &c[1], &c[2], &c[3], in); } NK_API void nk_color_hsv_f(float *out_h, float *out_s, float *out_v, struct nk_color in) { float a; nk_color_hsva_f(out_h, out_s, out_v, &a, in); } NK_API void nk_color_hsv_fv(float *out, struct nk_color in) { float a; nk_color_hsva_f(&out[0], &out[1], &out[2], &a, in); } NK_API void nk_color_hsva_f(float *out_h, float *out_s, float *out_v, float *out_a, struct nk_color in) { float chroma; float K = 0.0f; float r,g,b,a; nk_color_f(&r,&g,&b,&a, in); if (g < b) { const float t = g; g = b; b = t; K = -1.f; } if (r < g) { const float t = r; r = g; g = t; K = -2.f/6.0f - K; } chroma = r - ((g < b) ? g: b); *out_h = NK_ABS(K + (g - b)/(6.0f * chroma + 1e-20f)); *out_s = chroma / (r + 1e-20f); *out_v = r; *out_a = (float)in.a / 255.0f; } NK_API void nk_color_hsva_fv(float *out, struct nk_color in) { nk_color_hsva_f(&out[0], &out[1], &out[2], &out[3], in); } NK_API void nk_color_hsva_i(int *out_h, int *out_s, int *out_v, int *out_a, struct nk_color in) { float h,s,v,a; nk_color_hsva_f(&h, &s, &v, &a, in); *out_h = (nk_byte)(h * 255.0f); *out_s = (nk_byte)(s * 255.0f); *out_v = (nk_byte)(v * 255.0f); *out_a = (nk_byte)(a * 255.0f); } NK_API void nk_color_hsva_iv(int *out, struct nk_color in) { nk_color_hsva_i(&out[0], &out[1], &out[2], &out[3], in); } NK_API void nk_color_hsva_bv(nk_byte *out, struct nk_color in) { int tmp[4]; nk_color_hsva_i(&tmp[0], &tmp[1], &tmp[2], &tmp[3], in); out[0] = (nk_byte)tmp[0]; out[1] = (nk_byte)tmp[1]; out[2] = (nk_byte)tmp[2]; out[3] = (nk_byte)tmp[3]; } NK_API void nk_color_hsva_b(nk_byte *h, nk_byte *s, nk_byte *v, nk_byte *a, struct nk_color in) { int tmp[4]; nk_color_hsva_i(&tmp[0], &tmp[1], &tmp[2], &tmp[3], in); *h = (nk_byte)tmp[0]; *s = (nk_byte)tmp[1]; *v = (nk_byte)tmp[2]; *a = (nk_byte)tmp[3]; } NK_API void nk_color_hsv_i(int *out_h, int *out_s, int *out_v, struct nk_color in) { int a; nk_color_hsva_i(out_h, out_s, out_v, &a, in); } NK_API void nk_color_hsv_b(nk_byte *out_h, nk_byte *out_s, nk_byte *out_v, struct nk_color in) { int tmp[4]; nk_color_hsva_i(&tmp[0], &tmp[1], &tmp[2], &tmp[3], in); *out_h = (nk_byte)tmp[0]; *out_s = (nk_byte)tmp[1]; *out_v = (nk_byte)tmp[2]; } NK_API void nk_color_hsv_iv(int *out, struct nk_color in) { nk_color_hsv_i(&out[0], &out[1], &out[2], in); } NK_API void nk_color_hsv_bv(nk_byte *out, struct nk_color in) { int tmp[4]; nk_color_hsv_i(&tmp[0], &tmp[1], &tmp[2], in); out[0] = (nk_byte)tmp[0]; out[1] = (nk_byte)tmp[1]; out[2] = (nk_byte)tmp[2]; } /* * ============================================================== * * IMAGE * * =============================================================== */ NK_API nk_handle nk_handle_ptr(void *ptr) { nk_handle handle = {0}; handle.ptr = ptr; return handle; } NK_API nk_handle nk_handle_id(int id) { nk_handle handle; nk_zero_struct(handle); handle.id = id; return handle; } NK_API struct nk_image nk_subimage_ptr(void *ptr, unsigned short w, unsigned short h, struct nk_rect r) { struct nk_image s; nk_zero(&s, sizeof(s)); s.handle.ptr = ptr; s.w = w; s.h = h; s.region[0] = (unsigned short)r.x; s.region[1] = (unsigned short)r.y; s.region[2] = (unsigned short)r.w; s.region[3] = (unsigned short)r.h; return s; } NK_API struct nk_image nk_subimage_id(int id, unsigned short w, unsigned short h, struct nk_rect r) { struct nk_image s; nk_zero(&s, sizeof(s)); s.handle.id = id; s.w = w; s.h = h; s.region[0] = (unsigned short)r.x; s.region[1] = (unsigned short)r.y; s.region[2] = (unsigned short)r.w; s.region[3] = (unsigned short)r.h; return s; } NK_API struct nk_image nk_subimage_handle(nk_handle handle, unsigned short w, unsigned short h, struct nk_rect r) { struct nk_image s; nk_zero(&s, sizeof(s)); s.handle = handle; s.w = w; s.h = h; s.region[0] = (unsigned short)r.x; s.region[1] = (unsigned short)r.y; s.region[2] = (unsigned short)r.w; s.region[3] = (unsigned short)r.h; return s; } NK_API struct nk_image nk_image_handle(nk_handle handle) { struct nk_image s; nk_zero(&s, sizeof(s)); s.handle = handle; s.w = 0; s.h = 0; s.region[0] = 0; s.region[1] = 0; s.region[2] = 0; s.region[3] = 0; return s; } NK_API struct nk_image nk_image_ptr(void *ptr) { struct nk_image s; nk_zero(&s, sizeof(s)); NK_ASSERT(ptr); s.handle.ptr = ptr; s.w = 0; s.h = 0; s.region[0] = 0; s.region[1] = 0; s.region[2] = 0; s.region[3] = 0; return s; } NK_API struct nk_image nk_image_id(int id) { struct nk_image s; nk_zero(&s, sizeof(s)); s.handle.id = id; s.w = 0; s.h = 0; s.region[0] = 0; s.region[1] = 0; s.region[2] = 0; s.region[3] = 0; return s; } NK_API int nk_image_is_subimage(const struct nk_image* img) { NK_ASSERT(img); return !(img->w == 0 && img->h == 0); } NK_INTERN void nk_unify(struct nk_rect *clip, const struct nk_rect *a, float x0, float y0, float x1, float y1) { NK_ASSERT(a); NK_ASSERT(clip); clip->x = NK_MAX(a->x, x0); clip->y = NK_MAX(a->y, y0); clip->w = NK_MIN(a->x + a->w, x1) - clip->x; clip->h = NK_MIN(a->y + a->h, y1) - clip->y; clip->w = NK_MAX(0, clip->w); clip->h = NK_MAX(0, clip->h); } NK_API void nk_triangle_from_direction(struct nk_vec2 *result, struct nk_rect r, float pad_x, float pad_y, enum nk_heading direction) { float w_half, h_half; NK_ASSERT(result); r.w = NK_MAX(2 * pad_x, r.w); r.h = NK_MAX(2 * pad_y, r.h); r.w = r.w - 2 * pad_x; r.h = r.h - 2 * pad_y; r.x = r.x + pad_x; r.y = r.y + pad_y; w_half = r.w / 2.0f; h_half = r.h / 2.0f; if (direction == NK_UP) { result[0] = nk_vec2(r.x + w_half, r.y); result[1] = nk_vec2(r.x + r.w, r.y + r.h); result[2] = nk_vec2(r.x, r.y + r.h); } else if (direction == NK_RIGHT) { result[0] = nk_vec2(r.x, r.y); result[1] = nk_vec2(r.x + r.w, r.y + h_half); result[2] = nk_vec2(r.x, r.y + r.h); } else if (direction == NK_DOWN) { result[0] = nk_vec2(r.x, r.y); result[1] = nk_vec2(r.x + r.w, r.y); result[2] = nk_vec2(r.x + w_half, r.y + r.h); } else { result[0] = nk_vec2(r.x, r.y + h_half); result[1] = nk_vec2(r.x + r.w, r.y); result[2] = nk_vec2(r.x + r.w, r.y + r.h); } } NK_INTERN int nk_text_clamp(const struct nk_user_font *font, const char *text, int text_len, float space, int *glyphs, float *text_width) { int glyph_len = 0; float last_width = 0; nk_rune unicode = 0; float width = 0; int len = 0; int g = 0; glyph_len = nk_utf_decode(text, &unicode, text_len); while (glyph_len && (width < space) && (len < text_len)) { float s; len += glyph_len; s = font->width(font->userdata, font->height, text, len); last_width = width; width = s; glyph_len = nk_utf_decode(&text[len], &unicode, text_len - len); g++; } *glyphs = g; *text_width = last_width; return len; } enum {NK_DO_NOT_STOP_ON_NEW_LINE, NK_STOP_ON_NEW_LINE}; NK_INTERN struct nk_vec2 nk_text_calculate_text_bounds(const struct nk_user_font *font, const char *begin, int byte_len, float row_height, const char **remaining, struct nk_vec2 *out_offset, int *glyphs, int op) { float line_height = row_height; struct nk_vec2 text_size = nk_vec2(0,0); float line_width = 0.0f; float glyph_width; int glyph_len = 0; nk_rune unicode = 0; int text_len = 0; if (!begin || byte_len <= 0 || !font) return nk_vec2(0,row_height); glyph_len = nk_utf_decode(begin, &unicode, byte_len); if (!glyph_len) return text_size; glyph_width = font->width(font->userdata, font->height, begin, glyph_len); *glyphs = 0; while ((text_len < byte_len) && glyph_len) { if (unicode == '\n') { text_size.x = NK_MAX(text_size.x, line_width); text_size.y += line_height; line_width = 0; *glyphs+=1; if (op == NK_STOP_ON_NEW_LINE) break; text_len++; glyph_len = nk_utf_decode(begin + text_len, &unicode, byte_len-text_len); continue; } if (unicode == '\r') { text_len++; *glyphs+=1; glyph_len = nk_utf_decode(begin + text_len, &unicode, byte_len-text_len); continue; } *glyphs = *glyphs + 1; text_len += glyph_len; line_width += (float)glyph_width; glyph_width = font->width(font->userdata, font->height, begin+text_len, glyph_len); glyph_len = nk_utf_decode(begin + text_len, &unicode, byte_len-text_len); continue; } if (text_size.x < line_width) text_size.x = line_width; if (out_offset) *out_offset = nk_vec2(line_width, text_size.y + line_height); if (line_width > 0 || text_size.y == 0.0f) text_size.y += line_height; if (remaining) *remaining = begin+text_len; return text_size; } /* ============================================================== * * UTF-8 * * ===============================================================*/ NK_GLOBAL const nk_byte nk_utfbyte[NK_UTF_SIZE+1] = {0x80, 0, 0xC0, 0xE0, 0xF0}; NK_GLOBAL const nk_byte nk_utfmask[NK_UTF_SIZE+1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8}; NK_GLOBAL const nk_uint nk_utfmin[NK_UTF_SIZE+1] = {0, 0, 0x80, 0x800, 0x10000}; NK_GLOBAL const nk_uint nk_utfmax[NK_UTF_SIZE+1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF}; NK_INTERN int nk_utf_validate(nk_rune *u, int i) { NK_ASSERT(u); if (!u) return 0; if (!NK_BETWEEN(*u, nk_utfmin[i], nk_utfmax[i]) || NK_BETWEEN(*u, 0xD800, 0xDFFF)) *u = NK_UTF_INVALID; for (i = 1; *u > nk_utfmax[i]; ++i); return i; } NK_INTERN nk_rune nk_utf_decode_byte(char c, int *i) { NK_ASSERT(i); if (!i) return 0; for(*i = 0; *i < (int)NK_LEN(nk_utfmask); ++(*i)) { if (((nk_byte)c & nk_utfmask[*i]) == nk_utfbyte[*i]) return (nk_byte)(c & ~nk_utfmask[*i]); } return 0; } NK_API int nk_utf_decode(const char *c, nk_rune *u, int clen) { int i, j, len, type=0; nk_rune udecoded; NK_ASSERT(c); NK_ASSERT(u); if (!c || !u) return 0; if (!clen) return 0; *u = NK_UTF_INVALID; udecoded = nk_utf_decode_byte(c[0], &len); if (!NK_BETWEEN(len, 1, NK_UTF_SIZE)) return 1; for (i = 1, j = 1; i < clen && j < len; ++i, ++j) { udecoded = (udecoded << 6) | nk_utf_decode_byte(c[i], &type); if (type != 0) return j; } if (j < len) return 0; *u = udecoded; nk_utf_validate(u, len); return len; } NK_INTERN char nk_utf_encode_byte(nk_rune u, int i) { return (char)((nk_utfbyte[i]) | ((nk_byte)u & ~nk_utfmask[i])); } NK_API int nk_utf_encode(nk_rune u, char *c, int clen) { int len, i; len = nk_utf_validate(&u, 0); if (clen < len || !len || len > NK_UTF_SIZE) return 0; for (i = len - 1; i != 0; --i) { c[i] = nk_utf_encode_byte(u, 0); u >>= 6; } c[0] = nk_utf_encode_byte(u, len); return len; } NK_API int nk_utf_len(const char *str, int len) { const char *text; int glyphs = 0; int text_len; int glyph_len; int src_len = 0; nk_rune unicode; NK_ASSERT(str); if (!str || !len) return 0; text = str; text_len = len; glyph_len = nk_utf_decode(text, &unicode, text_len); while (glyph_len && src_len < len) { glyphs++; src_len = src_len + glyph_len; glyph_len = nk_utf_decode(text + src_len, &unicode, text_len - src_len); } return glyphs; } NK_API const char* nk_utf_at(const char *buffer, int length, int index, nk_rune *unicode, int *len) { int i = 0; int src_len = 0; int glyph_len = 0; const char *text; int text_len; NK_ASSERT(buffer); NK_ASSERT(unicode); NK_ASSERT(len); if (!buffer || !unicode || !len) return 0; if (index < 0) { *unicode = NK_UTF_INVALID; *len = 0; return 0; } text = buffer; text_len = length; glyph_len = nk_utf_decode(text, unicode, text_len); while (glyph_len) { if (i == index) { *len = glyph_len; break; } i++; src_len = src_len + glyph_len; glyph_len = nk_utf_decode(text + src_len, unicode, text_len - src_len); } if (i != index) return 0; return buffer + src_len; } /* ============================================================== * * BUFFER * * ===============================================================*/ #ifdef NK_INCLUDE_DEFAULT_ALLOCATOR NK_INTERN void* nk_malloc(nk_handle unused, void *old,nk_size size) {NK_UNUSED(unused); NK_UNUSED(old); return malloc(size);} NK_INTERN void nk_mfree(nk_handle unused, void *ptr) {NK_UNUSED(unused); free(ptr);} NK_API void nk_buffer_init_default(struct nk_buffer *buffer) { struct nk_allocator alloc; alloc.userdata.ptr = 0; alloc.alloc = nk_malloc; alloc.free = nk_mfree; nk_buffer_init(buffer, &alloc, NK_BUFFER_DEFAULT_INITIAL_SIZE); } #endif NK_API void nk_buffer_init(struct nk_buffer *b, const struct nk_allocator *a, nk_size initial_size) { NK_ASSERT(b); NK_ASSERT(a); NK_ASSERT(initial_size); if (!b || !a || !initial_size) return; nk_zero(b, sizeof(*b)); b->type = NK_BUFFER_DYNAMIC; b->memory.ptr = a->alloc(a->userdata,0, initial_size); b->memory.size = initial_size; b->size = initial_size; b->grow_factor = 2.0f; b->pool = *a; } NK_API void nk_buffer_init_fixed(struct nk_buffer *b, void *m, nk_size size) { NK_ASSERT(b); NK_ASSERT(m); NK_ASSERT(size); if (!b || !m || !size) return; nk_zero(b, sizeof(*b)); b->type = NK_BUFFER_FIXED; b->memory.ptr = m; b->memory.size = size; b->size = size; } NK_INTERN void* nk_buffer_align(void *unaligned, nk_size align, nk_size *alignment, enum nk_buffer_allocation_type type) { void *memory = 0; switch (type) { default: case NK_BUFFER_MAX: case NK_BUFFER_FRONT: if (align) { memory = NK_ALIGN_PTR(unaligned, align); *alignment = (nk_size)((nk_byte*)memory - (nk_byte*)unaligned); } else { memory = unaligned; *alignment = 0; } break; case NK_BUFFER_BACK: if (align) { memory = NK_ALIGN_PTR_BACK(unaligned, align); *alignment = (nk_size)((nk_byte*)unaligned - (nk_byte*)memory); } else { memory = unaligned; *alignment = 0; } break; } return memory; } NK_INTERN void* nk_buffer_realloc(struct nk_buffer *b, nk_size capacity, nk_size *size) { void *temp; nk_size buffer_size; NK_ASSERT(b); NK_ASSERT(size); if (!b || !size || !b->pool.alloc || !b->pool.free) return 0; buffer_size = b->memory.size; temp = b->pool.alloc(b->pool.userdata, b->memory.ptr, capacity); NK_ASSERT(temp); if (!temp) return 0; *size = capacity; if (temp != b->memory.ptr) { NK_MEMCPY(temp, b->memory.ptr, buffer_size); b->pool.free(b->pool.userdata, b->memory.ptr); } if (b->size == buffer_size) { /* no back buffer so just set correct size */ b->size = capacity; return temp; } else { /* copy back buffer to the end of the new buffer */ void *dst, *src; nk_size back_size; back_size = buffer_size - b->size; dst = nk_ptr_add(void, temp, capacity - back_size); src = nk_ptr_add(void, temp, b->size); NK_MEMCPY(dst, src, back_size); b->size = capacity - back_size; } return temp; } NK_INTERN void* nk_buffer_alloc(struct nk_buffer *b, enum nk_buffer_allocation_type type, nk_size size, nk_size align) { int full; nk_size alignment; void *unaligned; void *memory; NK_ASSERT(b); NK_ASSERT(size); if (!b || !size) return 0; b->needed += size; /* calculate total size with needed alignment + size */ if (type == NK_BUFFER_FRONT) unaligned = nk_ptr_add(void, b->memory.ptr, b->allocated); else unaligned = nk_ptr_add(void, b->memory.ptr, b->size - size); memory = nk_buffer_align(unaligned, align, &alignment, type); /* check if buffer has enough memory*/ if (type == NK_BUFFER_FRONT) full = ((b->allocated + size + alignment) > b->size); else full = ((b->size - (size + alignment)) <= b->allocated); if (full) { nk_size capacity; NK_ASSERT(b->type == NK_BUFFER_DYNAMIC); NK_ASSERT(b->pool.alloc && b->pool.free); if (b->type != NK_BUFFER_DYNAMIC || !b->pool.alloc || !b->pool.free) return 0; /* buffer is full so allocate bigger buffer if dynamic */ capacity = (nk_size)((float)b->memory.size * b->grow_factor); capacity = NK_MAX(capacity, nk_round_up_pow2((nk_uint)(b->allocated + size))); b->memory.ptr = nk_buffer_realloc(b, capacity, &b->memory.size); if (!b->memory.ptr) return 0; /* align newly allocated pointer */ if (type == NK_BUFFER_FRONT) unaligned = nk_ptr_add(void, b->memory.ptr, b->allocated); else unaligned = nk_ptr_add(void, b->memory.ptr, b->size - size); memory = nk_buffer_align(unaligned, align, &alignment, type); } if (type == NK_BUFFER_FRONT) b->allocated += size + alignment; else b->size -= (size + alignment); b->needed += alignment; b->calls++; return memory; } NK_API void nk_buffer_push(struct nk_buffer *b, enum nk_buffer_allocation_type type, const void *memory, nk_size size, nk_size align) { void *mem = nk_buffer_alloc(b, type, size, align); if (!mem) return; NK_MEMCPY(mem, memory, size); } NK_API void nk_buffer_mark(struct nk_buffer *buffer, enum nk_buffer_allocation_type type) { NK_ASSERT(buffer); if (!buffer) return; buffer->marker[type].active = nk_true; if (type == NK_BUFFER_BACK) buffer->marker[type].offset = buffer->size; else buffer->marker[type].offset = buffer->allocated; } NK_API void nk_buffer_reset(struct nk_buffer *buffer, enum nk_buffer_allocation_type type) { NK_ASSERT(buffer); if (!buffer) return; if (type == NK_BUFFER_BACK) { /* reset back buffer either back to marker or empty */ buffer->needed -= (buffer->memory.size - buffer->marker[type].offset); if (buffer->marker[type].active) buffer->size = buffer->marker[type].offset; else buffer->size = buffer->memory.size; buffer->marker[type].active = nk_false; } else { /* reset front buffer either back to back marker or empty */ buffer->needed -= (buffer->allocated - buffer->marker[type].offset); if (buffer->marker[type].active) buffer->allocated = buffer->marker[type].offset; else buffer->allocated = 0; buffer->marker[type].active = nk_false; } } NK_API void nk_buffer_clear(struct nk_buffer *b) { NK_ASSERT(b); if (!b) return; b->allocated = 0; b->size = b->memory.size; b->calls = 0; b->needed = 0; } NK_API void nk_buffer_free(struct nk_buffer *b) { NK_ASSERT(b); if (!b || !b->memory.ptr) return; if (b->type == NK_BUFFER_FIXED) return; if (!b->pool.free) return; NK_ASSERT(b->pool.free); b->pool.free(b->pool.userdata, b->memory.ptr); } NK_API void nk_buffer_info(struct nk_memory_status *s, struct nk_buffer *b) { NK_ASSERT(b); NK_ASSERT(s); if (!s || !b) return; s->allocated = b->allocated; s->size = b->memory.size; s->needed = b->needed; s->memory = b->memory.ptr; s->calls = b->calls; } NK_API void* nk_buffer_memory(struct nk_buffer *buffer) { NK_ASSERT(buffer); if (!buffer) return 0; return buffer->memory.ptr; } NK_API const void* nk_buffer_memory_const(const struct nk_buffer *buffer) { NK_ASSERT(buffer); if (!buffer) return 0; return buffer->memory.ptr; } NK_API nk_size nk_buffer_total(struct nk_buffer *buffer) { NK_ASSERT(buffer); if (!buffer) return 0; return buffer->memory.size; } /* * ============================================================== * * STRING * * =============================================================== */ #ifdef NK_INCLUDE_DEFAULT_ALLOCATOR NK_API void nk_str_init_default(struct nk_str *str) { struct nk_allocator alloc; alloc.userdata.ptr = 0; alloc.alloc = nk_malloc; alloc.free = nk_mfree; nk_buffer_init(&str->buffer, &alloc, 32); str->len = 0; } #endif NK_API void nk_str_init(struct nk_str *str, const struct nk_allocator *alloc, nk_size size) { nk_buffer_init(&str->buffer, alloc, size); str->len = 0; } NK_API void nk_str_init_fixed(struct nk_str *str, void *memory, nk_size size) { nk_buffer_init_fixed(&str->buffer, memory, size); str->len = 0; } NK_API int nk_str_append_text_char(struct nk_str *s, const char *str, int len) { char *mem; NK_ASSERT(s); NK_ASSERT(str); if (!s || !str || !len) return 0; mem = (char*)nk_buffer_alloc(&s->buffer, NK_BUFFER_FRONT, (nk_size)len * sizeof(char), 0); if (!mem) return 0; NK_MEMCPY(mem, str, (nk_size)len * sizeof(char)); s->len += nk_utf_len(str, len); return len; } NK_API int nk_str_append_str_char(struct nk_str *s, const char *str) { return nk_str_append_text_char(s, str, nk_strlen(str)); } NK_API int nk_str_append_text_utf8(struct nk_str *str, const char *text, int len) { int i = 0; int byte_len = 0; nk_rune unicode; if (!str || !text || !len) return 0; for (i = 0; i < len; ++i) byte_len += nk_utf_decode(text+byte_len, &unicode, 4); nk_str_append_text_char(str, text, byte_len); return len; } NK_API int nk_str_append_str_utf8(struct nk_str *str, const char *text) { int runes = 0; int byte_len = 0; int num_runes = 0; int glyph_len = 0; nk_rune unicode; if (!str || !text) return 0; glyph_len = byte_len = nk_utf_decode(text+byte_len, &unicode, 4); while (unicode != '\0' && glyph_len) { glyph_len = nk_utf_decode(text+byte_len, &unicode, 4); byte_len += glyph_len; num_runes++; } nk_str_append_text_char(str, text, byte_len); return runes; } NK_API int nk_str_append_text_runes(struct nk_str *str, const nk_rune *text, int len) { int i = 0; int byte_len = 0; nk_glyph glyph; NK_ASSERT(str); if (!str || !text || !len) return 0; for (i = 0; i < len; ++i) { byte_len = nk_utf_encode(text[i], glyph, NK_UTF_SIZE); if (!byte_len) break; nk_str_append_text_char(str, glyph, byte_len); } return len; } NK_API int nk_str_append_str_runes(struct nk_str *str, const nk_rune *runes) { int i = 0; nk_glyph glyph; int byte_len; NK_ASSERT(str); if (!str || !runes) return 0; while (runes[i] != '\0') { byte_len = nk_utf_encode(runes[i], glyph, NK_UTF_SIZE); nk_str_append_text_char(str, glyph, byte_len); i++; } return i; } NK_API int nk_str_insert_at_char(struct nk_str *s, int pos, const char *str, int len) { int i; void *mem; char *src; char *dst; int copylen; NK_ASSERT(s); NK_ASSERT(str); NK_ASSERT(len >= 0); if (!s || !str || !len || (nk_size)pos > s->buffer.allocated) return 0; if ((s->buffer.allocated + (nk_size)len >= s->buffer.memory.size) && (s->buffer.type == NK_BUFFER_FIXED)) return 0; copylen = (int)s->buffer.allocated - pos; if (!copylen) { nk_str_append_text_char(s, str, len); return 1; } mem = nk_buffer_alloc(&s->buffer, NK_BUFFER_FRONT, (nk_size)len * sizeof(char), 0); if (!mem) return 0; /* memmove */ NK_ASSERT(((int)pos + (int)len + ((int)copylen - 1)) >= 0); NK_ASSERT(((int)pos + ((int)copylen - 1)) >= 0); dst = nk_ptr_add(char, s->buffer.memory.ptr, pos + len + (copylen - 1)); src = nk_ptr_add(char, s->buffer.memory.ptr, pos + (copylen-1)); for (i = 0; i < copylen; ++i) *dst-- = *src--; mem = nk_ptr_add(void, s->buffer.memory.ptr, pos); NK_MEMCPY(mem, str, (nk_size)len * sizeof(char)); s->len = nk_utf_len((char *)s->buffer.memory.ptr, (int)s->buffer.allocated); return 1; } NK_API int nk_str_insert_at_rune(struct nk_str *str, int pos, const char *cstr, int len) { int glyph_len; nk_rune unicode; const char *begin; const char *buffer; NK_ASSERT(str); NK_ASSERT(cstr); NK_ASSERT(len); if (!str || !cstr || !len) return 0; begin = nk_str_at_rune(str, pos, &unicode, &glyph_len); buffer = nk_str_get_const(str); if (!begin) return 0; return nk_str_insert_text_char(str, (int)(begin - buffer), cstr, len); } NK_API int nk_str_insert_text_char(struct nk_str *str, int pos, const char *text, int len) {return nk_str_insert_at_char(str, pos, text, len);} NK_API int nk_str_insert_str_char(struct nk_str *str, int pos, const char *text) {return nk_str_insert_at_char(str, pos, text, nk_strlen(text));} NK_API int nk_str_insert_text_utf8(struct nk_str *str, int pos, const char *text, int len) { int i = 0; int byte_len = 0; nk_rune unicode; NK_ASSERT(str); NK_ASSERT(text); if (!str || !text || !len) return 0; for (i = 0; i < len; ++i) byte_len += nk_utf_decode(text+byte_len, &unicode, 4); nk_str_insert_at_rune(str, pos, text, byte_len); return len; } NK_API int nk_str_insert_str_utf8(struct nk_str *str, int pos, const char *text) { int runes = 0; int byte_len = 0; int num_runes = 0; int glyph_len = 0; nk_rune unicode; if (!str || !text) return 0; glyph_len = byte_len = nk_utf_decode(text+byte_len, &unicode, 4); while (unicode != '\0' && glyph_len) { glyph_len = nk_utf_decode(text+byte_len, &unicode, 4); byte_len += glyph_len; num_runes++; } nk_str_insert_at_rune(str, pos, text, byte_len); return runes; } NK_API int nk_str_insert_text_runes(struct nk_str *str, int pos, const nk_rune *runes, int len) { int i = 0; int byte_len = 0; nk_glyph glyph; NK_ASSERT(str); if (!str || !runes || !len) return 0; for (i = 0; i < len; ++i) { byte_len = nk_utf_encode(runes[i], glyph, NK_UTF_SIZE); if (!byte_len) break; nk_str_insert_at_rune(str, pos+i, glyph, byte_len); } return len; } NK_API int nk_str_insert_str_runes(struct nk_str *str, int pos, const nk_rune *runes) { int i = 0; nk_glyph glyph; int byte_len; NK_ASSERT(str); if (!str || !runes) return 0; while (runes[i] != '\0') { byte_len = nk_utf_encode(runes[i], glyph, NK_UTF_SIZE); nk_str_insert_at_rune(str, pos+i, glyph, byte_len); i++; } return i; } NK_API void nk_str_remove_chars(struct nk_str *s, int len) { NK_ASSERT(s); NK_ASSERT(len >= 0); if (!s || len < 0 || (nk_size)len > s->buffer.allocated) return; NK_ASSERT(((int)s->buffer.allocated - (int)len) >= 0); s->buffer.allocated -= (nk_size)len; s->len = nk_utf_len((char *)s->buffer.memory.ptr, (int)s->buffer.allocated); } NK_API void nk_str_remove_runes(struct nk_str *str, int len) { int index; const char *begin; const char *end; nk_rune unicode; NK_ASSERT(str); NK_ASSERT(len >= 0); if (!str || len < 0) return; if (len >= str->len) { str->len = 0; return; } index = str->len - len; begin = nk_str_at_rune(str, index, &unicode, &len); end = (const char*)str->buffer.memory.ptr + str->buffer.allocated; nk_str_remove_chars(str, (int)(end-begin)+1); } NK_API void nk_str_delete_chars(struct nk_str *s, int pos, int len) { NK_ASSERT(s); if (!s || !len || (nk_size)pos > s->buffer.allocated || (nk_size)(pos + len) > s->buffer.allocated) return; if ((nk_size)(pos + len) < s->buffer.allocated) { /* memmove */ char *dst = nk_ptr_add(char, s->buffer.memory.ptr, pos); char *src = nk_ptr_add(char, s->buffer.memory.ptr, pos + len); NK_MEMCPY(dst, src, s->buffer.allocated - (nk_size)(pos + len)); NK_ASSERT(((int)s->buffer.allocated - (int)len) >= 0); s->buffer.allocated -= (nk_size)len; } else nk_str_remove_chars(s, len); s->len = nk_utf_len((char *)s->buffer.memory.ptr, (int)s->buffer.allocated); } NK_API void nk_str_delete_runes(struct nk_str *s, int pos, int len) { char *temp; nk_rune unicode; char *begin; char *end; int unused; NK_ASSERT(s); NK_ASSERT(s->len >= pos + len); if (s->len < pos + len) len = NK_CLAMP(0, (s->len - pos), s->len); if (!len) return; temp = (char *)s->buffer.memory.ptr; begin = nk_str_at_rune(s, pos, &unicode, &unused); if (!begin) return; s->buffer.memory.ptr = begin; end = nk_str_at_rune(s, len, &unicode, &unused); s->buffer.memory.ptr = temp; if (!end) return; nk_str_delete_chars(s, (int)(begin - temp), (int)(end - begin)); } NK_API char* nk_str_at_char(struct nk_str *s, int pos) { NK_ASSERT(s); if (!s || pos > (int)s->buffer.allocated) return 0; return nk_ptr_add(char, s->buffer.memory.ptr, pos); } NK_API char* nk_str_at_rune(struct nk_str *str, int pos, nk_rune *unicode, int *len) { int i = 0; int src_len = 0; int glyph_len = 0; char *text; int text_len; NK_ASSERT(str); NK_ASSERT(unicode); NK_ASSERT(len); if (!str || !unicode || !len) return 0; if (pos < 0) { *unicode = 0; *len = 0; return 0; } text = (char*)str->buffer.memory.ptr; text_len = (int)str->buffer.allocated; glyph_len = nk_utf_decode(text, unicode, text_len); while (glyph_len) { if (i == pos) { *len = glyph_len; break; } i+= glyph_len; src_len = src_len + glyph_len; glyph_len = nk_utf_decode(text + src_len, unicode, text_len - src_len); } if (i != pos) return 0; return text + src_len; } NK_API const char* nk_str_at_char_const(const struct nk_str *s, int pos) { NK_ASSERT(s); if (!s || pos > (int)s->buffer.allocated) return 0; return nk_ptr_add(char, s->buffer.memory.ptr, pos); } NK_API const char* nk_str_at_const(const struct nk_str *str, int pos, nk_rune *unicode, int *len) { int i = 0; int src_len = 0; int glyph_len = 0; char *text; int text_len; NK_ASSERT(str); NK_ASSERT(unicode); NK_ASSERT(len); if (!str || !unicode || !len) return 0; if (pos < 0) { *unicode = 0; *len = 0; return 0; } text = (char*)str->buffer.memory.ptr; text_len = (int)str->buffer.allocated; glyph_len = nk_utf_decode(text, unicode, text_len); while (glyph_len) { if (i == pos) { *len = glyph_len; break; } i++; src_len = src_len + glyph_len; glyph_len = nk_utf_decode(text + src_len, unicode, text_len - src_len); } if (i != pos) return 0; return text + src_len; } NK_API nk_rune nk_str_rune_at(const struct nk_str *str, int pos) { int len; nk_rune unicode = 0; nk_str_at_const(str, pos, &unicode, &len); return unicode; } NK_API char* nk_str_get(struct nk_str *s) { NK_ASSERT(s); if (!s || !s->len || !s->buffer.allocated) return 0; return (char*)s->buffer.memory.ptr; } NK_API const char* nk_str_get_const(const struct nk_str *s) { NK_ASSERT(s); if (!s || !s->len || !s->buffer.allocated) return 0; return (const char*)s->buffer.memory.ptr; } NK_API int nk_str_len(struct nk_str *s) { NK_ASSERT(s); if (!s || !s->len || !s->buffer.allocated) return 0; return s->len; } NK_API int nk_str_len_char(struct nk_str *s) { NK_ASSERT(s); if (!s || !s->len || !s->buffer.allocated) return 0; return (int)s->buffer.allocated; } NK_API void nk_str_clear(struct nk_str *str) { NK_ASSERT(str); nk_buffer_clear(&str->buffer); str->len = 0; } NK_API void nk_str_free(struct nk_str *str) { NK_ASSERT(str); nk_buffer_free(&str->buffer); str->len = 0; } /* * ============================================================== * * Command buffer * * =============================================================== */ NK_INTERN void nk_command_buffer_init(struct nk_command_buffer *cmdbuf, struct nk_buffer *buffer, enum nk_command_clipping clip) { NK_ASSERT(cmdbuf); NK_ASSERT(buffer); if (!cmdbuf || !buffer) return; cmdbuf->base = buffer; cmdbuf->use_clipping = clip; cmdbuf->begin = buffer->allocated; cmdbuf->end = buffer->allocated; cmdbuf->last = buffer->allocated; } NK_INTERN void nk_command_buffer_reset(struct nk_command_buffer *buffer) { NK_ASSERT(buffer); if (!buffer) return; buffer->begin = 0; buffer->end = 0; buffer->last = 0; buffer->clip = nk_null_rect; #ifdef NK_INCLUDE_COMMAND_USERDATA buffer->userdata.ptr = 0; #endif } NK_INTERN void* nk_command_buffer_push(struct nk_command_buffer* b, enum nk_command_type t, nk_size size) { NK_STORAGE const nk_size align = NK_ALIGNOF(struct nk_command); struct nk_command *cmd; nk_size alignment; void *unaligned; void *memory; NK_ASSERT(b); NK_ASSERT(b->base); if (!b) return 0; cmd = (struct nk_command*)nk_buffer_alloc(b->base,NK_BUFFER_FRONT,size,align); if (!cmd) return 0; /* make sure the offset to the next command is aligned */ b->last = (nk_size)((nk_byte*)cmd - (nk_byte*)b->base->memory.ptr); unaligned = (nk_byte*)cmd + size; memory = NK_ALIGN_PTR(unaligned, align); alignment = (nk_size)((nk_byte*)memory - (nk_byte*)unaligned); cmd->type = t; cmd->next = b->base->allocated + alignment; #ifdef NK_INCLUDE_COMMAND_USERDATA cmd->userdata = b->userdata; #endif b->end = cmd->next; return cmd; } NK_API void nk_push_scissor(struct nk_command_buffer *b, struct nk_rect r) { struct nk_command_scissor *cmd; NK_ASSERT(b); if (!b) return; b->clip.x = r.x; b->clip.y = r.y; b->clip.w = r.w; b->clip.h = r.h; cmd = (struct nk_command_scissor*) nk_command_buffer_push(b, NK_COMMAND_SCISSOR, sizeof(*cmd)); if (!cmd) return; cmd->x = (short)r.x; cmd->y = (short)r.y; cmd->w = (unsigned short)NK_MAX(0, r.w); cmd->h = (unsigned short)NK_MAX(0, r.h); } NK_API void nk_stroke_line(struct nk_command_buffer *b, float x0, float y0, float x1, float y1, float line_thickness, struct nk_color c) { struct nk_command_line *cmd; NK_ASSERT(b); if (!b) return; cmd = (struct nk_command_line*) nk_command_buffer_push(b, NK_COMMAND_LINE, sizeof(*cmd)); if (!cmd) return; cmd->line_thickness = (unsigned short)line_thickness; cmd->begin.x = (short)x0; cmd->begin.y = (short)y0; cmd->end.x = (short)x1; cmd->end.y = (short)y1; cmd->color = c; } NK_API void nk_stroke_curve(struct nk_command_buffer *b, float ax, float ay, float ctrl0x, float ctrl0y, float ctrl1x, float ctrl1y, float bx, float by, float line_thickness, struct nk_color col) { struct nk_command_curve *cmd; NK_ASSERT(b); if (!b || col.a == 0) return; cmd = (struct nk_command_curve*) nk_command_buffer_push(b, NK_COMMAND_CURVE, sizeof(*cmd)); if (!cmd) return; cmd->line_thickness = (unsigned short)line_thickness; cmd->begin.x = (short)ax; cmd->begin.y = (short)ay; cmd->ctrl[0].x = (short)ctrl0x; cmd->ctrl[0].y = (short)ctrl0y; cmd->ctrl[1].x = (short)ctrl1x; cmd->ctrl[1].y = (short)ctrl1y; cmd->end.x = (short)bx; cmd->end.y = (short)by; cmd->color = col; } NK_API void nk_stroke_rect(struct nk_command_buffer *b, struct nk_rect rect, float rounding, float line_thickness, struct nk_color c) { struct nk_command_rect *cmd; NK_ASSERT(b); if (!b || c.a == 0 || rect.w == 0 || rect.h == 0) return; if (b->use_clipping) { const struct nk_rect *clip = &b->clip; if (!NK_INTERSECT(rect.x, rect.y, rect.w, rect.h, clip->x, clip->y, clip->w, clip->h)) return; } cmd = (struct nk_command_rect*) nk_command_buffer_push(b, NK_COMMAND_RECT, sizeof(*cmd)); if (!cmd) return; cmd->rounding = (unsigned short)rounding; cmd->line_thickness = (unsigned short)line_thickness; cmd->x = (short)rect.x; cmd->y = (short)rect.y; cmd->w = (unsigned short)NK_MAX(0, rect.w); cmd->h = (unsigned short)NK_MAX(0, rect.h); cmd->color = c; } NK_API void nk_fill_rect(struct nk_command_buffer *b, struct nk_rect rect, float rounding, struct nk_color c) { struct nk_command_rect_filled *cmd; NK_ASSERT(b); if (!b || c.a == 0 || rect.w == 0 || rect.h == 0) return; if (b->use_clipping) { const struct nk_rect *clip = &b->clip; if (!NK_INTERSECT(rect.x, rect.y, rect.w, rect.h, clip->x, clip->y, clip->w, clip->h)) return; } cmd = (struct nk_command_rect_filled*) nk_command_buffer_push(b, NK_COMMAND_RECT_FILLED, sizeof(*cmd)); if (!cmd) return; cmd->rounding = (unsigned short)rounding; cmd->x = (short)rect.x; cmd->y = (short)rect.y; cmd->w = (unsigned short)NK_MAX(0, rect.w); cmd->h = (unsigned short)NK_MAX(0, rect.h); cmd->color = c; } NK_API void nk_fill_rect_multi_color(struct nk_command_buffer *b, struct nk_rect rect, struct nk_color left, struct nk_color top, struct nk_color right, struct nk_color bottom) { struct nk_command_rect_multi_color *cmd; NK_ASSERT(b); if (!b || rect.w == 0 || rect.h == 0) return; if (b->use_clipping) { const struct nk_rect *clip = &b->clip; if (!NK_INTERSECT(rect.x, rect.y, rect.w, rect.h, clip->x, clip->y, clip->w, clip->h)) return; } cmd = (struct nk_command_rect_multi_color*) nk_command_buffer_push(b, NK_COMMAND_RECT_MULTI_COLOR, sizeof(*cmd)); if (!cmd) return; cmd->x = (short)rect.x; cmd->y = (short)rect.y; cmd->w = (unsigned short)NK_MAX(0, rect.w); cmd->h = (unsigned short)NK_MAX(0, rect.h); cmd->left = left; cmd->top = top; cmd->right = right; cmd->bottom = bottom; } NK_API void nk_stroke_circle(struct nk_command_buffer *b, struct nk_rect r, float line_thickness, struct nk_color c) { struct nk_command_circle *cmd; if (!b || r.w == 0 || r.h == 0) return; if (b->use_clipping) { const struct nk_rect *clip = &b->clip; if (!NK_INTERSECT(r.x, r.y, r.w, r.h, clip->x, clip->y, clip->w, clip->h)) return; } cmd = (struct nk_command_circle*) nk_command_buffer_push(b, NK_COMMAND_CIRCLE, sizeof(*cmd)); if (!cmd) return; cmd->line_thickness = (unsigned short)line_thickness; cmd->x = (short)r.x; cmd->y = (short)r.y; cmd->w = (unsigned short)NK_MAX(r.w, 0); cmd->h = (unsigned short)NK_MAX(r.h, 0); cmd->color = c; } NK_API void nk_fill_circle(struct nk_command_buffer *b, struct nk_rect r, struct nk_color c) { struct nk_command_circle_filled *cmd; NK_ASSERT(b); if (!b || c.a == 0 || r.w == 0 || r.h == 0) return; if (b->use_clipping) { const struct nk_rect *clip = &b->clip; if (!NK_INTERSECT(r.x, r.y, r.w, r.h, clip->x, clip->y, clip->w, clip->h)) return; } cmd = (struct nk_command_circle_filled*) nk_command_buffer_push(b, NK_COMMAND_CIRCLE_FILLED, sizeof(*cmd)); if (!cmd) return; cmd->x = (short)r.x; cmd->y = (short)r.y; cmd->w = (unsigned short)NK_MAX(r.w, 0); cmd->h = (unsigned short)NK_MAX(r.h, 0); cmd->color = c; } NK_API void nk_stroke_arc(struct nk_command_buffer *b, float cx, float cy, float radius, float a_min, float a_max, float line_thickness, struct nk_color c) { struct nk_command_arc *cmd; if (!b || c.a == 0) return; cmd = (struct nk_command_arc*) nk_command_buffer_push(b, NK_COMMAND_ARC, sizeof(*cmd)); if (!cmd) return; cmd->line_thickness = (unsigned short)line_thickness; cmd->cx = (short)cx; cmd->cy = (short)cy; cmd->r = (unsigned short)radius; cmd->a[0] = a_min; cmd->a[1] = a_max; cmd->color = c; } NK_API void nk_fill_arc(struct nk_command_buffer *b, float cx, float cy, float radius, float a_min, float a_max, struct nk_color c) { struct nk_command_arc_filled *cmd; NK_ASSERT(b); if (!b || c.a == 0) return; cmd = (struct nk_command_arc_filled*) nk_command_buffer_push(b, NK_COMMAND_ARC_FILLED, sizeof(*cmd)); if (!cmd) return; cmd->cx = (short)cx; cmd->cy = (short)cy; cmd->r = (unsigned short)radius; cmd->a[0] = a_min; cmd->a[1] = a_max; cmd->color = c; } NK_API void nk_stroke_triangle(struct nk_command_buffer *b, float x0, float y0, float x1, float y1, float x2, float y2, float line_thickness, struct nk_color c) { struct nk_command_triangle *cmd; NK_ASSERT(b); if (!b || c.a == 0) return; if (b->use_clipping) { const struct nk_rect *clip = &b->clip; if (!NK_INBOX(x0, y0, clip->x, clip->y, clip->w, clip->h) && !NK_INBOX(x1, y1, clip->x, clip->y, clip->w, clip->h) && !NK_INBOX(x2, y2, clip->x, clip->y, clip->w, clip->h)) return; } cmd = (struct nk_command_triangle*) nk_command_buffer_push(b, NK_COMMAND_TRIANGLE, sizeof(*cmd)); if (!cmd) return; cmd->line_thickness = (unsigned short)line_thickness; cmd->a.x = (short)x0; cmd->a.y = (short)y0; cmd->b.x = (short)x1; cmd->b.y = (short)y1; cmd->c.x = (short)x2; cmd->c.y = (short)y2; cmd->color = c; } NK_API void nk_fill_triangle(struct nk_command_buffer *b, float x0, float y0, float x1, float y1, float x2, float y2, struct nk_color c) { struct nk_command_triangle_filled *cmd; NK_ASSERT(b); if (!b || c.a == 0) return; if (!b) return; if (b->use_clipping) { const struct nk_rect *clip = &b->clip; if (!NK_INBOX(x0, y0, clip->x, clip->y, clip->w, clip->h) && !NK_INBOX(x1, y1, clip->x, clip->y, clip->w, clip->h) && !NK_INBOX(x2, y2, clip->x, clip->y, clip->w, clip->h)) return; } cmd = (struct nk_command_triangle_filled*) nk_command_buffer_push(b, NK_COMMAND_TRIANGLE_FILLED, sizeof(*cmd)); if (!cmd) return; cmd->a.x = (short)x0; cmd->a.y = (short)y0; cmd->b.x = (short)x1; cmd->b.y = (short)y1; cmd->c.x = (short)x2; cmd->c.y = (short)y2; cmd->color = c; } NK_API void nk_stroke_polygon(struct nk_command_buffer *b, float *points, int point_count, float line_thickness, struct nk_color col) { int i; nk_size size = 0; struct nk_command_polygon *cmd; NK_ASSERT(b); if (!b || col.a == 0) return; size = sizeof(*cmd) + sizeof(short) * 2 * (nk_size)point_count; cmd = (struct nk_command_polygon*) nk_command_buffer_push(b, NK_COMMAND_POLYGON, size); if (!cmd) return; cmd->color = col; cmd->line_thickness = (unsigned short)line_thickness; cmd->point_count = (unsigned short)point_count; for (i = 0; i < point_count; ++i) { cmd->points[i].x = (short)points[i*2]; cmd->points[i].y = (short)points[i*2+1]; } } NK_API void nk_fill_polygon(struct nk_command_buffer *b, float *points, int point_count, struct nk_color col) { int i; nk_size size = 0; struct nk_command_polygon_filled *cmd; NK_ASSERT(b); if (!b || col.a == 0) return; size = sizeof(*cmd) + sizeof(short) * 2 * (nk_size)point_count; cmd = (struct nk_command_polygon_filled*) nk_command_buffer_push(b, NK_COMMAND_POLYGON_FILLED, size); if (!cmd) return; cmd->color = col; cmd->point_count = (unsigned short)point_count; for (i = 0; i < point_count; ++i) { cmd->points[i].x = (short)points[i*2+0]; cmd->points[i].y = (short)points[i*2+1]; } } NK_API void nk_stroke_polyline(struct nk_command_buffer *b, float *points, int point_count, float line_thickness, struct nk_color col) { int i; nk_size size = 0; struct nk_command_polyline *cmd; NK_ASSERT(b); if (!b || col.a == 0) return; size = sizeof(*cmd) + sizeof(short) * 2 * (nk_size)point_count; cmd = (struct nk_command_polyline*) nk_command_buffer_push(b, NK_COMMAND_POLYLINE, size); if (!cmd) return; cmd->color = col; cmd->point_count = (unsigned short)point_count; cmd->line_thickness = (unsigned short)line_thickness; for (i = 0; i < point_count; ++i) { cmd->points[i].x = (short)points[i*2]; cmd->points[i].y = (short)points[i*2+1]; } } NK_API void nk_draw_image(struct nk_command_buffer *b, struct nk_rect r, const struct nk_image *img, struct nk_color col) { struct nk_command_image *cmd; NK_ASSERT(b); if (!b) return; if (b->use_clipping) { const struct nk_rect *c = &b->clip; if (c->w == 0 || c->h == 0 || !NK_INTERSECT(r.x, r.y, r.w, r.h, c->x, c->y, c->w, c->h)) return; } cmd = (struct nk_command_image*) nk_command_buffer_push(b, NK_COMMAND_IMAGE, sizeof(*cmd)); if (!cmd) return; cmd->x = (short)r.x; cmd->y = (short)r.y; cmd->w = (unsigned short)NK_MAX(0, r.w); cmd->h = (unsigned short)NK_MAX(0, r.h); cmd->img = *img; cmd->col = col; } NK_API void nk_draw_text(struct nk_command_buffer *b, struct nk_rect r, const char *string, int length, const struct nk_user_font *font, struct nk_color bg, struct nk_color fg) { float text_width = 0; struct nk_command_text *cmd; NK_ASSERT(b); NK_ASSERT(font); if (!b || !string || !length || (bg.a == 0 && fg.a == 0)) return; if (b->use_clipping) { const struct nk_rect *c = &b->clip; if (c->w == 0 || c->h == 0 || !NK_INTERSECT(r.x, r.y, r.w, r.h, c->x, c->y, c->w, c->h)) return; } /* make sure text fits inside bounds */ text_width = font->width(font->userdata, font->height, string, length); if (text_width > r.w){ int glyphs = 0; float txt_width = (float)text_width; length = nk_text_clamp(font, string, length, r.w, &glyphs, &txt_width); } if (!length) return; cmd = (struct nk_command_text*) nk_command_buffer_push(b, NK_COMMAND_TEXT, sizeof(*cmd) + (nk_size)(length + 1)); if (!cmd) return; cmd->x = (short)r.x; cmd->y = (short)r.y; cmd->w = (unsigned short)r.w; cmd->h = (unsigned short)r.h; cmd->background = bg; cmd->foreground = fg; cmd->font = font; cmd->length = length; cmd->height = font->height; NK_MEMCPY(cmd->string, string, (nk_size)length); cmd->string[length] = '\0'; } /* ============================================================== * * DRAW LIST * * ===============================================================*/ #ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT NK_API void nk_draw_list_init(struct nk_draw_list *list) { nk_size i = 0; nk_zero(list, sizeof(*list)); for (i = 0; i < NK_LEN(list->circle_vtx); ++i) { const float a = ((float)i / (float)NK_LEN(list->circle_vtx)) * 2 * NK_PI; list->circle_vtx[i].x = (float)NK_COS(a); list->circle_vtx[i].y = (float)NK_SIN(a); } } NK_API void nk_draw_list_setup(struct nk_draw_list *canvas, const struct nk_convert_config *config, struct nk_buffer *cmds, struct nk_buffer *vertices, struct nk_buffer *elements) { canvas->buffer = cmds; canvas->config = *config; canvas->elements = elements; canvas->vertices = vertices; canvas->clip_rect = nk_null_rect; } NK_API const struct nk_draw_command* nk__draw_list_begin(const struct nk_draw_list *canvas, const struct nk_buffer *buffer) { nk_byte *memory; nk_size offset; const struct nk_draw_command *cmd; NK_ASSERT(buffer); if (!buffer || !buffer->size || !canvas->cmd_count) return 0; memory = (nk_byte*)buffer->memory.ptr; offset = buffer->memory.size - canvas->cmd_offset; cmd = nk_ptr_add(const struct nk_draw_command, memory, offset); return cmd; } NK_API const struct nk_draw_command* nk__draw_list_end(const struct nk_draw_list *canvas, const struct nk_buffer *buffer) { nk_size size; nk_size offset; nk_byte *memory; const struct nk_draw_command *end; NK_ASSERT(buffer); NK_ASSERT(canvas); if (!buffer || !canvas) return 0; memory = (nk_byte*)buffer->memory.ptr; size = buffer->memory.size; offset = size - canvas->cmd_offset; end = nk_ptr_add(const struct nk_draw_command, memory, offset); end -= (canvas->cmd_count-1); return end; } NK_API const struct nk_draw_command* nk__draw_list_next(const struct nk_draw_command *cmd, const struct nk_buffer *buffer, const struct nk_draw_list *canvas) { const struct nk_draw_command *end; NK_ASSERT(buffer); NK_ASSERT(canvas); if (!cmd || !buffer || !canvas) return 0; end = nk__draw_list_end(canvas, buffer); if (cmd <= end) return 0; return (cmd-1); } NK_API void nk_draw_list_clear(struct nk_draw_list *list) { NK_ASSERT(list); if (!list) return; if (list->buffer) nk_buffer_clear(list->buffer); if (list->vertices) nk_buffer_clear(list->vertices); if (list->elements) nk_buffer_clear(list->elements); list->element_count = 0; list->vertex_count = 0; list->cmd_offset = 0; list->cmd_count = 0; list->path_count = 0; list->vertices = 0; list->elements = 0; list->clip_rect = nk_null_rect; } NK_INTERN struct nk_vec2* nk_draw_list_alloc_path(struct nk_draw_list *list, int count) { struct nk_vec2 *points; NK_STORAGE const nk_size point_align = NK_ALIGNOF(struct nk_vec2); NK_STORAGE const nk_size point_size = sizeof(struct nk_vec2); points = (struct nk_vec2*) nk_buffer_alloc(list->buffer, NK_BUFFER_FRONT, point_size * (nk_size)count, point_align); if (!points) return 0; if (!list->path_offset) { void *memory = nk_buffer_memory(list->buffer); list->path_offset = (unsigned int)((nk_byte*)points - (nk_byte*)memory); } list->path_count += (unsigned int)count; return points; } NK_INTERN struct nk_vec2 nk_draw_list_path_last(struct nk_draw_list *list) { void *memory; struct nk_vec2 *point; NK_ASSERT(list->path_count); memory = nk_buffer_memory(list->buffer); point = nk_ptr_add(struct nk_vec2, memory, list->path_offset); point += (list->path_count-1); return *point; } NK_INTERN struct nk_draw_command* nk_draw_list_push_command(struct nk_draw_list *list, struct nk_rect clip, nk_handle texture) { NK_STORAGE const nk_size cmd_align = NK_ALIGNOF(struct nk_draw_command); NK_STORAGE const nk_size cmd_size = sizeof(struct nk_draw_command); struct nk_draw_command *cmd; NK_ASSERT(list); cmd = (struct nk_draw_command*) nk_buffer_alloc(list->buffer, NK_BUFFER_BACK, cmd_size, cmd_align); if (!cmd) return 0; if (!list->cmd_count) { nk_byte *memory = (nk_byte*)nk_buffer_memory(list->buffer); nk_size total = nk_buffer_total(list->buffer); memory = nk_ptr_add(nk_byte, memory, total); list->cmd_offset = (nk_size)(memory - (nk_byte*)cmd); } cmd->elem_count = 0; cmd->clip_rect = clip; cmd->texture = texture; list->cmd_count++; list->clip_rect = clip; return cmd; } NK_INTERN struct nk_draw_command* nk_draw_list_command_last(struct nk_draw_list *list) { void *memory; nk_size size; struct nk_draw_command *cmd; NK_ASSERT(list->cmd_count); memory = nk_buffer_memory(list->buffer); size = nk_buffer_total(list->buffer); cmd = nk_ptr_add(struct nk_draw_command, memory, size - list->cmd_offset); return (cmd - (list->cmd_count-1)); } NK_INTERN void nk_draw_list_add_clip(struct nk_draw_list *list, struct nk_rect rect) { NK_ASSERT(list); if (!list) return; if (!list->cmd_count) { nk_draw_list_push_command(list, rect, list->config.null.texture); } else { struct nk_draw_command *prev = nk_draw_list_command_last(list); if (prev->elem_count == 0) prev->clip_rect = rect; nk_draw_list_push_command(list, rect, prev->texture); } } NK_INTERN void nk_draw_list_push_image(struct nk_draw_list *list, nk_handle texture) { NK_ASSERT(list); if (!list) return; if (!list->cmd_count) { nk_draw_list_push_command(list, nk_null_rect, texture); } else { struct nk_draw_command *prev = nk_draw_list_command_last(list); if (prev->elem_count == 0) prev->texture = texture; else if (prev->texture.id != texture.id) nk_draw_list_push_command(list, prev->clip_rect, texture); } } #ifdef NK_INCLUDE_COMMAND_USERDATA NK_API void nk_draw_list_push_userdata(struct nk_draw_list *list, nk_handle userdata) { NK_ASSERT(list); if (!list) return; if (!list->cmd_count) { struct nk_draw_command *prev; nk_draw_list_push_command(list, nk_null_rect, list->config.null.texture); prev = nk_draw_list_command_last(list); prev->userdata = userdata; } else { struct nk_draw_command *prev = nk_draw_list_command_last(list); if (prev->elem_count == 0) { prev->userdata = userdata; } else if (prev->userdata.ptr != userdata.ptr) { nk_draw_list_push_command(list, prev->clip_rect, prev->texture); prev = nk_draw_list_command_last(list); prev->userdata = userdata; } } } #endif NK_INTERN void* nk_draw_list_alloc_vertices(struct nk_draw_list *list, nk_size count) { void *vtx; NK_ASSERT(list); if (!list) return 0; vtx = nk_buffer_alloc(list->vertices, NK_BUFFER_FRONT, list->config.vertex_size*count, list->config.vertex_alignment); if (!vtx) return 0; list->vertex_count += (unsigned int)count; return vtx; } NK_INTERN nk_draw_index* nk_draw_list_alloc_elements(struct nk_draw_list *list, nk_size count) { nk_draw_index *ids; struct nk_draw_command *cmd; NK_STORAGE const nk_size elem_align = NK_ALIGNOF(nk_draw_index); NK_STORAGE const nk_size elem_size = sizeof(nk_draw_index); NK_ASSERT(list); if (!list) return 0; ids = (nk_draw_index*) nk_buffer_alloc(list->elements, NK_BUFFER_FRONT, elem_size*count, elem_align); if (!ids) return 0; cmd = nk_draw_list_command_last(list); list->element_count += (unsigned int)count; cmd->elem_count += (unsigned int)count; return ids; } static int nk_draw_vertex_layout_element_is_end_of_layout( const struct nk_draw_vertex_layout_element *element) { return (element->attribute == NK_VERTEX_ATTRIBUTE_COUNT || element->format == NK_FORMAT_COUNT); } static void nk_draw_vertex_color(void *attribute, const float *values, enum nk_draw_vertex_layout_format format) { /* if this triggers you tried to provide a value format for a color */ NK_ASSERT(format >= NK_FORMAT_COLOR_BEGIN); NK_ASSERT(format <= NK_FORMAT_COLOR_END); if (format < NK_FORMAT_COLOR_BEGIN || format > NK_FORMAT_COLOR_END) return; switch (format) { default: NK_ASSERT(0 && "Invalid vertex layout color format"); break; case NK_FORMAT_R8G8B8A8: case NK_FORMAT_R8G8B8: { struct nk_color col = nk_rgba_fv(values); NK_MEMCPY(attribute, &col.r, sizeof(col)); } break; case NK_FORMAT_R16G15B16: { nk_ushort col[3]; col[0] = (nk_ushort)NK_CLAMP(NK_USHORT_MIN, values[0] * NK_USHORT_MAX, NK_USHORT_MAX); col[1] = (nk_ushort)NK_CLAMP(NK_USHORT_MIN, values[1] * NK_USHORT_MAX, NK_USHORT_MAX); col[2] = (nk_ushort)NK_CLAMP(NK_USHORT_MIN, values[2] * NK_USHORT_MAX, NK_USHORT_MAX); NK_MEMCPY(attribute, col, sizeof(col)); } break; case NK_FORMAT_R16G15B16A16: { nk_ushort col[4]; col[0] = (nk_ushort)NK_CLAMP(NK_USHORT_MIN, values[0] * NK_USHORT_MAX, NK_USHORT_MAX); col[1] = (nk_ushort)NK_CLAMP(NK_USHORT_MIN, values[1] * NK_USHORT_MAX, NK_USHORT_MAX); col[2] = (nk_ushort)NK_CLAMP(NK_USHORT_MIN, values[2] * NK_USHORT_MAX, NK_USHORT_MAX); col[3] = (nk_ushort)NK_CLAMP(NK_USHORT_MIN, values[3] * NK_USHORT_MAX, NK_USHORT_MAX); NK_MEMCPY(attribute, col, sizeof(col)); } break; case NK_FORMAT_R32G32B32: { nk_uint col[3]; col[0] = (nk_uint)NK_CLAMP(NK_UINT_MIN, values[0] * NK_UINT_MAX, NK_UINT_MAX); col[1] = (nk_uint)NK_CLAMP(NK_UINT_MIN, values[1] * NK_UINT_MAX, NK_UINT_MAX); col[2] = (nk_uint)NK_CLAMP(NK_UINT_MIN, values[2] * NK_UINT_MAX, NK_UINT_MAX); NK_MEMCPY(attribute, col, sizeof(col)); } break; case NK_FORMAT_R32G32B32A32: { nk_uint col[4]; col[0] = (nk_uint)NK_CLAMP(NK_UINT_MIN, values[0] * NK_UINT_MAX, NK_UINT_MAX); col[1] = (nk_uint)NK_CLAMP(NK_UINT_MIN, values[1] * NK_UINT_MAX, NK_UINT_MAX); col[2] = (nk_uint)NK_CLAMP(NK_UINT_MIN, values[2] * NK_UINT_MAX, NK_UINT_MAX); col[3] = (nk_uint)NK_CLAMP(NK_UINT_MIN, values[3] * NK_UINT_MAX, NK_UINT_MAX); NK_MEMCPY(attribute, col, sizeof(col)); } break; case NK_FORMAT_R32G32B32A32_FLOAT: NK_MEMCPY(attribute, values, sizeof(float)*4); break; case NK_FORMAT_R32G32B32A32_DOUBLE: { double col[4]; col[0] = (double)NK_SATURATE(values[0]); col[1] = (double)NK_SATURATE(values[1]); col[2] = (double)NK_SATURATE(values[2]); col[3] = (double)NK_SATURATE(values[3]); NK_MEMCPY(attribute, col, sizeof(col)); } break; case NK_FORMAT_RGB32: case NK_FORMAT_RGBA32: { struct nk_color col = nk_rgba_fv(values); nk_uint color = nk_color_u32(col); NK_MEMCPY(attribute, &color, sizeof(color)); } break; } } static void nk_draw_vertex_element(void *dst, const float *values, int value_count, enum nk_draw_vertex_layout_format format) { int value_index; void *attribute = dst; /* if this triggers you tried to provide a color format for a value */ NK_ASSERT(format < NK_FORMAT_COLOR_BEGIN); if (format >= NK_FORMAT_COLOR_BEGIN && format <= NK_FORMAT_COLOR_END) return; for (value_index = 0; value_index < value_count; ++value_index) { switch (format) { default: NK_ASSERT(0 && "invalid vertex layout format"); break; case NK_FORMAT_SCHAR: { char value = (char)NK_CLAMP(NK_SCHAR_MIN, values[value_index], NK_SCHAR_MAX); NK_MEMCPY(attribute, &value, sizeof(value)); attribute = (void*)((char*)attribute + sizeof(char)); } break; case NK_FORMAT_SSHORT: { nk_short value = (nk_short)NK_CLAMP(NK_SSHORT_MIN, values[value_index], NK_SSHORT_MAX); NK_MEMCPY(attribute, &value, sizeof(value)); attribute = (void*)((char*)attribute + sizeof(value)); } break; case NK_FORMAT_SINT: { nk_int value = (nk_int)NK_CLAMP(NK_SINT_MIN, values[value_index], NK_SINT_MAX); NK_MEMCPY(attribute, &value, sizeof(value)); attribute = (void*)((char*)attribute + sizeof(nk_int)); } break; case NK_FORMAT_UCHAR: { unsigned char value = (unsigned char)NK_CLAMP(NK_UCHAR_MIN, values[value_index], NK_UCHAR_MAX); NK_MEMCPY(attribute, &value, sizeof(value)); attribute = (void*)((char*)attribute + sizeof(unsigned char)); } break; case NK_FORMAT_USHORT: { nk_ushort value = (nk_ushort)NK_CLAMP(NK_USHORT_MIN, values[value_index], NK_USHORT_MAX); NK_MEMCPY(attribute, &value, sizeof(value)); attribute = (void*)((char*)attribute + sizeof(value)); } break; case NK_FORMAT_UINT: { nk_uint value = (nk_uint)NK_CLAMP(NK_UINT_MIN, values[value_index], NK_UINT_MAX); NK_MEMCPY(attribute, &value, sizeof(value)); attribute = (void*)((char*)attribute + sizeof(nk_uint)); } break; case NK_FORMAT_FLOAT: NK_MEMCPY(attribute, &values[value_index], sizeof(values[value_index])); attribute = (void*)((char*)attribute + sizeof(float)); break; case NK_FORMAT_DOUBLE: { double value = (double)values[value_index]; NK_MEMCPY(attribute, &value, sizeof(value)); attribute = (void*)((char*)attribute + sizeof(double)); } break; } } } NK_INTERN void* nk_draw_vertex(void *dst, const struct nk_convert_config *config, struct nk_vec2 pos, struct nk_vec2 uv, struct nk_colorf color) { void *result = (void*)((char*)dst + config->vertex_size); const struct nk_draw_vertex_layout_element *elem_iter = config->vertex_layout; while (!nk_draw_vertex_layout_element_is_end_of_layout(elem_iter)) { void *address = (void*)((char*)dst + elem_iter->offset); switch (elem_iter->attribute) { case NK_VERTEX_ATTRIBUTE_COUNT: default: NK_ASSERT(0 && "wrong element attribute"); case NK_VERTEX_POSITION: nk_draw_vertex_element(address, &pos.x, 2, elem_iter->format); break; case NK_VERTEX_TEXCOORD: nk_draw_vertex_element(address, &uv.x, 2, elem_iter->format); break; case NK_VERTEX_COLOR: nk_draw_vertex_color(address, &color.r, elem_iter->format); break; } elem_iter++; } return result; } NK_API void nk_draw_list_stroke_poly_line(struct nk_draw_list *list, const struct nk_vec2 *points, const unsigned int points_count, struct nk_color color, enum nk_draw_list_stroke closed, float thickness, enum nk_anti_aliasing aliasing) { nk_size count; int thick_line; struct nk_colorf col; struct nk_colorf col_trans; NK_ASSERT(list); if (!list || points_count < 2) return; color.a = (nk_byte)((float)color.a * list->config.global_alpha); count = points_count; if (!closed) count = points_count-1; thick_line = thickness > 1.0f; #ifdef NK_INCLUDE_COMMAND_USERDATA nk_draw_list_push_userdata(list, list->userdata); #endif color.a = (nk_byte)((float)color.a * list->config.global_alpha); nk_color_fv(&col.r, color); col_trans = col; col_trans.a = 0; if (aliasing == NK_ANTI_ALIASING_ON) { /* ANTI-ALIASED STROKE */ const float AA_SIZE = 1.0f; NK_STORAGE const nk_size pnt_align = NK_ALIGNOF(struct nk_vec2); NK_STORAGE const nk_size pnt_size = sizeof(struct nk_vec2); /* allocate vertices and elements */ nk_size i1 = 0; nk_size vertex_offset; nk_size index = list->vertex_count; const nk_size idx_count = (thick_line) ? (count * 18) : (count * 12); const nk_size vtx_count = (thick_line) ? (points_count * 4): (points_count *3); void *vtx = nk_draw_list_alloc_vertices(list, vtx_count); nk_draw_index *ids = nk_draw_list_alloc_elements(list, idx_count); nk_size size; struct nk_vec2 *normals, *temp; NK_ASSERT(vtx && ids); if (!vtx || !ids) return; /* temporary allocate normals + points */ vertex_offset = (nk_size)((nk_byte*)vtx - (nk_byte*)list->vertices->memory.ptr); nk_buffer_mark(list->vertices, NK_BUFFER_FRONT); size = pnt_size * ((thick_line) ? 5 : 3) * points_count; normals = (struct nk_vec2*) nk_buffer_alloc(list->vertices, NK_BUFFER_FRONT, size, pnt_align); NK_ASSERT(normals); if (!normals) return; temp = normals + points_count; /* make sure vertex pointer is still correct */ vtx = (void*)((nk_byte*)list->vertices->memory.ptr + vertex_offset); /* calculate normals */ for (i1 = 0; i1 < count; ++i1) { const nk_size i2 = ((i1 + 1) == points_count) ? 0 : (i1 + 1); struct nk_vec2 diff = nk_vec2_sub(points[i2], points[i1]); float len; /* vec2 inverted length */ len = nk_vec2_len_sqr(diff); if (len != 0.0f) len = nk_inv_sqrt(len); else len = 1.0f; diff = nk_vec2_muls(diff, len); normals[i1].x = diff.y; normals[i1].y = -diff.x; } if (!closed) normals[points_count-1] = normals[points_count-2]; if (!thick_line) { nk_size idx1, i; if (!closed) { struct nk_vec2 d; temp[0] = nk_vec2_add(points[0], nk_vec2_muls(normals[0], AA_SIZE)); temp[1] = nk_vec2_sub(points[0], nk_vec2_muls(normals[0], AA_SIZE)); d = nk_vec2_muls(normals[points_count-1], AA_SIZE); temp[(points_count-1) * 2 + 0] = nk_vec2_add(points[points_count-1], d); temp[(points_count-1) * 2 + 1] = nk_vec2_sub(points[points_count-1], d); } /* fill elements */ idx1 = index; for (i1 = 0; i1 < count; i1++) { struct nk_vec2 dm; float dmr2; nk_size i2 = ((i1 + 1) == points_count) ? 0 : (i1 + 1); nk_size idx2 = ((i1+1) == points_count) ? index: (idx1 + 3); /* average normals */ dm = nk_vec2_muls(nk_vec2_add(normals[i1], normals[i2]), 0.5f); dmr2 = dm.x * dm.x + dm.y* dm.y; if (dmr2 > 0.000001f) { float scale = 1.0f/dmr2; scale = NK_MIN(100.0f, scale); dm = nk_vec2_muls(dm, scale); } dm = nk_vec2_muls(dm, AA_SIZE); temp[i2*2+0] = nk_vec2_add(points[i2], dm); temp[i2*2+1] = nk_vec2_sub(points[i2], dm); ids[0] = (nk_draw_index)(idx2 + 0); ids[1] = (nk_draw_index)(idx1+0); ids[2] = (nk_draw_index)(idx1 + 2); ids[3] = (nk_draw_index)(idx1+2); ids[4] = (nk_draw_index)(idx2 + 2); ids[5] = (nk_draw_index)(idx2+0); ids[6] = (nk_draw_index)(idx2 + 1); ids[7] = (nk_draw_index)(idx1+1); ids[8] = (nk_draw_index)(idx1 + 0); ids[9] = (nk_draw_index)(idx1+0); ids[10]= (nk_draw_index)(idx2 + 0); ids[11]= (nk_draw_index)(idx2+1); ids += 12; idx1 = idx2; } /* fill vertices */ for (i = 0; i < points_count; ++i) { const struct nk_vec2 uv = list->config.null.uv; vtx = nk_draw_vertex(vtx, &list->config, points[i], uv, col); vtx = nk_draw_vertex(vtx, &list->config, temp[i*2+0], uv, col_trans); vtx = nk_draw_vertex(vtx, &list->config, temp[i*2+1], uv, col_trans); } } else { nk_size idx1, i; const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; if (!closed) { struct nk_vec2 d1 = nk_vec2_muls(normals[0], half_inner_thickness + AA_SIZE); struct nk_vec2 d2 = nk_vec2_muls(normals[0], half_inner_thickness); temp[0] = nk_vec2_add(points[0], d1); temp[1] = nk_vec2_add(points[0], d2); temp[2] = nk_vec2_sub(points[0], d2); temp[3] = nk_vec2_sub(points[0], d1); d1 = nk_vec2_muls(normals[points_count-1], half_inner_thickness + AA_SIZE); d2 = nk_vec2_muls(normals[points_count-1], half_inner_thickness); temp[(points_count-1)*4+0] = nk_vec2_add(points[points_count-1], d1); temp[(points_count-1)*4+1] = nk_vec2_add(points[points_count-1], d2); temp[(points_count-1)*4+2] = nk_vec2_sub(points[points_count-1], d2); temp[(points_count-1)*4+3] = nk_vec2_sub(points[points_count-1], d1); } /* add all elements */ idx1 = index; for (i1 = 0; i1 < count; ++i1) { struct nk_vec2 dm_out, dm_in; const nk_size i2 = ((i1+1) == points_count) ? 0: (i1 + 1); nk_size idx2 = ((i1+1) == points_count) ? index: (idx1 + 4); /* average normals */ struct nk_vec2 dm = nk_vec2_muls(nk_vec2_add(normals[i1], normals[i2]), 0.5f); float dmr2 = dm.x * dm.x + dm.y* dm.y; if (dmr2 > 0.000001f) { float scale = 1.0f/dmr2; scale = NK_MIN(100.0f, scale); dm = nk_vec2_muls(dm, scale); } dm_out = nk_vec2_muls(dm, ((half_inner_thickness) + AA_SIZE)); dm_in = nk_vec2_muls(dm, half_inner_thickness); temp[i2*4+0] = nk_vec2_add(points[i2], dm_out); temp[i2*4+1] = nk_vec2_add(points[i2], dm_in); temp[i2*4+2] = nk_vec2_sub(points[i2], dm_in); temp[i2*4+3] = nk_vec2_sub(points[i2], dm_out); /* add indexes */ ids[0] = (nk_draw_index)(idx2 + 1); ids[1] = (nk_draw_index)(idx1+1); ids[2] = (nk_draw_index)(idx1 + 2); ids[3] = (nk_draw_index)(idx1+2); ids[4] = (nk_draw_index)(idx2 + 2); ids[5] = (nk_draw_index)(idx2+1); ids[6] = (nk_draw_index)(idx2 + 1); ids[7] = (nk_draw_index)(idx1+1); ids[8] = (nk_draw_index)(idx1 + 0); ids[9] = (nk_draw_index)(idx1+0); ids[10]= (nk_draw_index)(idx2 + 0); ids[11] = (nk_draw_index)(idx2+1); ids[12]= (nk_draw_index)(idx2 + 2); ids[13] = (nk_draw_index)(idx1+2); ids[14]= (nk_draw_index)(idx1 + 3); ids[15] = (nk_draw_index)(idx1+3); ids[16]= (nk_draw_index)(idx2 + 3); ids[17] = (nk_draw_index)(idx2+2); ids += 18; idx1 = idx2; } /* add vertices */ for (i = 0; i < points_count; ++i) { const struct nk_vec2 uv = list->config.null.uv; vtx = nk_draw_vertex(vtx, &list->config, temp[i*4+0], uv, col_trans); vtx = nk_draw_vertex(vtx, &list->config, temp[i*4+1], uv, col); vtx = nk_draw_vertex(vtx, &list->config, temp[i*4+2], uv, col); vtx = nk_draw_vertex(vtx, &list->config, temp[i*4+3], uv, col_trans); } } /* free temporary normals + points */ nk_buffer_reset(list->vertices, NK_BUFFER_FRONT); } else { /* NON ANTI-ALIASED STROKE */ nk_size i1 = 0; nk_size idx = list->vertex_count; const nk_size idx_count = count * 6; const nk_size vtx_count = count * 4; void *vtx = nk_draw_list_alloc_vertices(list, vtx_count); nk_draw_index *ids = nk_draw_list_alloc_elements(list, idx_count); if (!vtx || !ids) return; for (i1 = 0; i1 < count; ++i1) { float dx, dy; const struct nk_vec2 uv = list->config.null.uv; const nk_size i2 = ((i1+1) == points_count) ? 0 : i1 + 1; const struct nk_vec2 p1 = points[i1]; const struct nk_vec2 p2 = points[i2]; struct nk_vec2 diff = nk_vec2_sub(p2, p1); float len; /* vec2 inverted length */ len = nk_vec2_len_sqr(diff); if (len != 0.0f) len = nk_inv_sqrt(len); else len = 1.0f; diff = nk_vec2_muls(diff, len); /* add vertices */ dx = diff.x * (thickness * 0.5f); dy = diff.y * (thickness * 0.5f); vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(p1.x + dy, p1.y - dx), uv, col); vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(p2.x + dy, p2.y - dx), uv, col); vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(p2.x - dy, p2.y + dx), uv, col); vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(p1.x - dy, p1.y + dx), uv, col); ids[0] = (nk_draw_index)(idx+0); ids[1] = (nk_draw_index)(idx+1); ids[2] = (nk_draw_index)(idx+2); ids[3] = (nk_draw_index)(idx+0); ids[4] = (nk_draw_index)(idx+2); ids[5] = (nk_draw_index)(idx+3); ids += 6; idx += 4; } } } NK_API void nk_draw_list_fill_poly_convex(struct nk_draw_list *list, const struct nk_vec2 *points, const unsigned int points_count, struct nk_color color, enum nk_anti_aliasing aliasing) { struct nk_colorf col; struct nk_colorf col_trans; NK_STORAGE const nk_size pnt_align = NK_ALIGNOF(struct nk_vec2); NK_STORAGE const nk_size pnt_size = sizeof(struct nk_vec2); NK_ASSERT(list); if (!list || points_count < 3) return; #ifdef NK_INCLUDE_COMMAND_USERDATA nk_draw_list_push_userdata(list, list->userdata); #endif color.a = (nk_byte)((float)color.a * list->config.global_alpha); nk_color_fv(&col.r, color); col_trans = col; col_trans.a = 0; if (aliasing == NK_ANTI_ALIASING_ON) { nk_size i = 0; nk_size i0 = 0; nk_size i1 = 0; const float AA_SIZE = 1.0f; nk_size vertex_offset = 0; nk_size index = list->vertex_count; const nk_size idx_count = (points_count-2)*3 + points_count*6; const nk_size vtx_count = (points_count*2); void *vtx = nk_draw_list_alloc_vertices(list, vtx_count); nk_draw_index *ids = nk_draw_list_alloc_elements(list, idx_count); nk_size size = 0; struct nk_vec2 *normals = 0; unsigned int vtx_inner_idx = (unsigned int)(index + 0); unsigned int vtx_outer_idx = (unsigned int)(index + 1); if (!vtx || !ids) return; /* temporary allocate normals */ vertex_offset = (nk_size)((nk_byte*)vtx - (nk_byte*)list->vertices->memory.ptr); nk_buffer_mark(list->vertices, NK_BUFFER_FRONT); size = pnt_size * points_count; normals = (struct nk_vec2*) nk_buffer_alloc(list->vertices, NK_BUFFER_FRONT, size, pnt_align); NK_ASSERT(normals); if (!normals) return; vtx = (void*)((nk_byte*)list->vertices->memory.ptr + vertex_offset); /* add elements */ for (i = 2; i < points_count; i++) { ids[0] = (nk_draw_index)(vtx_inner_idx); ids[1] = (nk_draw_index)(vtx_inner_idx + ((i-1) << 1)); ids[2] = (nk_draw_index)(vtx_inner_idx + (i << 1)); ids += 3; } /* compute normals */ for (i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) { struct nk_vec2 p0 = points[i0]; struct nk_vec2 p1 = points[i1]; struct nk_vec2 diff = nk_vec2_sub(p1, p0); /* vec2 inverted length */ float len = nk_vec2_len_sqr(diff); if (len != 0.0f) len = nk_inv_sqrt(len); else len = 1.0f; diff = nk_vec2_muls(diff, len); normals[i0].x = diff.y; normals[i0].y = -diff.x; } /* add vertices + indexes */ for (i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) { const struct nk_vec2 uv = list->config.null.uv; struct nk_vec2 n0 = normals[i0]; struct nk_vec2 n1 = normals[i1]; struct nk_vec2 dm = nk_vec2_muls(nk_vec2_add(n0, n1), 0.5f); float dmr2 = dm.x*dm.x + dm.y*dm.y; if (dmr2 > 0.000001f) { float scale = 1.0f / dmr2; scale = NK_MIN(scale, 100.0f); dm = nk_vec2_muls(dm, scale); } dm = nk_vec2_muls(dm, AA_SIZE * 0.5f); /* add vertices */ vtx = nk_draw_vertex(vtx, &list->config, nk_vec2_sub(points[i1], dm), uv, col); vtx = nk_draw_vertex(vtx, &list->config, nk_vec2_add(points[i1], dm), uv, col_trans); /* add indexes */ ids[0] = (nk_draw_index)(vtx_inner_idx+(i1<<1)); ids[1] = (nk_draw_index)(vtx_inner_idx+(i0<<1)); ids[2] = (nk_draw_index)(vtx_outer_idx+(i0<<1)); ids[3] = (nk_draw_index)(vtx_outer_idx+(i0<<1)); ids[4] = (nk_draw_index)(vtx_outer_idx+(i1<<1)); ids[5] = (nk_draw_index)(vtx_inner_idx+(i1<<1)); ids += 6; } /* free temporary normals + points */ nk_buffer_reset(list->vertices, NK_BUFFER_FRONT); } else { nk_size i = 0; nk_size index = list->vertex_count; const nk_size idx_count = (points_count-2)*3; const nk_size vtx_count = points_count; void *vtx = nk_draw_list_alloc_vertices(list, vtx_count); nk_draw_index *ids = nk_draw_list_alloc_elements(list, idx_count); if (!vtx || !ids) return; for (i = 0; i < vtx_count; ++i) vtx = nk_draw_vertex(vtx, &list->config, points[i], list->config.null.uv, col); for (i = 2; i < points_count; ++i) { ids[0] = (nk_draw_index)index; ids[1] = (nk_draw_index)(index+ i - 1); ids[2] = (nk_draw_index)(index+i); ids += 3; } } } NK_API void nk_draw_list_path_clear(struct nk_draw_list *list) { NK_ASSERT(list); if (!list) return; nk_buffer_reset(list->buffer, NK_BUFFER_FRONT); list->path_count = 0; list->path_offset = 0; } NK_API void nk_draw_list_path_line_to(struct nk_draw_list *list, struct nk_vec2 pos) { struct nk_vec2 *points = 0; struct nk_draw_command *cmd = 0; NK_ASSERT(list); if (!list) return; if (!list->cmd_count) nk_draw_list_add_clip(list, nk_null_rect); cmd = nk_draw_list_command_last(list); if (cmd && cmd->texture.ptr != list->config.null.texture.ptr) nk_draw_list_push_image(list, list->config.null.texture); points = nk_draw_list_alloc_path(list, 1); if (!points) return; points[0] = pos; } NK_API void nk_draw_list_path_arc_to_fast(struct nk_draw_list *list, struct nk_vec2 center, float radius, int a_min, int a_max) { int a = 0; NK_ASSERT(list); if (!list) return; if (a_min <= a_max) { for (a = a_min; a <= a_max; a++) { const struct nk_vec2 c = list->circle_vtx[(nk_size)a % NK_LEN(list->circle_vtx)]; const float x = center.x + c.x * radius; const float y = center.y + c.y * radius; nk_draw_list_path_line_to(list, nk_vec2(x, y)); } } } NK_API void nk_draw_list_path_arc_to(struct nk_draw_list *list, struct nk_vec2 center, float radius, float a_min, float a_max, unsigned int segments) { unsigned int i = 0; NK_ASSERT(list); if (!list) return; if (radius == 0.0f) return; for (i = 0; i <= segments; ++i) { const float a = a_min + ((float)i / ((float)segments) * (a_max - a_min)); const float x = center.x + (float)NK_COS(a) * radius; const float y = center.y + (float)NK_SIN(a) * radius; nk_draw_list_path_line_to(list, nk_vec2(x, y)); } } NK_API void nk_draw_list_path_rect_to(struct nk_draw_list *list, struct nk_vec2 a, struct nk_vec2 b, float rounding) { float r; NK_ASSERT(list); if (!list) return; r = rounding; r = NK_MIN(r, ((b.x-a.x) < 0) ? -(b.x-a.x): (b.x-a.x)); r = NK_MIN(r, ((b.y-a.y) < 0) ? -(b.y-a.y): (b.y-a.y)); if (r == 0.0f) { nk_draw_list_path_line_to(list, a); nk_draw_list_path_line_to(list, nk_vec2(b.x,a.y)); nk_draw_list_path_line_to(list, b); nk_draw_list_path_line_to(list, nk_vec2(a.x,b.y)); } else { nk_draw_list_path_arc_to_fast(list, nk_vec2(a.x + r, a.y + r), r, 6, 9); nk_draw_list_path_arc_to_fast(list, nk_vec2(b.x - r, a.y + r), r, 9, 12); nk_draw_list_path_arc_to_fast(list, nk_vec2(b.x - r, b.y - r), r, 0, 3); nk_draw_list_path_arc_to_fast(list, nk_vec2(a.x + r, b.y - r), r, 3, 6); } } NK_API void nk_draw_list_path_curve_to(struct nk_draw_list *list, struct nk_vec2 p2, struct nk_vec2 p3, struct nk_vec2 p4, unsigned int num_segments) { float t_step; unsigned int i_step; struct nk_vec2 p1; NK_ASSERT(list); NK_ASSERT(list->path_count); if (!list || !list->path_count) return; num_segments = NK_MAX(num_segments, 1); p1 = nk_draw_list_path_last(list); t_step = 1.0f/(float)num_segments; for (i_step = 1; i_step <= num_segments; ++i_step) { float t = t_step * (float)i_step; float u = 1.0f - t; float w1 = u*u*u; float w2 = 3*u*u*t; float w3 = 3*u*t*t; float w4 = t * t *t; float x = w1 * p1.x + w2 * p2.x + w3 * p3.x + w4 * p4.x; float y = w1 * p1.y + w2 * p2.y + w3 * p3.y + w4 * p4.y; nk_draw_list_path_line_to(list, nk_vec2(x,y)); } } NK_API void nk_draw_list_path_fill(struct nk_draw_list *list, struct nk_color color) { struct nk_vec2 *points; NK_ASSERT(list); if (!list) return; points = (struct nk_vec2*)nk_buffer_memory(list->buffer); nk_draw_list_fill_poly_convex(list, points, list->path_count, color, list->config.shape_AA); nk_draw_list_path_clear(list); } NK_API void nk_draw_list_path_stroke(struct nk_draw_list *list, struct nk_color color, enum nk_draw_list_stroke closed, float thickness) { struct nk_vec2 *points; NK_ASSERT(list); if (!list) return; points = (struct nk_vec2*)nk_buffer_memory(list->buffer); nk_draw_list_stroke_poly_line(list, points, list->path_count, color, closed, thickness, list->config.line_AA); nk_draw_list_path_clear(list); } NK_API void nk_draw_list_stroke_line(struct nk_draw_list *list, struct nk_vec2 a, struct nk_vec2 b, struct nk_color col, float thickness) { NK_ASSERT(list); if (!list || !col.a) return; nk_draw_list_path_line_to(list, nk_vec2_add(a, nk_vec2(0.5f, 0.5f))); nk_draw_list_path_line_to(list, nk_vec2_add(b, nk_vec2(0.5f, 0.5f))); nk_draw_list_path_stroke(list, col, NK_STROKE_OPEN, thickness); } NK_API void nk_draw_list_fill_rect(struct nk_draw_list *list, struct nk_rect rect, struct nk_color col, float rounding) { NK_ASSERT(list); if (!list || !col.a) return; nk_draw_list_path_rect_to(list, nk_vec2(rect.x + 0.5f, rect.y + 0.5f), nk_vec2(rect.x + rect.w + 0.5f, rect.y + rect.h + 0.5f), rounding); nk_draw_list_path_fill(list, col); } NK_API void nk_draw_list_stroke_rect(struct nk_draw_list *list, struct nk_rect rect, struct nk_color col, float rounding, float thickness) { NK_ASSERT(list); if (!list || !col.a) return; nk_draw_list_path_rect_to(list, nk_vec2(rect.x + 0.5f, rect.y + 0.5f), nk_vec2(rect.x + rect.w + 0.5f, rect.y + rect.h + 0.5f), rounding); nk_draw_list_path_stroke(list, col, NK_STROKE_CLOSED, thickness); } NK_API void nk_draw_list_fill_rect_multi_color(struct nk_draw_list *list, struct nk_rect rect, struct nk_color left, struct nk_color top, struct nk_color right, struct nk_color bottom) { void *vtx; struct nk_colorf col_left, col_top; struct nk_colorf col_right, col_bottom; nk_draw_index *idx; nk_draw_index index; nk_color_fv(&col_left.r, left); nk_color_fv(&col_right.r, right); nk_color_fv(&col_top.r, top); nk_color_fv(&col_bottom.r, bottom); NK_ASSERT(list); if (!list) return; nk_draw_list_push_image(list, list->config.null.texture); index = (nk_draw_index)list->vertex_count; vtx = nk_draw_list_alloc_vertices(list, 4); idx = nk_draw_list_alloc_elements(list, 6); if (!vtx || !idx) return; idx[0] = (nk_draw_index)(index+0); idx[1] = (nk_draw_index)(index+1); idx[2] = (nk_draw_index)(index+2); idx[3] = (nk_draw_index)(index+0); idx[4] = (nk_draw_index)(index+2); idx[5] = (nk_draw_index)(index+3); vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x, rect.y), list->config.null.uv, col_left); vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x + rect.w, rect.y), list->config.null.uv, col_top); vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x + rect.w, rect.y + rect.h), list->config.null.uv, col_right); vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x, rect.y + rect.h), list->config.null.uv, col_bottom); } NK_API void nk_draw_list_fill_triangle(struct nk_draw_list *list, struct nk_vec2 a, struct nk_vec2 b, struct nk_vec2 c, struct nk_color col) { NK_ASSERT(list); if (!list || !col.a) return; nk_draw_list_path_line_to(list, a); nk_draw_list_path_line_to(list, b); nk_draw_list_path_line_to(list, c); nk_draw_list_path_fill(list, col); } NK_API void nk_draw_list_stroke_triangle(struct nk_draw_list *list, struct nk_vec2 a, struct nk_vec2 b, struct nk_vec2 c, struct nk_color col, float thickness) { NK_ASSERT(list); if (!list || !col.a) return; nk_draw_list_path_line_to(list, a); nk_draw_list_path_line_to(list, b); nk_draw_list_path_line_to(list, c); nk_draw_list_path_stroke(list, col, NK_STROKE_CLOSED, thickness); } NK_API void nk_draw_list_fill_circle(struct nk_draw_list *list, struct nk_vec2 center, float radius, struct nk_color col, unsigned int segs) { float a_max; NK_ASSERT(list); if (!list || !col.a) return; a_max = NK_PI * 2.0f * ((float)segs - 1.0f) / (float)segs; nk_draw_list_path_arc_to(list, center, radius, 0.0f, a_max, segs); nk_draw_list_path_fill(list, col); } NK_API void nk_draw_list_stroke_circle(struct nk_draw_list *list, struct nk_vec2 center, float radius, struct nk_color col, unsigned int segs, float thickness) { float a_max; NK_ASSERT(list); if (!list || !col.a) return; a_max = NK_PI * 2.0f * ((float)segs - 1.0f) / (float)segs; nk_draw_list_path_arc_to(list, center, radius, 0.0f, a_max, segs); nk_draw_list_path_stroke(list, col, NK_STROKE_CLOSED, thickness); } NK_API void nk_draw_list_stroke_curve(struct nk_draw_list *list, struct nk_vec2 p0, struct nk_vec2 cp0, struct nk_vec2 cp1, struct nk_vec2 p1, struct nk_color col, unsigned int segments, float thickness) { NK_ASSERT(list); if (!list || !col.a) return; nk_draw_list_path_line_to(list, p0); nk_draw_list_path_curve_to(list, cp0, cp1, p1, segments); nk_draw_list_path_stroke(list, col, NK_STROKE_OPEN, thickness); } NK_INTERN void nk_draw_list_push_rect_uv(struct nk_draw_list *list, struct nk_vec2 a, struct nk_vec2 c, struct nk_vec2 uva, struct nk_vec2 uvc, struct nk_color color) { void *vtx; struct nk_vec2 uvb; struct nk_vec2 uvd; struct nk_vec2 b; struct nk_vec2 d; struct nk_colorf col; nk_draw_index *idx; nk_draw_index index; NK_ASSERT(list); if (!list) return; nk_color_fv(&col.r, color); uvb = nk_vec2(uvc.x, uva.y); uvd = nk_vec2(uva.x, uvc.y); b = nk_vec2(c.x, a.y); d = nk_vec2(a.x, c.y); index = (nk_draw_index)list->vertex_count; vtx = nk_draw_list_alloc_vertices(list, 4); idx = nk_draw_list_alloc_elements(list, 6); if (!vtx || !idx) return; idx[0] = (nk_draw_index)(index+0); idx[1] = (nk_draw_index)(index+1); idx[2] = (nk_draw_index)(index+2); idx[3] = (nk_draw_index)(index+0); idx[4] = (nk_draw_index)(index+2); idx[5] = (nk_draw_index)(index+3); vtx = nk_draw_vertex(vtx, &list->config, a, uva, col); vtx = nk_draw_vertex(vtx, &list->config, b, uvb, col); vtx = nk_draw_vertex(vtx, &list->config, c, uvc, col); vtx = nk_draw_vertex(vtx, &list->config, d, uvd, col); } NK_API void nk_draw_list_add_image(struct nk_draw_list *list, struct nk_image texture, struct nk_rect rect, struct nk_color color) { NK_ASSERT(list); if (!list) return; /* push new command with given texture */ nk_draw_list_push_image(list, texture.handle); if (nk_image_is_subimage(&texture)) { /* add region inside of the texture */ struct nk_vec2 uv[2]; uv[0].x = (float)texture.region[0]/(float)texture.w; uv[0].y = (float)texture.region[1]/(float)texture.h; uv[1].x = (float)(texture.region[0] + texture.region[2])/(float)texture.w; uv[1].y = (float)(texture.region[1] + texture.region[3])/(float)texture.h; nk_draw_list_push_rect_uv(list, nk_vec2(rect.x, rect.y), nk_vec2(rect.x + rect.w, rect.y + rect.h), uv[0], uv[1], color); } else nk_draw_list_push_rect_uv(list, nk_vec2(rect.x, rect.y), nk_vec2(rect.x + rect.w, rect.y + rect.h), nk_vec2(0.0f, 0.0f), nk_vec2(1.0f, 1.0f),color); } NK_API void nk_draw_list_add_text(struct nk_draw_list *list, const struct nk_user_font *font, struct nk_rect rect, const char *text, int len, float font_height, struct nk_color fg) { float x = 0; int text_len = 0; nk_rune unicode = 0; nk_rune next = 0; int glyph_len = 0; int next_glyph_len = 0; struct nk_user_font_glyph g; NK_ASSERT(list); if (!list || !len || !text) return; if (!NK_INTERSECT(rect.x, rect.y, rect.w, rect.h, list->clip_rect.x, list->clip_rect.y, list->clip_rect.w, list->clip_rect.h)) return; nk_draw_list_push_image(list, font->texture); x = rect.x; glyph_len = text_len = nk_utf_decode(text, &unicode, len); if (!glyph_len) return; /* draw every glyph image */ fg.a = (nk_byte)((float)fg.a * list->config.global_alpha); while (text_len <= len && glyph_len) { float gx, gy, gh, gw; float char_width = 0; if (unicode == NK_UTF_INVALID) break; /* query currently drawn glyph information */ next_glyph_len = nk_utf_decode(text + text_len, &next, (int)len - text_len); font->query(font->userdata, font_height, &g, unicode, (next == NK_UTF_INVALID) ? '\0' : next); /* calculate and draw glyph drawing rectangle and image */ gx = x + g.offset.x; gy = rect.y + g.offset.y; gw = g.width; gh = g.height; char_width = g.xadvance; nk_draw_list_push_rect_uv(list, nk_vec2(gx,gy), nk_vec2(gx + gw, gy+ gh), g.uv[0], g.uv[1], fg); /* offset next glyph */ text_len += glyph_len; x += char_width; glyph_len = next_glyph_len; unicode = next; } } NK_API void nk_convert(struct nk_context *ctx, struct nk_buffer *cmds, struct nk_buffer *vertices, struct nk_buffer *elements, const struct nk_convert_config *config) { const struct nk_command *cmd; NK_ASSERT(ctx); NK_ASSERT(cmds); NK_ASSERT(vertices); NK_ASSERT(elements); NK_ASSERT(config); NK_ASSERT(config->vertex_layout); NK_ASSERT(config->vertex_size); if (!ctx || !cmds || !vertices || !elements || !config || !config->vertex_layout) return; nk_draw_list_setup(&ctx->draw_list, config, cmds, vertices, elements); nk_foreach(cmd, ctx) { #ifdef NK_INCLUDE_COMMAND_USERDATA ctx->draw_list.userdata = cmd->userdata; #endif switch (cmd->type) { case NK_COMMAND_NOP: break; case NK_COMMAND_SCISSOR: { const struct nk_command_scissor *s = (const struct nk_command_scissor*)cmd; nk_draw_list_add_clip(&ctx->draw_list, nk_rect(s->x, s->y, s->w, s->h)); } break; case NK_COMMAND_LINE: { const struct nk_command_line *l = (const struct nk_command_line*)cmd; nk_draw_list_stroke_line(&ctx->draw_list, nk_vec2(l->begin.x, l->begin.y), nk_vec2(l->end.x, l->end.y), l->color, l->line_thickness); } break; case NK_COMMAND_CURVE: { const struct nk_command_curve *q = (const struct nk_command_curve*)cmd; nk_draw_list_stroke_curve(&ctx->draw_list, nk_vec2(q->begin.x, q->begin.y), nk_vec2(q->ctrl[0].x, q->ctrl[0].y), nk_vec2(q->ctrl[1].x, q->ctrl[1].y), nk_vec2(q->end.x, q->end.y), q->color, config->curve_segment_count, q->line_thickness); } break; case NK_COMMAND_RECT: { const struct nk_command_rect *r = (const struct nk_command_rect*)cmd; nk_draw_list_stroke_rect(&ctx->draw_list, nk_rect(r->x, r->y, r->w, r->h), r->color, (float)r->rounding, r->line_thickness); } break; case NK_COMMAND_RECT_FILLED: { const struct nk_command_rect_filled *r = (const struct nk_command_rect_filled*)cmd; nk_draw_list_fill_rect(&ctx->draw_list, nk_rect(r->x, r->y, r->w, r->h), r->color, (float)r->rounding); } break; case NK_COMMAND_RECT_MULTI_COLOR: { const struct nk_command_rect_multi_color *r = (const struct nk_command_rect_multi_color*)cmd; nk_draw_list_fill_rect_multi_color(&ctx->draw_list, nk_rect(r->x, r->y, r->w, r->h), r->left, r->top, r->right, r->bottom); } break; case NK_COMMAND_CIRCLE: { const struct nk_command_circle *c = (const struct nk_command_circle*)cmd; nk_draw_list_stroke_circle(&ctx->draw_list, nk_vec2((float)c->x + (float)c->w/2, (float)c->y + (float)c->h/2), (float)c->w/2, c->color, config->circle_segment_count, c->line_thickness); } break; case NK_COMMAND_CIRCLE_FILLED: { const struct nk_command_circle_filled *c = (const struct nk_command_circle_filled *)cmd; nk_draw_list_fill_circle(&ctx->draw_list, nk_vec2((float)c->x + (float)c->w/2, (float)c->y + (float)c->h/2), (float)c->w/2, c->color, config->circle_segment_count); } break; case NK_COMMAND_ARC: { const struct nk_command_arc *c = (const struct nk_command_arc*)cmd; nk_draw_list_path_line_to(&ctx->draw_list, nk_vec2(c->cx, c->cy)); nk_draw_list_path_arc_to(&ctx->draw_list, nk_vec2(c->cx, c->cy), c->r, c->a[0], c->a[1], config->arc_segment_count); nk_draw_list_path_stroke(&ctx->draw_list, c->color, NK_STROKE_CLOSED, c->line_thickness); } break; case NK_COMMAND_ARC_FILLED: { const struct nk_command_arc_filled *c = (const struct nk_command_arc_filled*)cmd; nk_draw_list_path_line_to(&ctx->draw_list, nk_vec2(c->cx, c->cy)); nk_draw_list_path_arc_to(&ctx->draw_list, nk_vec2(c->cx, c->cy), c->r, c->a[0], c->a[1], config->arc_segment_count); nk_draw_list_path_fill(&ctx->draw_list, c->color); } break; case NK_COMMAND_TRIANGLE: { const struct nk_command_triangle *t = (const struct nk_command_triangle*)cmd; nk_draw_list_stroke_triangle(&ctx->draw_list, nk_vec2(t->a.x, t->a.y), nk_vec2(t->b.x, t->b.y), nk_vec2(t->c.x, t->c.y), t->color, t->line_thickness); } break; case NK_COMMAND_TRIANGLE_FILLED: { const struct nk_command_triangle_filled *t = (const struct nk_command_triangle_filled*)cmd; nk_draw_list_fill_triangle(&ctx->draw_list, nk_vec2(t->a.x, t->a.y), nk_vec2(t->b.x, t->b.y), nk_vec2(t->c.x, t->c.y), t->color); } break; case NK_COMMAND_POLYGON: { int i; const struct nk_command_polygon*p = (const struct nk_command_polygon*)cmd; for (i = 0; i < p->point_count; ++i) { struct nk_vec2 pnt = nk_vec2((float)p->points[i].x, (float)p->points[i].y); nk_draw_list_path_line_to(&ctx->draw_list, pnt); } nk_draw_list_path_stroke(&ctx->draw_list, p->color, NK_STROKE_CLOSED, p->line_thickness); } break; case NK_COMMAND_POLYGON_FILLED: { int i; const struct nk_command_polygon_filled *p = (const struct nk_command_polygon_filled*)cmd; for (i = 0; i < p->point_count; ++i) { struct nk_vec2 pnt = nk_vec2((float)p->points[i].x, (float)p->points[i].y); nk_draw_list_path_line_to(&ctx->draw_list, pnt); } nk_draw_list_path_fill(&ctx->draw_list, p->color); } break; case NK_COMMAND_POLYLINE: { int i; const struct nk_command_polyline *p = (const struct nk_command_polyline*)cmd; for (i = 0; i < p->point_count; ++i) { struct nk_vec2 pnt = nk_vec2((float)p->points[i].x, (float)p->points[i].y); nk_draw_list_path_line_to(&ctx->draw_list, pnt); } nk_draw_list_path_stroke(&ctx->draw_list, p->color, NK_STROKE_OPEN, p->line_thickness); } break; case NK_COMMAND_TEXT: { const struct nk_command_text *t = (const struct nk_command_text*)cmd; nk_draw_list_add_text(&ctx->draw_list, t->font, nk_rect(t->x, t->y, t->w, t->h), t->string, t->length, t->height, t->foreground); } break; case NK_COMMAND_IMAGE: { const struct nk_command_image *i = (const struct nk_command_image*)cmd; nk_draw_list_add_image(&ctx->draw_list, i->img, nk_rect(i->x, i->y, i->w, i->h), i->col); } break; default: break; } } } NK_API const struct nk_draw_command* nk__draw_begin(const struct nk_context *ctx, const struct nk_buffer *buffer) {return nk__draw_list_begin(&ctx->draw_list, buffer);} NK_API const struct nk_draw_command* nk__draw_end(const struct nk_context *ctx, const struct nk_buffer *buffer) {return nk__draw_list_end(&ctx->draw_list, buffer);} NK_API const struct nk_draw_command* nk__draw_next(const struct nk_draw_command *cmd, const struct nk_buffer *buffer, const struct nk_context *ctx) {return nk__draw_list_next(cmd, buffer, &ctx->draw_list);} #endif /* * ============================================================== * * FONT HANDLING * * =============================================================== */ #ifdef NK_INCLUDE_FONT_BAKING /* ------------------------------------------------------------- * * RECT PACK * * --------------------------------------------------------------*/ /* stb_rect_pack.h - v0.05 - public domain - rectangle packing */ /* Sean Barrett 2014 */ #define NK_RP__MAXVAL 0xffff typedef unsigned short nk_rp_coord; struct nk_rp_rect { /* reserved for your use: */ int id; /* input: */ nk_rp_coord w, h; /* output: */ nk_rp_coord x, y; int was_packed; /* non-zero if valid packing */ }; /* 16 bytes, nominally */ struct nk_rp_node { nk_rp_coord x,y; struct nk_rp_node *next; }; struct nk_rp_context { int width; int height; int align; int init_mode; int heuristic; int num_nodes; struct nk_rp_node *active_head; struct nk_rp_node *free_head; struct nk_rp_node extra[2]; /* we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2' */ }; struct nk_rp__findresult { int x,y; struct nk_rp_node **prev_link; }; enum NK_RP_HEURISTIC { NK_RP_HEURISTIC_Skyline_default=0, NK_RP_HEURISTIC_Skyline_BL_sortHeight = NK_RP_HEURISTIC_Skyline_default, NK_RP_HEURISTIC_Skyline_BF_sortHeight }; enum NK_RP_INIT_STATE{NK_RP__INIT_skyline = 1}; NK_INTERN void nk_rp_setup_allow_out_of_mem(struct nk_rp_context *context, int allow_out_of_mem) { if (allow_out_of_mem) /* if it's ok to run out of memory, then don't bother aligning them; */ /* this gives better packing, but may fail due to OOM (even though */ /* the rectangles easily fit). @TODO a smarter approach would be to only */ /* quantize once we've hit OOM, then we could get rid of this parameter. */ context->align = 1; else { /* if it's not ok to run out of memory, then quantize the widths */ /* so that num_nodes is always enough nodes. */ /* */ /* I.e. num_nodes * align >= width */ /* align >= width / num_nodes */ /* align = ceil(width/num_nodes) */ context->align = (context->width + context->num_nodes-1) / context->num_nodes; } } NK_INTERN void nk_rp_init_target(struct nk_rp_context *context, int width, int height, struct nk_rp_node *nodes, int num_nodes) { int i; #ifndef STBRP_LARGE_RECTS NK_ASSERT(width <= 0xffff && height <= 0xffff); #endif for (i=0; i < num_nodes-1; ++i) nodes[i].next = &nodes[i+1]; nodes[i].next = 0; context->init_mode = NK_RP__INIT_skyline; context->heuristic = NK_RP_HEURISTIC_Skyline_default; context->free_head = &nodes[0]; context->active_head = &context->extra[0]; context->width = width; context->height = height; context->num_nodes = num_nodes; nk_rp_setup_allow_out_of_mem(context, 0); /* node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly) */ context->extra[0].x = 0; context->extra[0].y = 0; context->extra[0].next = &context->extra[1]; context->extra[1].x = (nk_rp_coord) width; context->extra[1].y = 65535; context->extra[1].next = 0; } /* find minimum y position if it starts at x1 */ NK_INTERN int nk_rp__skyline_find_min_y(struct nk_rp_context *c, struct nk_rp_node *first, int x0, int width, int *pwaste) { struct nk_rp_node *node = first; int x1 = x0 + width; int min_y, visited_width, waste_area; NK_ASSERT(first->x <= x0); NK_UNUSED(c); NK_ASSERT(node->next->x > x0); /* we ended up handling this in the caller for efficiency */ NK_ASSERT(node->x <= x0); min_y = 0; waste_area = 0; visited_width = 0; while (node->x < x1) { if (node->y > min_y) { /* raise min_y higher. */ /* we've accounted for all waste up to min_y, */ /* but we'll now add more waste for everything we've visited */ waste_area += visited_width * (node->y - min_y); min_y = node->y; /* the first time through, visited_width might be reduced */ if (node->x < x0) visited_width += node->next->x - x0; else visited_width += node->next->x - node->x; } else { /* add waste area */ int under_width = node->next->x - node->x; if (under_width + visited_width > width) under_width = width - visited_width; waste_area += under_width * (min_y - node->y); visited_width += under_width; } node = node->next; } *pwaste = waste_area; return min_y; } NK_INTERN struct nk_rp__findresult nk_rp__skyline_find_best_pos(struct nk_rp_context *c, int width, int height) { int best_waste = (1<<30), best_x, best_y = (1 << 30); struct nk_rp__findresult fr; struct nk_rp_node **prev, *node, *tail, **best = 0; /* align to multiple of c->align */ width = (width + c->align - 1); width -= width % c->align; NK_ASSERT(width % c->align == 0); node = c->active_head; prev = &c->active_head; while (node->x + width <= c->width) { int y,waste; y = nk_rp__skyline_find_min_y(c, node, node->x, width, &waste); /* actually just want to test BL */ if (c->heuristic == NK_RP_HEURISTIC_Skyline_BL_sortHeight) { /* bottom left */ if (y < best_y) { best_y = y; best = prev; } } else { /* best-fit */ if (y + height <= c->height) { /* can only use it if it first vertically */ if (y < best_y || (y == best_y && waste < best_waste)) { best_y = y; best_waste = waste; best = prev; } } } prev = &node->next; node = node->next; } best_x = (best == 0) ? 0 : (*best)->x; /* if doing best-fit (BF), we also have to try aligning right edge to each node position */ /* */ /* e.g, if fitting */ /* */ /* ____________________ */ /* |____________________| */ /* */ /* into */ /* */ /* | | */ /* | ____________| */ /* |____________| */ /* */ /* then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned */ /* */ /* This makes BF take about 2x the time */ if (c->heuristic == NK_RP_HEURISTIC_Skyline_BF_sortHeight) { tail = c->active_head; node = c->active_head; prev = &c->active_head; /* find first node that's admissible */ while (tail->x < width) tail = tail->next; while (tail) { int xpos = tail->x - width; int y,waste; NK_ASSERT(xpos >= 0); /* find the left position that matches this */ while (node->next->x <= xpos) { prev = &node->next; node = node->next; } NK_ASSERT(node->next->x > xpos && node->x <= xpos); y = nk_rp__skyline_find_min_y(c, node, xpos, width, &waste); if (y + height < c->height) { if (y <= best_y) { if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) { best_x = xpos; NK_ASSERT(y <= best_y); best_y = y; best_waste = waste; best = prev; } } } tail = tail->next; } } fr.prev_link = best; fr.x = best_x; fr.y = best_y; return fr; } NK_INTERN struct nk_rp__findresult nk_rp__skyline_pack_rectangle(struct nk_rp_context *context, int width, int height) { /* find best position according to heuristic */ struct nk_rp__findresult res = nk_rp__skyline_find_best_pos(context, width, height); struct nk_rp_node *node, *cur; /* bail if: */ /* 1. it failed */ /* 2. the best node doesn't fit (we don't always check this) */ /* 3. we're out of memory */ if (res.prev_link == 0 || res.y + height > context->height || context->free_head == 0) { res.prev_link = 0; return res; } /* on success, create new node */ node = context->free_head; node->x = (nk_rp_coord) res.x; node->y = (nk_rp_coord) (res.y + height); context->free_head = node->next; /* insert the new node into the right starting point, and */ /* let 'cur' point to the remaining nodes needing to be */ /* stitched back in */ cur = *res.prev_link; if (cur->x < res.x) { /* preserve the existing one, so start testing with the next one */ struct nk_rp_node *next = cur->next; cur->next = node; cur = next; } else { *res.prev_link = node; } /* from here, traverse cur and free the nodes, until we get to one */ /* that shouldn't be freed */ while (cur->next && cur->next->x <= res.x + width) { struct nk_rp_node *next = cur->next; /* move the current node to the free list */ cur->next = context->free_head; context->free_head = cur; cur = next; } /* stitch the list back in */ node->next = cur; if (cur->x < res.x + width) cur->x = (nk_rp_coord) (res.x + width); return res; } NK_INTERN int nk_rect_height_compare(const void *a, const void *b) { const struct nk_rp_rect *p = (const struct nk_rp_rect *) a; const struct nk_rp_rect *q = (const struct nk_rp_rect *) b; if (p->h > q->h) return -1; if (p->h < q->h) return 1; return (p->w > q->w) ? -1 : (p->w < q->w); } NK_INTERN int nk_rect_original_order(const void *a, const void *b) { const struct nk_rp_rect *p = (const struct nk_rp_rect *) a; const struct nk_rp_rect *q = (const struct nk_rp_rect *) b; return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed); } static void nk_rp_qsort(struct nk_rp_rect *array, unsigned int len, int(*cmp)(const void*,const void*)) { /* iterative quick sort */ #define NK_MAX_SORT_STACK 64 unsigned right, left = 0, stack[NK_MAX_SORT_STACK], pos = 0; unsigned seed = len/2 * 69069+1; for (;;) { for (; left+1 < len; len++) { struct nk_rp_rect pivot, tmp; if (pos == NK_MAX_SORT_STACK) len = stack[pos = 0]; pivot = array[left+seed%(len-left)]; seed = seed * 69069 + 1; stack[pos++] = len; for (right = left-1;;) { while (cmp(&array[++right], &pivot) < 0); while (cmp(&pivot, &array[--len]) < 0); if (right >= len) break; tmp = array[right]; array[right] = array[len]; array[len] = tmp; } } if (pos == 0) break; left = len; len = stack[--pos]; } #undef NK_MAX_SORT_STACK } NK_INTERN void nk_rp_pack_rects(struct nk_rp_context *context, struct nk_rp_rect *rects, int num_rects) { int i; /* we use the 'was_packed' field internally to allow sorting/unsorting */ for (i=0; i < num_rects; ++i) { rects[i].was_packed = i; } /* sort according to heuristic */ nk_rp_qsort(rects, (unsigned)num_rects, nk_rect_height_compare); for (i=0; i < num_rects; ++i) { struct nk_rp__findresult fr = nk_rp__skyline_pack_rectangle(context, rects[i].w, rects[i].h); if (fr.prev_link) { rects[i].x = (nk_rp_coord) fr.x; rects[i].y = (nk_rp_coord) fr.y; } else { rects[i].x = rects[i].y = NK_RP__MAXVAL; } } /* unsort */ nk_rp_qsort(rects, (unsigned)num_rects, nk_rect_original_order); /* set was_packed flags */ for (i=0; i < num_rects; ++i) rects[i].was_packed = !(rects[i].x == NK_RP__MAXVAL && rects[i].y == NK_RP__MAXVAL); } /* * ============================================================== * * TRUETYPE * * =============================================================== */ /* stb_truetype.h - v1.07 - public domain */ #define NK_TT_MAX_OVERSAMPLE 8 #define NK_TT__OVER_MASK (NK_TT_MAX_OVERSAMPLE-1) struct nk_tt_bakedchar { unsigned short x0,y0,x1,y1; /* coordinates of bbox in bitmap */ float xoff,yoff,xadvance; }; struct nk_tt_aligned_quad{ float x0,y0,s0,t0; /* top-left */ float x1,y1,s1,t1; /* bottom-right */ }; struct nk_tt_packedchar { unsigned short x0,y0,x1,y1; /* coordinates of bbox in bitmap */ float xoff,yoff,xadvance; float xoff2,yoff2; }; struct nk_tt_pack_range { float font_size; int first_unicode_codepoint_in_range; /* if non-zero, then the chars are continuous, and this is the first codepoint */ int *array_of_unicode_codepoints; /* if non-zero, then this is an array of unicode codepoints */ int num_chars; struct nk_tt_packedchar *chardata_for_range; /* output */ unsigned char h_oversample, v_oversample; /* don't set these, they're used internally */ }; struct nk_tt_pack_context { void *pack_info; int width; int height; int stride_in_bytes; int padding; unsigned int h_oversample, v_oversample; unsigned char *pixels; void *nodes; }; struct nk_tt_fontinfo { const unsigned char* data; /* pointer to .ttf file */ int fontstart;/* offset of start of font */ int numGlyphs;/* number of glyphs, needed for range checking */ int loca,head,glyf,hhea,hmtx,kern; /* table locations as offset from start of .ttf */ int index_map; /* a cmap mapping for our chosen character encoding */ int indexToLocFormat; /* format needed to map from glyph index to glyph */ }; enum { NK_TT_vmove=1, NK_TT_vline, NK_TT_vcurve }; struct nk_tt_vertex { short x,y,cx,cy; unsigned char type,padding; }; struct nk_tt__bitmap{ int w,h,stride; unsigned char *pixels; }; struct nk_tt__hheap_chunk { struct nk_tt__hheap_chunk *next; }; struct nk_tt__hheap { struct nk_allocator alloc; struct nk_tt__hheap_chunk *head; void *first_free; int num_remaining_in_head_chunk; }; struct nk_tt__edge { float x0,y0, x1,y1; int invert; }; struct nk_tt__active_edge { struct nk_tt__active_edge *next; float fx,fdx,fdy; float direction; float sy; float ey; }; struct nk_tt__point {float x,y;}; #define NK_TT_MACSTYLE_DONTCARE 0 #define NK_TT_MACSTYLE_BOLD 1 #define NK_TT_MACSTYLE_ITALIC 2 #define NK_TT_MACSTYLE_UNDERSCORE 4 #define NK_TT_MACSTYLE_NONE 8 /* <= not same as 0, this makes us check the bitfield is 0 */ enum { /* platformID */ NK_TT_PLATFORM_ID_UNICODE =0, NK_TT_PLATFORM_ID_MAC =1, NK_TT_PLATFORM_ID_ISO =2, NK_TT_PLATFORM_ID_MICROSOFT =3 }; enum { /* encodingID for NK_TT_PLATFORM_ID_UNICODE */ NK_TT_UNICODE_EID_UNICODE_1_0 =0, NK_TT_UNICODE_EID_UNICODE_1_1 =1, NK_TT_UNICODE_EID_ISO_10646 =2, NK_TT_UNICODE_EID_UNICODE_2_0_BMP=3, NK_TT_UNICODE_EID_UNICODE_2_0_FULL=4 }; enum { /* encodingID for NK_TT_PLATFORM_ID_MICROSOFT */ NK_TT_MS_EID_SYMBOL =0, NK_TT_MS_EID_UNICODE_BMP =1, NK_TT_MS_EID_SHIFTJIS =2, NK_TT_MS_EID_UNICODE_FULL =10 }; enum { /* encodingID for NK_TT_PLATFORM_ID_MAC; same as Script Manager codes */ NK_TT_MAC_EID_ROMAN =0, NK_TT_MAC_EID_ARABIC =4, NK_TT_MAC_EID_JAPANESE =1, NK_TT_MAC_EID_HEBREW =5, NK_TT_MAC_EID_CHINESE_TRAD =2, NK_TT_MAC_EID_GREEK =6, NK_TT_MAC_EID_KOREAN =3, NK_TT_MAC_EID_RUSSIAN =7 }; enum { /* languageID for NK_TT_PLATFORM_ID_MICROSOFT; same as LCID... */ /* problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs */ NK_TT_MS_LANG_ENGLISH =0x0409, NK_TT_MS_LANG_ITALIAN =0x0410, NK_TT_MS_LANG_CHINESE =0x0804, NK_TT_MS_LANG_JAPANESE =0x0411, NK_TT_MS_LANG_DUTCH =0x0413, NK_TT_MS_LANG_KOREAN =0x0412, NK_TT_MS_LANG_FRENCH =0x040c, NK_TT_MS_LANG_RUSSIAN =0x0419, NK_TT_MS_LANG_GERMAN =0x0407, NK_TT_MS_LANG_SPANISH =0x0409, NK_TT_MS_LANG_HEBREW =0x040d, NK_TT_MS_LANG_SWEDISH =0x041D }; enum { /* languageID for NK_TT_PLATFORM_ID_MAC */ NK_TT_MAC_LANG_ENGLISH =0 , NK_TT_MAC_LANG_JAPANESE =11, NK_TT_MAC_LANG_ARABIC =12, NK_TT_MAC_LANG_KOREAN =23, NK_TT_MAC_LANG_DUTCH =4 , NK_TT_MAC_LANG_RUSSIAN =32, NK_TT_MAC_LANG_FRENCH =1 , NK_TT_MAC_LANG_SPANISH =6 , NK_TT_MAC_LANG_GERMAN =2 , NK_TT_MAC_LANG_SWEDISH =5 , NK_TT_MAC_LANG_HEBREW =10, NK_TT_MAC_LANG_CHINESE_SIMPLIFIED =33, NK_TT_MAC_LANG_ITALIAN =3 , NK_TT_MAC_LANG_CHINESE_TRAD =19 }; #define nk_ttBYTE(p) (* (const nk_byte *) (p)) #define nk_ttCHAR(p) (* (const char *) (p)) #if defined(NK_BIGENDIAN) && !defined(NK_ALLOW_UNALIGNED_TRUETYPE) #define nk_ttUSHORT(p) (* (nk_ushort *) (p)) #define nk_ttSHORT(p) (* (nk_short *) (p)) #define nk_ttULONG(p) (* (nk_uint *) (p)) #define nk_ttLONG(p) (* (nk_int *) (p)) #else static nk_ushort nk_ttUSHORT(const nk_byte *p) { return (nk_ushort)(p[0]*256 + p[1]); } static nk_short nk_ttSHORT(const nk_byte *p) { return (nk_short)(p[0]*256 + p[1]); } static nk_uint nk_ttULONG(const nk_byte *p) { return (nk_uint)((p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]); } #endif #define nk_tt_tag4(p,c0,c1,c2,c3)\ ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) #define nk_tt_tag(p,str) nk_tt_tag4(p,str[0],str[1],str[2],str[3]) NK_INTERN int nk_tt_GetGlyphShape(const struct nk_tt_fontinfo *info, struct nk_allocator *alloc, int glyph_index, struct nk_tt_vertex **pvertices); NK_INTERN nk_uint nk_tt__find_table(const nk_byte *data, nk_uint fontstart, const char *tag) { /* @OPTIMIZE: binary search */ nk_int num_tables = nk_ttUSHORT(data+fontstart+4); nk_uint tabledir = fontstart + 12; nk_int i; for (i = 0; i < num_tables; ++i) { nk_uint loc = tabledir + (nk_uint)(16*i); if (nk_tt_tag(data+loc+0, tag)) return nk_ttULONG(data+loc+8); } return 0; } NK_INTERN int nk_tt_InitFont(struct nk_tt_fontinfo *info, const unsigned char *data2, int fontstart) { nk_uint cmap, t; nk_int i,numTables; const nk_byte *data = (const nk_byte *) data2; info->data = data; info->fontstart = fontstart; cmap = nk_tt__find_table(data, (nk_uint)fontstart, "cmap"); /* required */ info->loca = (int)nk_tt__find_table(data, (nk_uint)fontstart, "loca"); /* required */ info->head = (int)nk_tt__find_table(data, (nk_uint)fontstart, "head"); /* required */ info->glyf = (int)nk_tt__find_table(data, (nk_uint)fontstart, "glyf"); /* required */ info->hhea = (int)nk_tt__find_table(data, (nk_uint)fontstart, "hhea"); /* required */ info->hmtx = (int)nk_tt__find_table(data, (nk_uint)fontstart, "hmtx"); /* required */ info->kern = (int)nk_tt__find_table(data, (nk_uint)fontstart, "kern"); /* not required */ if (!cmap || !info->loca || !info->head || !info->glyf || !info->hhea || !info->hmtx) return 0; t = nk_tt__find_table(data, (nk_uint)fontstart, "maxp"); if (t) info->numGlyphs = nk_ttUSHORT(data+t+4); else info->numGlyphs = 0xffff; /* find a cmap encoding table we understand *now* to avoid searching */ /* later. (todo: could make this installable) */ /* the same regardless of glyph. */ numTables = nk_ttUSHORT(data + cmap + 2); info->index_map = 0; for (i=0; i < numTables; ++i) { nk_uint encoding_record = cmap + 4 + 8 * (nk_uint)i; /* find an encoding we understand: */ switch(nk_ttUSHORT(data+encoding_record)) { case NK_TT_PLATFORM_ID_MICROSOFT: switch (nk_ttUSHORT(data+encoding_record+2)) { case NK_TT_MS_EID_UNICODE_BMP: case NK_TT_MS_EID_UNICODE_FULL: /* MS/Unicode */ info->index_map = (int)(cmap + nk_ttULONG(data+encoding_record+4)); break; default: break; } break; case NK_TT_PLATFORM_ID_UNICODE: /* Mac/iOS has these */ /* all the encodingIDs are unicode, so we don't bother to check it */ info->index_map = (int)(cmap + nk_ttULONG(data+encoding_record+4)); break; default: break; } } if (info->index_map == 0) return 0; info->indexToLocFormat = nk_ttUSHORT(data+info->head + 50); return 1; } NK_INTERN int nk_tt_FindGlyphIndex(const struct nk_tt_fontinfo *info, int unicode_codepoint) { const nk_byte *data = info->data; nk_uint index_map = (nk_uint)info->index_map; nk_ushort format = nk_ttUSHORT(data + index_map + 0); if (format == 0) { /* apple byte encoding */ nk_int bytes = nk_ttUSHORT(data + index_map + 2); if (unicode_codepoint < bytes-6) return nk_ttBYTE(data + index_map + 6 + unicode_codepoint); return 0; } else if (format == 6) { nk_uint first = nk_ttUSHORT(data + index_map + 6); nk_uint count = nk_ttUSHORT(data + index_map + 8); if ((nk_uint) unicode_codepoint >= first && (nk_uint) unicode_codepoint < first+count) return nk_ttUSHORT(data + index_map + 10 + (unicode_codepoint - (int)first)*2); return 0; } else if (format == 2) { NK_ASSERT(0); /* @TODO: high-byte mapping for japanese/chinese/korean */ return 0; } else if (format == 4) { /* standard mapping for windows fonts: binary search collection of ranges */ nk_ushort segcount = nk_ttUSHORT(data+index_map+6) >> 1; nk_ushort searchRange = nk_ttUSHORT(data+index_map+8) >> 1; nk_ushort entrySelector = nk_ttUSHORT(data+index_map+10); nk_ushort rangeShift = nk_ttUSHORT(data+index_map+12) >> 1; /* do a binary search of the segments */ nk_uint endCount = index_map + 14; nk_uint search = endCount; if (unicode_codepoint > 0xffff) return 0; /* they lie from endCount .. endCount + segCount */ /* but searchRange is the nearest power of two, so... */ if (unicode_codepoint >= nk_ttUSHORT(data + search + rangeShift*2)) search += (nk_uint)(rangeShift*2); /* now decrement to bias correctly to find smallest */ search -= 2; while (entrySelector) { nk_ushort end; searchRange >>= 1; end = nk_ttUSHORT(data + search + searchRange*2); if (unicode_codepoint > end) search += (nk_uint)(searchRange*2); --entrySelector; } search += 2; { nk_ushort offset, start; nk_ushort item = (nk_ushort) ((search - endCount) >> 1); NK_ASSERT(unicode_codepoint <= nk_ttUSHORT(data + endCount + 2*item)); start = nk_ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); if (unicode_codepoint < start) return 0; offset = nk_ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); if (offset == 0) return (nk_ushort) (unicode_codepoint + nk_ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); return nk_ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); } } else if (format == 12 || format == 13) { nk_uint ngroups = nk_ttULONG(data+index_map+12); nk_int low,high; low = 0; high = (nk_int)ngroups; /* Binary search the right group. */ while (low < high) { nk_int mid = low + ((high-low) >> 1); /* rounds down, so low <= mid < high */ nk_uint start_char = nk_ttULONG(data+index_map+16+mid*12); nk_uint end_char = nk_ttULONG(data+index_map+16+mid*12+4); if ((nk_uint) unicode_codepoint < start_char) high = mid; else if ((nk_uint) unicode_codepoint > end_char) low = mid+1; else { nk_uint start_glyph = nk_ttULONG(data+index_map+16+mid*12+8); if (format == 12) return (int)start_glyph + (int)unicode_codepoint - (int)start_char; else /* format == 13 */ return (int)start_glyph; } } return 0; /* not found */ } /* @TODO */ NK_ASSERT(0); return 0; } NK_INTERN void nk_tt_setvertex(struct nk_tt_vertex *v, nk_byte type, nk_int x, nk_int y, nk_int cx, nk_int cy) { v->type = type; v->x = (nk_short) x; v->y = (nk_short) y; v->cx = (nk_short) cx; v->cy = (nk_short) cy; } NK_INTERN int nk_tt__GetGlyfOffset(const struct nk_tt_fontinfo *info, int glyph_index) { int g1,g2; if (glyph_index >= info->numGlyphs) return -1; /* glyph index out of range */ if (info->indexToLocFormat >= 2) return -1; /* unknown index->glyph map format */ if (info->indexToLocFormat == 0) { g1 = info->glyf + nk_ttUSHORT(info->data + info->loca + glyph_index * 2) * 2; g2 = info->glyf + nk_ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2; } else { g1 = info->glyf + (int)nk_ttULONG (info->data + info->loca + glyph_index * 4); g2 = info->glyf + (int)nk_ttULONG (info->data + info->loca + glyph_index * 4 + 4); } return g1==g2 ? -1 : g1; /* if length is 0, return -1 */ } NK_INTERN int nk_tt_GetGlyphBox(const struct nk_tt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) { int g = nk_tt__GetGlyfOffset(info, glyph_index); if (g < 0) return 0; if (x0) *x0 = nk_ttSHORT(info->data + g + 2); if (y0) *y0 = nk_ttSHORT(info->data + g + 4); if (x1) *x1 = nk_ttSHORT(info->data + g + 6); if (y1) *y1 = nk_ttSHORT(info->data + g + 8); return 1; } NK_INTERN int stbtt__close_shape(struct nk_tt_vertex *vertices, int num_vertices, int was_off, int start_off, nk_int sx, nk_int sy, nk_int scx, nk_int scy, nk_int cx, nk_int cy) { if (start_off) { if (was_off) nk_tt_setvertex(&vertices[num_vertices++], NK_TT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy); nk_tt_setvertex(&vertices[num_vertices++], NK_TT_vcurve, sx,sy,scx,scy); } else { if (was_off) nk_tt_setvertex(&vertices[num_vertices++], NK_TT_vcurve,sx,sy,cx,cy); else nk_tt_setvertex(&vertices[num_vertices++], NK_TT_vline,sx,sy,0,0); } return num_vertices; } NK_INTERN int nk_tt_GetGlyphShape(const struct nk_tt_fontinfo *info, struct nk_allocator *alloc, int glyph_index, struct nk_tt_vertex **pvertices) { nk_short numberOfContours; const nk_byte *endPtsOfContours; const nk_byte *data = info->data; struct nk_tt_vertex *vertices=0; int num_vertices=0; int g = nk_tt__GetGlyfOffset(info, glyph_index); *pvertices = 0; if (g < 0) return 0; numberOfContours = nk_ttSHORT(data + g); if (numberOfContours > 0) { nk_byte flags=0,flagcount; nk_int ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0; nk_int x,y,cx,cy,sx,sy, scx,scy; const nk_byte *points; endPtsOfContours = (data + g + 10); ins = nk_ttUSHORT(data + g + 10 + numberOfContours * 2); points = data + g + 10 + numberOfContours * 2 + 2 + ins; n = 1+nk_ttUSHORT(endPtsOfContours + numberOfContours*2-2); m = n + 2*numberOfContours; /* a loose bound on how many vertices we might need */ vertices = (struct nk_tt_vertex *)alloc->alloc(alloc->userdata, 0, (nk_size)m * sizeof(vertices[0])); if (vertices == 0) return 0; next_move = 0; flagcount=0; /* in first pass, we load uninterpreted data into the allocated array */ /* above, shifted to the end of the array so we won't overwrite it when */ /* we create our final data starting from the front */ off = m - n; /* starting offset for uninterpreted data, regardless of how m ends up being calculated */ /* first load flags */ for (i=0; i < n; ++i) { if (flagcount == 0) { flags = *points++; if (flags & 8) flagcount = *points++; } else --flagcount; vertices[off+i].type = flags; } /* now load x coordinates */ x=0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; if (flags & 2) { nk_short dx = *points++; x += (flags & 16) ? dx : -dx; /* ??? */ } else { if (!(flags & 16)) { x = x + (nk_short) (points[0]*256 + points[1]); points += 2; } } vertices[off+i].x = (nk_short) x; } /* now load y coordinates */ y=0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; if (flags & 4) { nk_short dy = *points++; y += (flags & 32) ? dy : -dy; /* ??? */ } else { if (!(flags & 32)) { y = y + (nk_short) (points[0]*256 + points[1]); points += 2; } } vertices[off+i].y = (nk_short) y; } /* now convert them to our format */ num_vertices=0; sx = sy = cx = cy = scx = scy = 0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; x = (nk_short) vertices[off+i].x; y = (nk_short) vertices[off+i].y; if (next_move == i) { if (i != 0) num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); /* now start the new one */ start_off = !(flags & 1); if (start_off) { /* if we start off with an off-curve point, then when we need to find a point on the curve */ /* where we can start, and we need to save some state for when we wraparound. */ scx = x; scy = y; if (!(vertices[off+i+1].type & 1)) { /* next point is also a curve point, so interpolate an on-point curve */ sx = (x + (nk_int) vertices[off+i+1].x) >> 1; sy = (y + (nk_int) vertices[off+i+1].y) >> 1; } else { /* otherwise just use the next point as our start point */ sx = (nk_int) vertices[off+i+1].x; sy = (nk_int) vertices[off+i+1].y; ++i; /* we're using point i+1 as the starting point, so skip it */ } } else { sx = x; sy = y; } nk_tt_setvertex(&vertices[num_vertices++], NK_TT_vmove,sx,sy,0,0); was_off = 0; next_move = 1 + nk_ttUSHORT(endPtsOfContours+j*2); ++j; } else { if (!(flags & 1)) { /* if it's a curve */ if (was_off) /* two off-curve control points in a row means interpolate an on-curve midpoint */ nk_tt_setvertex(&vertices[num_vertices++], NK_TT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy); cx = x; cy = y; was_off = 1; } else { if (was_off) nk_tt_setvertex(&vertices[num_vertices++], NK_TT_vcurve, x,y, cx, cy); else nk_tt_setvertex(&vertices[num_vertices++], NK_TT_vline, x,y,0,0); was_off = 0; } } } num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); } else if (numberOfContours == -1) { /* Compound shapes. */ int more = 1; const nk_byte *comp = data + g + 10; num_vertices = 0; vertices = 0; while (more) { nk_ushort flags, gidx; int comp_num_verts = 0, i; struct nk_tt_vertex *comp_verts = 0, *tmp = 0; float mtx[6] = {1,0,0,1,0,0}, m, n; flags = (nk_ushort)nk_ttSHORT(comp); comp+=2; gidx = (nk_ushort)nk_ttSHORT(comp); comp+=2; if (flags & 2) { /* XY values */ if (flags & 1) { /* shorts */ mtx[4] = nk_ttSHORT(comp); comp+=2; mtx[5] = nk_ttSHORT(comp); comp+=2; } else { mtx[4] = nk_ttCHAR(comp); comp+=1; mtx[5] = nk_ttCHAR(comp); comp+=1; } } else { /* @TODO handle matching point */ NK_ASSERT(0); } if (flags & (1<<3)) { /* WE_HAVE_A_SCALE */ mtx[0] = mtx[3] = nk_ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = mtx[2] = 0; } else if (flags & (1<<6)) { /* WE_HAVE_AN_X_AND_YSCALE */ mtx[0] = nk_ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = mtx[2] = 0; mtx[3] = nk_ttSHORT(comp)/16384.0f; comp+=2; } else if (flags & (1<<7)) { /* WE_HAVE_A_TWO_BY_TWO */ mtx[0] = nk_ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = nk_ttSHORT(comp)/16384.0f; comp+=2; mtx[2] = nk_ttSHORT(comp)/16384.0f; comp+=2; mtx[3] = nk_ttSHORT(comp)/16384.0f; comp+=2; } /* Find transformation scales. */ m = (float) NK_SQRT(mtx[0]*mtx[0] + mtx[1]*mtx[1]); n = (float) NK_SQRT(mtx[2]*mtx[2] + mtx[3]*mtx[3]); /* Get indexed glyph. */ comp_num_verts = nk_tt_GetGlyphShape(info, alloc, gidx, &comp_verts); if (comp_num_verts > 0) { /* Transform vertices. */ for (i = 0; i < comp_num_verts; ++i) { struct nk_tt_vertex* v = &comp_verts[i]; short x,y; x=v->x; y=v->y; v->x = (short)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); v->y = (short)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); x=v->cx; y=v->cy; v->cx = (short)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); v->cy = (short)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); } /* Append vertices. */ tmp = (struct nk_tt_vertex*)alloc->alloc(alloc->userdata, 0, (nk_size)(num_vertices+comp_num_verts)*sizeof(struct nk_tt_vertex)); if (!tmp) { if (vertices) alloc->free(alloc->userdata, vertices); if (comp_verts) alloc->free(alloc->userdata, comp_verts); return 0; } if (num_vertices > 0) NK_MEMCPY(tmp, vertices, (nk_size)num_vertices*sizeof(struct nk_tt_vertex)); NK_MEMCPY(tmp+num_vertices, comp_verts, (nk_size)comp_num_verts*sizeof(struct nk_tt_vertex)); if (vertices) alloc->free(alloc->userdata,vertices); vertices = tmp; alloc->free(alloc->userdata,comp_verts); num_vertices += comp_num_verts; } /* More components ? */ more = flags & (1<<5); } } else if (numberOfContours < 0) { /* @TODO other compound variations? */ NK_ASSERT(0); } else { /* numberOfCounters == 0, do nothing */ } *pvertices = vertices; return num_vertices; } NK_INTERN void nk_tt_GetGlyphHMetrics(const struct nk_tt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) { nk_ushort numOfLongHorMetrics = nk_ttUSHORT(info->data+info->hhea + 34); if (glyph_index < numOfLongHorMetrics) { if (advanceWidth) *advanceWidth = nk_ttSHORT(info->data + info->hmtx + 4*glyph_index); if (leftSideBearing) *leftSideBearing = nk_ttSHORT(info->data + info->hmtx + 4*glyph_index + 2); } else { if (advanceWidth) *advanceWidth = nk_ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1)); if (leftSideBearing) *leftSideBearing = nk_ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics)); } } NK_INTERN void nk_tt_GetFontVMetrics(const struct nk_tt_fontinfo *info, int *ascent, int *descent, int *lineGap) { if (ascent ) *ascent = nk_ttSHORT(info->data+info->hhea + 4); if (descent) *descent = nk_ttSHORT(info->data+info->hhea + 6); if (lineGap) *lineGap = nk_ttSHORT(info->data+info->hhea + 8); } NK_INTERN float nk_tt_ScaleForPixelHeight(const struct nk_tt_fontinfo *info, float height) { int fheight = nk_ttSHORT(info->data + info->hhea + 4) - nk_ttSHORT(info->data + info->hhea + 6); return (float) height / (float)fheight; } NK_INTERN float nk_tt_ScaleForMappingEmToPixels(const struct nk_tt_fontinfo *info, float pixels) { int unitsPerEm = nk_ttUSHORT(info->data + info->head + 18); return pixels / (float)unitsPerEm; } /*------------------------------------------------------------- * antialiasing software rasterizer * --------------------------------------------------------------*/ NK_INTERN void nk_tt_GetGlyphBitmapBoxSubpixel(const struct nk_tt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) { int x0,y0,x1,y1; if (!nk_tt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) { /* e.g. space character */ if (ix0) *ix0 = 0; if (iy0) *iy0 = 0; if (ix1) *ix1 = 0; if (iy1) *iy1 = 0; } else { /* move to integral bboxes (treating pixels as little squares, what pixels get touched)? */ if (ix0) *ix0 = nk_ifloorf((float)x0 * scale_x + shift_x); if (iy0) *iy0 = nk_ifloorf((float)-y1 * scale_y + shift_y); if (ix1) *ix1 = nk_iceilf ((float)x1 * scale_x + shift_x); if (iy1) *iy1 = nk_iceilf ((float)-y0 * scale_y + shift_y); } } NK_INTERN void nk_tt_GetGlyphBitmapBox(const struct nk_tt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) { nk_tt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1); } /*------------------------------------------------------------- * Rasterizer * --------------------------------------------------------------*/ NK_INTERN void* nk_tt__hheap_alloc(struct nk_tt__hheap *hh, nk_size size) { if (hh->first_free) { void *p = hh->first_free; hh->first_free = * (void **) p; return p; } else { if (hh->num_remaining_in_head_chunk == 0) { int count = (size < 32 ? 2000 : size < 128 ? 800 : 100); struct nk_tt__hheap_chunk *c = (struct nk_tt__hheap_chunk *) hh->alloc.alloc(hh->alloc.userdata, 0, sizeof(struct nk_tt__hheap_chunk) + size * (nk_size)count); if (c == 0) return 0; c->next = hh->head; hh->head = c; hh->num_remaining_in_head_chunk = count; } --hh->num_remaining_in_head_chunk; return (char *) (hh->head) + size * (nk_size)hh->num_remaining_in_head_chunk; } } NK_INTERN void nk_tt__hheap_free(struct nk_tt__hheap *hh, void *p) { *(void **) p = hh->first_free; hh->first_free = p; } NK_INTERN void nk_tt__hheap_cleanup(struct nk_tt__hheap *hh) { struct nk_tt__hheap_chunk *c = hh->head; while (c) { struct nk_tt__hheap_chunk *n = c->next; hh->alloc.free(hh->alloc.userdata, c); c = n; } } NK_INTERN struct nk_tt__active_edge* nk_tt__new_active(struct nk_tt__hheap *hh, struct nk_tt__edge *e, int off_x, float start_point) { struct nk_tt__active_edge *z = (struct nk_tt__active_edge *) nk_tt__hheap_alloc(hh, sizeof(*z)); float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); /*STBTT_assert(e->y0 <= start_point); */ if (!z) return z; z->fdx = dxdy; z->fdy = (dxdy != 0) ? (1/dxdy): 0; z->fx = e->x0 + dxdy * (start_point - e->y0); z->fx -= (float)off_x; z->direction = e->invert ? 1.0f : -1.0f; z->sy = e->y0; z->ey = e->y1; z->next = 0; return z; } NK_INTERN void nk_tt__handle_clipped_edge(float *scanline, int x, struct nk_tt__active_edge *e, float x0, float y0, float x1, float y1) { if (y0 == y1) return; NK_ASSERT(y0 < y1); NK_ASSERT(e->sy <= e->ey); if (y0 > e->ey) return; if (y1 < e->sy) return; if (y0 < e->sy) { x0 += (x1-x0) * (e->sy - y0) / (y1-y0); y0 = e->sy; } if (y1 > e->ey) { x1 += (x1-x0) * (e->ey - y1) / (y1-y0); y1 = e->ey; } if (x0 == x) NK_ASSERT(x1 <= x+1); else if (x0 == x+1) NK_ASSERT(x1 >= x); else if (x0 <= x) NK_ASSERT(x1 <= x); else if (x0 >= x+1) NK_ASSERT(x1 >= x+1); else NK_ASSERT(x1 >= x && x1 <= x+1); if (x0 <= x && x1 <= x) scanline[x] += e->direction * (y1-y0); else if (x0 >= x+1 && x1 >= x+1); else { NK_ASSERT(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1); /* coverage = 1 - average x position */ scanline[x] += (float)e->direction * (float)(y1-y0) * (1.0f-((x0-(float)x)+(x1-(float)x))/2.0f); } } NK_INTERN void nk_tt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, struct nk_tt__active_edge *e, float y_top) { float y_bottom = y_top+1; while (e) { /* brute force every pixel */ /* compute intersection points with top & bottom */ NK_ASSERT(e->ey >= y_top); if (e->fdx == 0) { float x0 = e->fx; if (x0 < len) { if (x0 >= 0) { nk_tt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom); nk_tt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom); } else { nk_tt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom); } } } else { float x0 = e->fx; float dx = e->fdx; float xb = x0 + dx; float x_top, x_bottom; float y0,y1; float dy = e->fdy; NK_ASSERT(e->sy <= y_bottom && e->ey >= y_top); /* compute endpoints of line segment clipped to this scanline (if the */ /* line segment starts on this scanline. x0 is the intersection of the */ /* line with y_top, but that may be off the line segment. */ if (e->sy > y_top) { x_top = x0 + dx * (e->sy - y_top); y0 = e->sy; } else { x_top = x0; y0 = y_top; } if (e->ey < y_bottom) { x_bottom = x0 + dx * (e->ey - y_top); y1 = e->ey; } else { x_bottom = xb; y1 = y_bottom; } if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) { /* from here on, we don't have to range check x values */ if ((int) x_top == (int) x_bottom) { float height; /* simple case, only spans one pixel */ int x = (int) x_top; height = y1 - y0; NK_ASSERT(x >= 0 && x < len); scanline[x] += e->direction * (1.0f-(((float)x_top - (float)x) + ((float)x_bottom-(float)x))/2.0f) * (float)height; scanline_fill[x] += e->direction * (float)height; /* everything right of this pixel is filled */ } else { int x,x1,x2; float y_crossing, step, sign, area; /* covers 2+ pixels */ if (x_top > x_bottom) { /* flip scanline vertically; signed area is the same */ float t; y0 = y_bottom - (y0 - y_top); y1 = y_bottom - (y1 - y_top); t = y0, y0 = y1, y1 = t; t = x_bottom, x_bottom = x_top, x_top = t; dx = -dx; dy = -dy; t = x0, x0 = xb, xb = t; } x1 = (int) x_top; x2 = (int) x_bottom; /* compute intersection with y axis at x1+1 */ y_crossing = ((float)x1+1 - (float)x0) * (float)dy + (float)y_top; sign = e->direction; /* area of the rectangle covered from y0..y_crossing */ area = sign * (y_crossing-y0); /* area of the triangle (x_top,y0), (x+1,y0), (x+1,y_crossing) */ scanline[x1] += area * (1.0f-((float)((float)x_top - (float)x1)+(float)(x1+1-x1))/2.0f); step = sign * dy; for (x = x1+1; x < x2; ++x) { scanline[x] += area + step/2; area += step; } y_crossing += (float)dy * (float)(x2 - (x1+1)); scanline[x2] += area + sign * (1.0f-((float)(x2-x2)+((float)x_bottom-(float)x2))/2.0f) * (y1-y_crossing); scanline_fill[x2] += sign * (y1-y0); } } else { /* if edge goes outside of box we're drawing, we require */ /* clipping logic. since this does not match the intended use */ /* of this library, we use a different, very slow brute */ /* force implementation */ int x; for (x=0; x < len; ++x) { /* cases: */ /* */ /* there can be up to two intersections with the pixel. any intersection */ /* with left or right edges can be handled by splitting into two (or three) */ /* regions. intersections with top & bottom do not necessitate case-wise logic. */ /* */ /* the old way of doing this found the intersections with the left & right edges, */ /* then used some simple logic to produce up to three segments in sorted order */ /* from top-to-bottom. however, this had a problem: if an x edge was epsilon */ /* across the x border, then the corresponding y position might not be distinct */ /* from the other y segment, and it might ignored as an empty segment. to avoid */ /* that, we need to explicitly produce segments based on x positions. */ /* rename variables to clear pairs */ float ya = y_top; float x1 = (float) (x); float x2 = (float) (x+1); float x3 = xb; float y3 = y_bottom; float yb,y2; yb = ((float)x - x0) / dx + y_top; y2 = ((float)x+1 - x0) / dx + y_top; if (x0 < x1 && x3 > x2) { /* three segments descending down-right */ nk_tt__handle_clipped_edge(scanline,x,e, x0,ya, x1,yb); nk_tt__handle_clipped_edge(scanline,x,e, x1,yb, x2,y2); nk_tt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); } else if (x3 < x1 && x0 > x2) { /* three segments descending down-left */ nk_tt__handle_clipped_edge(scanline,x,e, x0,ya, x2,y2); nk_tt__handle_clipped_edge(scanline,x,e, x2,y2, x1,yb); nk_tt__handle_clipped_edge(scanline,x,e, x1,yb, x3,y3); } else if (x0 < x1 && x3 > x1) { /* two segments across x, down-right */ nk_tt__handle_clipped_edge(scanline,x,e, x0,ya, x1,yb); nk_tt__handle_clipped_edge(scanline,x,e, x1,yb, x3,y3); } else if (x3 < x1 && x0 > x1) { /* two segments across x, down-left */ nk_tt__handle_clipped_edge(scanline,x,e, x0,ya, x1,yb); nk_tt__handle_clipped_edge(scanline,x,e, x1,yb, x3,y3); } else if (x0 < x2 && x3 > x2) { /* two segments across x+1, down-right */ nk_tt__handle_clipped_edge(scanline,x,e, x0,ya, x2,y2); nk_tt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); } else if (x3 < x2 && x0 > x2) { /* two segments across x+1, down-left */ nk_tt__handle_clipped_edge(scanline,x,e, x0,ya, x2,y2); nk_tt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); } else { /* one segment */ nk_tt__handle_clipped_edge(scanline,x,e, x0,ya, x3,y3); } } } } e = e->next; } } /* directly AA rasterize edges w/o supersampling */ NK_INTERN void nk_tt__rasterize_sorted_edges(struct nk_tt__bitmap *result, struct nk_tt__edge *e, int n, int vsubsample, int off_x, int off_y, struct nk_allocator *alloc) { struct nk_tt__hheap hh; struct nk_tt__active_edge *active = 0; int y,j=0, i; float scanline_data[129], *scanline, *scanline2; NK_UNUSED(vsubsample); nk_zero_struct(hh); hh.alloc = *alloc; if (result->w > 64) scanline = (float *) alloc->alloc(alloc->userdata,0, (nk_size)(result->w*2+1) * sizeof(float)); else scanline = scanline_data; scanline2 = scanline + result->w; y = off_y; e[n].y0 = (float) (off_y + result->h) + 1; while (j < result->h) { /* find center of pixel for this scanline */ float scan_y_top = (float)y + 0.0f; float scan_y_bottom = (float)y + 1.0f; struct nk_tt__active_edge **step = &active; NK_MEMSET(scanline , 0, (nk_size)result->w*sizeof(scanline[0])); NK_MEMSET(scanline2, 0, (nk_size)(result->w+1)*sizeof(scanline[0])); /* update all active edges; */ /* remove all active edges that terminate before the top of this scanline */ while (*step) { struct nk_tt__active_edge * z = *step; if (z->ey <= scan_y_top) { *step = z->next; /* delete from list */ NK_ASSERT(z->direction); z->direction = 0; nk_tt__hheap_free(&hh, z); } else { step = &((*step)->next); /* advance through list */ } } /* insert all edges that start before the bottom of this scanline */ while (e->y0 <= scan_y_bottom) { if (e->y0 != e->y1) { struct nk_tt__active_edge *z = nk_tt__new_active(&hh, e, off_x, scan_y_top); if (z != 0) { NK_ASSERT(z->ey >= scan_y_top); /* insert at front */ z->next = active; active = z; } } ++e; } /* now process all active edges */ if (active) nk_tt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top); { float sum = 0; for (i=0; i < result->w; ++i) { float k; int m; sum += scanline2[i]; k = scanline[i] + sum; k = (float) NK_ABS(k) * 255.0f + 0.5f; m = (int) k; if (m > 255) m = 255; result->pixels[j*result->stride + i] = (unsigned char) m; } } /* advance all the edges */ step = &active; while (*step) { struct nk_tt__active_edge *z = *step; z->fx += z->fdx; /* advance to position for current scanline */ step = &((*step)->next); /* advance through list */ } ++y; ++j; } nk_tt__hheap_cleanup(&hh); if (scanline != scanline_data) alloc->free(alloc->userdata, scanline); } #define NK_TT__COMPARE(a,b) ((a)->y0 < (b)->y0) NK_INTERN void nk_tt__sort_edges_ins_sort(struct nk_tt__edge *p, int n) { int i,j; for (i=1; i < n; ++i) { struct nk_tt__edge t = p[i], *a = &t; j = i; while (j > 0) { struct nk_tt__edge *b = &p[j-1]; int c = NK_TT__COMPARE(a,b); if (!c) break; p[j] = p[j-1]; --j; } if (i != j) p[j] = t; } } NK_INTERN void nk_tt__sort_edges_quicksort(struct nk_tt__edge *p, int n) { /* threshold for transitioning to insertion sort */ while (n > 12) { struct nk_tt__edge t; int c01,c12,c,m,i,j; /* compute median of three */ m = n >> 1; c01 = NK_TT__COMPARE(&p[0],&p[m]); c12 = NK_TT__COMPARE(&p[m],&p[n-1]); /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ if (c01 != c12) { /* otherwise, we'll need to swap something else to middle */ int z; c = NK_TT__COMPARE(&p[0],&p[n-1]); /* 0>mid && mid<n: 0>n => n; 0<n => 0 */ /* 0<mid && mid>n: 0>n => 0; 0<n => n */ z = (c == c12) ? 0 : n-1; t = p[z]; p[z] = p[m]; p[m] = t; } /* now p[m] is the median-of-three */ /* swap it to the beginning so it won't move around */ t = p[0]; p[0] = p[m]; p[m] = t; /* partition loop */ i=1; j=n-1; for(;;) { /* handling of equality is crucial here */ /* for sentinels & efficiency with duplicates */ for (;;++i) { if (!NK_TT__COMPARE(&p[i], &p[0])) break; } for (;;--j) { if (!NK_TT__COMPARE(&p[0], &p[j])) break; } /* make sure we haven't crossed */ if (i >= j) break; t = p[i]; p[i] = p[j]; p[j] = t; ++i; --j; } /* recurse on smaller side, iterate on larger */ if (j < (n-i)) { nk_tt__sort_edges_quicksort(p,j); p = p+i; n = n-i; } else { nk_tt__sort_edges_quicksort(p+i, n-i); n = j; } } } NK_INTERN void nk_tt__sort_edges(struct nk_tt__edge *p, int n) { nk_tt__sort_edges_quicksort(p, n); nk_tt__sort_edges_ins_sort(p, n); } NK_INTERN void nk_tt__rasterize(struct nk_tt__bitmap *result, struct nk_tt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, struct nk_allocator *alloc) { float y_scale_inv = invert ? -scale_y : scale_y; struct nk_tt__edge *e; int n,i,j,k,m; int vsubsample = 1; /* vsubsample should divide 255 evenly; otherwise we won't reach full opacity */ /* now we have to blow out the windings into explicit edge lists */ n = 0; for (i=0; i < windings; ++i) n += wcount[i]; e = (struct nk_tt__edge*) alloc->alloc(alloc->userdata, 0,(sizeof(*e) * (nk_size)(n+1))); if (e == 0) return; n = 0; m=0; for (i=0; i < windings; ++i) { struct nk_tt__point *p = pts + m; m += wcount[i]; j = wcount[i]-1; for (k=0; k < wcount[i]; j=k++) { int a=k,b=j; /* skip the edge if horizontal */ if (p[j].y == p[k].y) continue; /* add edge from j to k to the list */ e[n].invert = 0; if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) { e[n].invert = 1; a=j,b=k; } e[n].x0 = p[a].x * scale_x + shift_x; e[n].y0 = (p[a].y * y_scale_inv + shift_y) * (float)vsubsample; e[n].x1 = p[b].x * scale_x + shift_x; e[n].y1 = (p[b].y * y_scale_inv + shift_y) * (float)vsubsample; ++n; } } /* now sort the edges by their highest point (should snap to integer, and then by x) */ /*STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); */ nk_tt__sort_edges(e, n); /* now, traverse the scanlines and find the intersections on each scanline, use xor winding rule */ nk_tt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, alloc); alloc->free(alloc->userdata, e); } NK_INTERN void nk_tt__add_point(struct nk_tt__point *points, int n, float x, float y) { if (!points) return; /* during first pass, it's unallocated */ points[n].x = x; points[n].y = y; } NK_INTERN int nk_tt__tesselate_curve(struct nk_tt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n) { /* tesselate until threshold p is happy... * @TODO warped to compensate for non-linear stretching */ /* midpoint */ float mx = (x0 + 2*x1 + x2)/4; float my = (y0 + 2*y1 + y2)/4; /* versus directly drawn line */ float dx = (x0+x2)/2 - mx; float dy = (y0+y2)/2 - my; if (n > 16) /* 65536 segments on one curve better be enough! */ return 1; /* half-pixel error allowed... need to be smaller if AA */ if (dx*dx+dy*dy > objspace_flatness_squared) { nk_tt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1); nk_tt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1); } else { nk_tt__add_point(points, *num_points,x2,y2); *num_points = *num_points+1; } return 1; } /* returns number of contours */ NK_INTERN struct nk_tt__point* nk_tt_FlattenCurves(struct nk_tt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, struct nk_allocator *alloc) { struct nk_tt__point *points=0; int num_points=0; float objspace_flatness_squared = objspace_flatness * objspace_flatness; int i; int n=0; int start=0; int pass; /* count how many "moves" there are to get the contour count */ for (i=0; i < num_verts; ++i) if (vertices[i].type == NK_TT_vmove) ++n; *num_contours = n; if (n == 0) return 0; *contour_lengths = (int *) alloc->alloc(alloc->userdata,0, (sizeof(**contour_lengths) * (nk_size)n)); if (*contour_lengths == 0) { *num_contours = 0; return 0; } /* make two passes through the points so we don't need to realloc */ for (pass=0; pass < 2; ++pass) { float x=0,y=0; if (pass == 1) { points = (struct nk_tt__point *) alloc->alloc(alloc->userdata,0, (nk_size)num_points * sizeof(points[0])); if (points == 0) goto error; } num_points = 0; n= -1; for (i=0; i < num_verts; ++i) { switch (vertices[i].type) { case NK_TT_vmove: /* start the next contour */ if (n >= 0) (*contour_lengths)[n] = num_points - start; ++n; start = num_points; x = vertices[i].x, y = vertices[i].y; nk_tt__add_point(points, num_points++, x,y); break; case NK_TT_vline: x = vertices[i].x, y = vertices[i].y; nk_tt__add_point(points, num_points++, x, y); break; case NK_TT_vcurve: nk_tt__tesselate_curve(points, &num_points, x,y, vertices[i].cx, vertices[i].cy, vertices[i].x, vertices[i].y, objspace_flatness_squared, 0); x = vertices[i].x, y = vertices[i].y; break; default: break; } } (*contour_lengths)[n] = num_points - start; } return points; error: alloc->free(alloc->userdata, points); alloc->free(alloc->userdata, *contour_lengths); *contour_lengths = 0; *num_contours = 0; return 0; } NK_INTERN void nk_tt_Rasterize(struct nk_tt__bitmap *result, float flatness_in_pixels, struct nk_tt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, struct nk_allocator *alloc) { float scale = scale_x > scale_y ? scale_y : scale_x; int winding_count, *winding_lengths; struct nk_tt__point *windings = nk_tt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, alloc); NK_ASSERT(alloc); if (windings) { nk_tt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, alloc); alloc->free(alloc->userdata, winding_lengths); alloc->free(alloc->userdata, windings); } } NK_INTERN void nk_tt_MakeGlyphBitmapSubpixel(const struct nk_tt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, struct nk_allocator *alloc) { int ix0,iy0; struct nk_tt_vertex *vertices; int num_verts = nk_tt_GetGlyphShape(info, alloc, glyph, &vertices); struct nk_tt__bitmap gbm; nk_tt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0); gbm.pixels = output; gbm.w = out_w; gbm.h = out_h; gbm.stride = out_stride; if (gbm.w && gbm.h) nk_tt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, alloc); alloc->free(alloc->userdata, vertices); } /*------------------------------------------------------------- * Bitmap baking * --------------------------------------------------------------*/ NK_INTERN int nk_tt_PackBegin(struct nk_tt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, struct nk_allocator *alloc) { int num_nodes = pw - padding; struct nk_rp_context *context = (struct nk_rp_context *) alloc->alloc(alloc->userdata,0, sizeof(*context)); struct nk_rp_node *nodes = (struct nk_rp_node*) alloc->alloc(alloc->userdata,0, (sizeof(*nodes ) * (nk_size)num_nodes)); if (context == 0 || nodes == 0) { if (context != 0) alloc->free(alloc->userdata, context); if (nodes != 0) alloc->free(alloc->userdata, nodes); return 0; } spc->width = pw; spc->height = ph; spc->pixels = pixels; spc->pack_info = context; spc->nodes = nodes; spc->padding = padding; spc->stride_in_bytes = (stride_in_bytes != 0) ? stride_in_bytes : pw; spc->h_oversample = 1; spc->v_oversample = 1; nk_rp_init_target(context, pw-padding, ph-padding, nodes, num_nodes); if (pixels) NK_MEMSET(pixels, 0, (nk_size)(pw*ph)); /* background of 0 around pixels */ return 1; } NK_INTERN void nk_tt_PackEnd(struct nk_tt_pack_context *spc, struct nk_allocator *alloc) { alloc->free(alloc->userdata, spc->nodes); alloc->free(alloc->userdata, spc->pack_info); } NK_INTERN void nk_tt_PackSetOversampling(struct nk_tt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample) { NK_ASSERT(h_oversample <= NK_TT_MAX_OVERSAMPLE); NK_ASSERT(v_oversample <= NK_TT_MAX_OVERSAMPLE); if (h_oversample <= NK_TT_MAX_OVERSAMPLE) spc->h_oversample = h_oversample; if (v_oversample <= NK_TT_MAX_OVERSAMPLE) spc->v_oversample = v_oversample; } NK_INTERN void nk_tt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, int kernel_width) { unsigned char buffer[NK_TT_MAX_OVERSAMPLE]; int safe_w = w - kernel_width; int j; for (j=0; j < h; ++j) { int i; unsigned int total; NK_MEMSET(buffer, 0, (nk_size)kernel_width); total = 0; /* make kernel_width a constant in common cases so compiler can optimize out the divide */ switch (kernel_width) { case 2: for (i=0; i <= safe_w; ++i) { total += (unsigned int)(pixels[i] - buffer[i & NK_TT__OVER_MASK]); buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / 2); } break; case 3: for (i=0; i <= safe_w; ++i) { total += (unsigned int)(pixels[i] - buffer[i & NK_TT__OVER_MASK]); buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / 3); } break; case 4: for (i=0; i <= safe_w; ++i) { total += (unsigned int)pixels[i] - buffer[i & NK_TT__OVER_MASK]; buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / 4); } break; case 5: for (i=0; i <= safe_w; ++i) { total += (unsigned int)(pixels[i] - buffer[i & NK_TT__OVER_MASK]); buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / 5); } break; default: for (i=0; i <= safe_w; ++i) { total += (unsigned int)(pixels[i] - buffer[i & NK_TT__OVER_MASK]); buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / (unsigned int)kernel_width); } break; } for (; i < w; ++i) { NK_ASSERT(pixels[i] == 0); total -= (unsigned int)(buffer[i & NK_TT__OVER_MASK]); pixels[i] = (unsigned char) (total / (unsigned int)kernel_width); } pixels += stride_in_bytes; } } NK_INTERN void nk_tt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, int kernel_width) { unsigned char buffer[NK_TT_MAX_OVERSAMPLE]; int safe_h = h - kernel_width; int j; for (j=0; j < w; ++j) { int i; unsigned int total; NK_MEMSET(buffer, 0, (nk_size)kernel_width); total = 0; /* make kernel_width a constant in common cases so compiler can optimize out the divide */ switch (kernel_width) { case 2: for (i=0; i <= safe_h; ++i) { total += (unsigned int)(pixels[i*stride_in_bytes] - buffer[i & NK_TT__OVER_MASK]); buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / 2); } break; case 3: for (i=0; i <= safe_h; ++i) { total += (unsigned int)(pixels[i*stride_in_bytes] - buffer[i & NK_TT__OVER_MASK]); buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / 3); } break; case 4: for (i=0; i <= safe_h; ++i) { total += (unsigned int)(pixels[i*stride_in_bytes] - buffer[i & NK_TT__OVER_MASK]); buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / 4); } break; case 5: for (i=0; i <= safe_h; ++i) { total += (unsigned int)(pixels[i*stride_in_bytes] - buffer[i & NK_TT__OVER_MASK]); buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / 5); } break; default: for (i=0; i <= safe_h; ++i) { total += (unsigned int)(pixels[i*stride_in_bytes] - buffer[i & NK_TT__OVER_MASK]); buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / (unsigned int)kernel_width); } break; } for (; i < h; ++i) { NK_ASSERT(pixels[i*stride_in_bytes] == 0); total -= (unsigned int)(buffer[i & NK_TT__OVER_MASK]); pixels[i*stride_in_bytes] = (unsigned char) (total / (unsigned int)kernel_width); } pixels += 1; } } NK_INTERN float nk_tt__oversample_shift(int oversample) { if (!oversample) return 0.0f; /* The prefilter is a box filter of width "oversample", */ /* which shifts phase by (oversample - 1)/2 pixels in */ /* oversampled space. We want to shift in the opposite */ /* direction to counter this. */ return (float)-(oversample - 1) / (2.0f * (float)oversample); } /* rects array must be big enough to accommodate all characters in the given ranges */ NK_INTERN int nk_tt_PackFontRangesGatherRects(struct nk_tt_pack_context *spc, struct nk_tt_fontinfo *info, struct nk_tt_pack_range *ranges, int num_ranges, struct nk_rp_rect *rects) { int i,j,k; k = 0; for (i=0; i < num_ranges; ++i) { float fh = ranges[i].font_size; float scale = (fh > 0) ? nk_tt_ScaleForPixelHeight(info, fh): nk_tt_ScaleForMappingEmToPixels(info, -fh); ranges[i].h_oversample = (unsigned char) spc->h_oversample; ranges[i].v_oversample = (unsigned char) spc->v_oversample; for (j=0; j < ranges[i].num_chars; ++j) { int x0,y0,x1,y1; int codepoint = ranges[i].first_unicode_codepoint_in_range ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; int glyph = nk_tt_FindGlyphIndex(info, codepoint); nk_tt_GetGlyphBitmapBoxSubpixel(info,glyph, scale * (float)spc->h_oversample, scale * (float)spc->v_oversample, 0,0, &x0,&y0,&x1,&y1); rects[k].w = (nk_rp_coord) (x1-x0 + spc->padding + (int)spc->h_oversample-1); rects[k].h = (nk_rp_coord) (y1-y0 + spc->padding + (int)spc->v_oversample-1); ++k; } } return k; } NK_INTERN int nk_tt_PackFontRangesRenderIntoRects(struct nk_tt_pack_context *spc, struct nk_tt_fontinfo *info, struct nk_tt_pack_range *ranges, int num_ranges, struct nk_rp_rect *rects, struct nk_allocator *alloc) { int i,j,k, return_value = 1; /* save current values */ int old_h_over = (int)spc->h_oversample; int old_v_over = (int)spc->v_oversample; /* rects array must be big enough to accommodate all characters in the given ranges */ k = 0; for (i=0; i < num_ranges; ++i) { float fh = ranges[i].font_size; float recip_h,recip_v,sub_x,sub_y; float scale = fh > 0 ? nk_tt_ScaleForPixelHeight(info, fh): nk_tt_ScaleForMappingEmToPixels(info, -fh); spc->h_oversample = ranges[i].h_oversample; spc->v_oversample = ranges[i].v_oversample; recip_h = 1.0f / (float)spc->h_oversample; recip_v = 1.0f / (float)spc->v_oversample; sub_x = nk_tt__oversample_shift((int)spc->h_oversample); sub_y = nk_tt__oversample_shift((int)spc->v_oversample); for (j=0; j < ranges[i].num_chars; ++j) { struct nk_rp_rect *r = &rects[k]; if (r->was_packed) { struct nk_tt_packedchar *bc = &ranges[i].chardata_for_range[j]; int advance, lsb, x0,y0,x1,y1; int codepoint = ranges[i].first_unicode_codepoint_in_range ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; int glyph = nk_tt_FindGlyphIndex(info, codepoint); nk_rp_coord pad = (nk_rp_coord) spc->padding; /* pad on left and top */ r->x = (nk_rp_coord)((int)r->x + (int)pad); r->y = (nk_rp_coord)((int)r->y + (int)pad); r->w = (nk_rp_coord)((int)r->w - (int)pad); r->h = (nk_rp_coord)((int)r->h - (int)pad); nk_tt_GetGlyphHMetrics(info, glyph, &advance, &lsb); nk_tt_GetGlyphBitmapBox(info, glyph, scale * (float)spc->h_oversample, (scale * (float)spc->v_oversample), &x0,&y0,&x1,&y1); nk_tt_MakeGlyphBitmapSubpixel(info, spc->pixels + r->x + r->y*spc->stride_in_bytes, (int)(r->w - spc->h_oversample+1), (int)(r->h - spc->v_oversample+1), spc->stride_in_bytes, scale * (float)spc->h_oversample, scale * (float)spc->v_oversample, 0,0, glyph, alloc); if (spc->h_oversample > 1) nk_tt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, r->w, r->h, spc->stride_in_bytes, (int)spc->h_oversample); if (spc->v_oversample > 1) nk_tt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, r->w, r->h, spc->stride_in_bytes, (int)spc->v_oversample); bc->x0 = (nk_ushort) r->x; bc->y0 = (nk_ushort) r->y; bc->x1 = (nk_ushort) (r->x + r->w); bc->y1 = (nk_ushort) (r->y + r->h); bc->xadvance = scale * (float)advance; bc->xoff = (float) x0 * recip_h + sub_x; bc->yoff = (float) y0 * recip_v + sub_y; bc->xoff2 = ((float)x0 + r->w) * recip_h + sub_x; bc->yoff2 = ((float)y0 + r->h) * recip_v + sub_y; } else { return_value = 0; /* if any fail, report failure */ } ++k; } } /* restore original values */ spc->h_oversample = (unsigned int)old_h_over; spc->v_oversample = (unsigned int)old_v_over; return return_value; } NK_INTERN void nk_tt_GetPackedQuad(struct nk_tt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, struct nk_tt_aligned_quad *q, int align_to_integer) { float ipw = 1.0f / (float)pw, iph = 1.0f / (float)ph; struct nk_tt_packedchar *b = (struct nk_tt_packedchar*)(chardata + char_index); if (align_to_integer) { int tx = nk_ifloorf((*xpos + b->xoff) + 0.5f); int ty = nk_ifloorf((*ypos + b->yoff) + 0.5f); float x = (float)tx; float y = (float)ty; q->x0 = x; q->y0 = y; q->x1 = x + b->xoff2 - b->xoff; q->y1 = y + b->yoff2 - b->yoff; } else { q->x0 = *xpos + b->xoff; q->y0 = *ypos + b->yoff; q->x1 = *xpos + b->xoff2; q->y1 = *ypos + b->yoff2; } q->s0 = b->x0 * ipw; q->t0 = b->y0 * iph; q->s1 = b->x1 * ipw; q->t1 = b->y1 * iph; *xpos += b->xadvance; } /* ------------------------------------------------------------- * * FONT BAKING * * --------------------------------------------------------------*/ struct nk_font_bake_data { struct nk_tt_fontinfo info; struct nk_rp_rect *rects; struct nk_tt_pack_range *ranges; nk_rune range_count; }; struct nk_font_baker { struct nk_allocator alloc; struct nk_tt_pack_context spc; struct nk_font_bake_data *build; struct nk_tt_packedchar *packed_chars; struct nk_rp_rect *rects; struct nk_tt_pack_range *ranges; }; NK_GLOBAL const nk_size nk_rect_align = NK_ALIGNOF(struct nk_rp_rect); NK_GLOBAL const nk_size nk_range_align = NK_ALIGNOF(struct nk_tt_pack_range); NK_GLOBAL const nk_size nk_char_align = NK_ALIGNOF(struct nk_tt_packedchar); NK_GLOBAL const nk_size nk_build_align = NK_ALIGNOF(struct nk_font_bake_data); NK_GLOBAL const nk_size nk_baker_align = NK_ALIGNOF(struct nk_font_baker); NK_INTERN int nk_range_count(const nk_rune *range) { const nk_rune *iter = range; NK_ASSERT(range); if (!range) return 0; while (*(iter++) != 0); return (iter == range) ? 0 : (int)((iter - range)/2); } NK_INTERN int nk_range_glyph_count(const nk_rune *range, int count) { int i = 0; int total_glyphs = 0; for (i = 0; i < count; ++i) { int diff; nk_rune f = range[(i*2)+0]; nk_rune t = range[(i*2)+1]; NK_ASSERT(t >= f); diff = (int)((t - f) + 1); total_glyphs += diff; } return total_glyphs; } NK_API const nk_rune* nk_font_default_glyph_ranges(void) { NK_STORAGE const nk_rune ranges[] = {0x0020, 0x00FF, 0}; return ranges; } NK_API const nk_rune* nk_font_chinese_glyph_ranges(void) { NK_STORAGE const nk_rune ranges[] = { 0x0020, 0x00FF, 0x3000, 0x30FF, 0x31F0, 0x31FF, 0xFF00, 0xFFEF, 0x4e00, 0x9FAF, 0 }; return ranges; } NK_API const nk_rune* nk_font_cyrillic_glyph_ranges(void) { NK_STORAGE const nk_rune ranges[] = { 0x0020, 0x00FF, 0x0400, 0x052F, 0x2DE0, 0x2DFF, 0xA640, 0xA69F, 0 }; return ranges; } NK_API const nk_rune* nk_font_korean_glyph_ranges(void) { NK_STORAGE const nk_rune ranges[] = { 0x0020, 0x00FF, 0x3131, 0x3163, 0xAC00, 0xD79D, 0 }; return ranges; } NK_INTERN void nk_font_baker_memory(nk_size *temp, int *glyph_count, struct nk_font_config *config_list, int count) { int range_count = 0; int total_range_count = 0; struct nk_font_config *iter; NK_ASSERT(config_list); NK_ASSERT(glyph_count); if (!config_list) { *temp = 0; *glyph_count = 0; return; } *glyph_count = 0; if (!config_list->range) config_list->range = nk_font_default_glyph_ranges(); for (iter = config_list; iter; iter = iter->next) { range_count = nk_range_count(iter->range); total_range_count += range_count; *glyph_count += nk_range_glyph_count(iter->range, range_count); } *temp = (nk_size)*glyph_count * sizeof(struct nk_rp_rect); *temp += (nk_size)total_range_count * sizeof(struct nk_tt_pack_range); *temp += (nk_size)*glyph_count * sizeof(struct nk_tt_packedchar); *temp += (nk_size)count * sizeof(struct nk_font_bake_data); *temp += sizeof(struct nk_font_baker); *temp += nk_rect_align + nk_range_align + nk_char_align; *temp += nk_build_align + nk_baker_align; } NK_INTERN struct nk_font_baker* nk_font_baker(void *memory, int glyph_count, int count, struct nk_allocator *alloc) { struct nk_font_baker *baker; if (!memory) return 0; /* setup baker inside a memory block */ baker = (struct nk_font_baker*)NK_ALIGN_PTR(memory, nk_baker_align); baker->build = (struct nk_font_bake_data*)NK_ALIGN_PTR((baker + 1), nk_build_align); baker->packed_chars = (struct nk_tt_packedchar*)NK_ALIGN_PTR((baker->build + count), nk_char_align); baker->rects = (struct nk_rp_rect*)NK_ALIGN_PTR((baker->packed_chars + glyph_count), nk_rect_align); baker->ranges = (struct nk_tt_pack_range*)NK_ALIGN_PTR((baker->rects + glyph_count), nk_range_align); baker->alloc = *alloc; return baker; } NK_INTERN int nk_font_bake_pack(struct nk_font_baker *baker, nk_size *image_memory, int *width, int *height, struct nk_recti *custom, const struct nk_font_config *config_list, int count, struct nk_allocator *alloc) { NK_STORAGE const nk_size max_height = 1024 * 32; const struct nk_font_config *config_iter; int total_glyph_count = 0; int total_range_count = 0; int range_count = 0; int i = 0; NK_ASSERT(image_memory); NK_ASSERT(width); NK_ASSERT(height); NK_ASSERT(config_list); NK_ASSERT(count); NK_ASSERT(alloc); if (!image_memory || !width || !height || !config_list || !count) return nk_false; for (config_iter = config_list; config_iter; config_iter = config_iter->next) { range_count = nk_range_count(config_iter->range); total_range_count += range_count; total_glyph_count += nk_range_glyph_count(config_iter->range, range_count); } /* setup font baker from temporary memory */ for (config_iter = config_list; config_iter; config_iter = config_iter->next) { const struct nk_font_config *cfg = config_iter; if (!nk_tt_InitFont(&baker->build[i++].info, (const unsigned char*)cfg->ttf_blob, 0)) return nk_false; } *height = 0; *width = (total_glyph_count > 1000) ? 1024 : 512; nk_tt_PackBegin(&baker->spc, 0, (int)*width, (int)max_height, 0, 1, alloc); { int input_i = 0; int range_n = 0; int rect_n = 0; int char_n = 0; /* pack custom user data first so it will be in the upper left corner*/ if (custom) { struct nk_rp_rect custom_space; nk_zero(&custom_space, sizeof(custom_space)); custom_space.w = (nk_rp_coord)((custom->w * 2) + 1); custom_space.h = (nk_rp_coord)(custom->h + 1); nk_tt_PackSetOversampling(&baker->spc, 1, 1); nk_rp_pack_rects((struct nk_rp_context*)baker->spc.pack_info, &custom_space, 1); *height = NK_MAX(*height, (int)(custom_space.y + custom_space.h)); custom->x = (short)custom_space.x; custom->y = (short)custom_space.y; custom->w = (short)custom_space.w; custom->h = (short)custom_space.h; } /* first font pass: pack all glyphs */ for (input_i = 0, config_iter = config_list; input_i < count && config_iter; input_i++, config_iter = config_iter->next) { int n = 0; int glyph_count; const nk_rune *in_range; const struct nk_font_config *cfg = config_iter; struct nk_font_bake_data *tmp = &baker->build[input_i]; /* count glyphs + ranges in current font */ glyph_count = 0; range_count = 0; for (in_range = cfg->range; in_range[0] && in_range[1]; in_range += 2) { glyph_count += (int)(in_range[1] - in_range[0]) + 1; range_count++; } /* setup ranges */ tmp->ranges = baker->ranges + range_n; tmp->range_count = (nk_rune)range_count; range_n += range_count; for (i = 0; i < range_count; ++i) { in_range = &cfg->range[i * 2]; tmp->ranges[i].font_size = cfg->size; tmp->ranges[i].first_unicode_codepoint_in_range = (int)in_range[0]; tmp->ranges[i].num_chars = (int)(in_range[1]- in_range[0]) + 1; tmp->ranges[i].chardata_for_range = baker->packed_chars + char_n; char_n += tmp->ranges[i].num_chars; } /* pack */ tmp->rects = baker->rects + rect_n; rect_n += glyph_count; nk_tt_PackSetOversampling(&baker->spc, cfg->oversample_h, cfg->oversample_v); n = nk_tt_PackFontRangesGatherRects(&baker->spc, &tmp->info, tmp->ranges, (int)tmp->range_count, tmp->rects); nk_rp_pack_rects((struct nk_rp_context*)baker->spc.pack_info, tmp->rects, (int)n); /* texture height */ for (i = 0; i < n; ++i) { if (tmp->rects[i].was_packed) *height = NK_MAX(*height, tmp->rects[i].y + tmp->rects[i].h); } } NK_ASSERT(rect_n == total_glyph_count); NK_ASSERT(char_n == total_glyph_count); NK_ASSERT(range_n == total_range_count); } *height = (int)nk_round_up_pow2((nk_uint)*height); *image_memory = (nk_size)(*width) * (nk_size)(*height); return nk_true; } NK_INTERN void nk_font_bake(struct nk_font_baker *baker, void *image_memory, int width, int height, struct nk_font_glyph *glyphs, int glyphs_count, const struct nk_font_config *config_list, int font_count) { int input_i = 0; nk_rune glyph_n = 0; const struct nk_font_config *config_iter; NK_ASSERT(image_memory); NK_ASSERT(width); NK_ASSERT(height); NK_ASSERT(config_list); NK_ASSERT(baker); NK_ASSERT(font_count); NK_ASSERT(glyphs_count); if (!image_memory || !width || !height || !config_list || !font_count || !glyphs || !glyphs_count) return; /* second font pass: render glyphs */ nk_zero(image_memory, (nk_size)((nk_size)width * (nk_size)height)); baker->spc.pixels = (unsigned char*)image_memory; baker->spc.height = (int)height; for (input_i = 0, config_iter = config_list; input_i < font_count && config_iter; ++input_i, config_iter = config_iter->next) { const struct nk_font_config *cfg = config_iter; struct nk_font_bake_data *tmp = &baker->build[input_i]; nk_tt_PackSetOversampling(&baker->spc, cfg->oversample_h, cfg->oversample_v); nk_tt_PackFontRangesRenderIntoRects(&baker->spc, &tmp->info, tmp->ranges, (int)tmp->range_count, tmp->rects, &baker->alloc); } nk_tt_PackEnd(&baker->spc, &baker->alloc); /* third pass: setup font and glyphs */ for (input_i = 0, config_iter = config_list; input_i < font_count && config_iter; ++input_i, config_iter = config_iter->next) { nk_size i = 0; int char_idx = 0; nk_rune glyph_count = 0; const struct nk_font_config *cfg = config_iter; struct nk_font_bake_data *tmp = &baker->build[input_i]; struct nk_baked_font *dst_font = cfg->font; float font_scale = nk_tt_ScaleForPixelHeight(&tmp->info, cfg->size); int unscaled_ascent, unscaled_descent, unscaled_line_gap; nk_tt_GetFontVMetrics(&tmp->info, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); /* fill baked font */ if (!cfg->merge_mode) { dst_font->ranges = cfg->range; dst_font->height = cfg->size; dst_font->ascent = ((float)unscaled_ascent * font_scale); dst_font->descent = ((float)unscaled_descent * font_scale); dst_font->glyph_offset = glyph_n; } /* fill own baked font glyph array */ for (i = 0; i < tmp->range_count; ++i) { struct nk_tt_pack_range *range = &tmp->ranges[i]; for (char_idx = 0; char_idx < range->num_chars; char_idx++) { nk_rune codepoint = 0; float dummy_x = 0, dummy_y = 0; struct nk_tt_aligned_quad q; struct nk_font_glyph *glyph; /* query glyph bounds from stb_truetype */ const struct nk_tt_packedchar *pc = &range->chardata_for_range[char_idx]; if (!pc->x0 && !pc->x1 && !pc->y0 && !pc->y1) continue; codepoint = (nk_rune)(range->first_unicode_codepoint_in_range + char_idx); nk_tt_GetPackedQuad(range->chardata_for_range, (int)width, (int)height, char_idx, &dummy_x, &dummy_y, &q, 0); /* fill own glyph type with data */ glyph = &glyphs[dst_font->glyph_offset + (unsigned int)glyph_count]; glyph->codepoint = codepoint; glyph->x0 = q.x0; glyph->y0 = q.y0; glyph->x1 = q.x1; glyph->y1 = q.y1; glyph->y0 += (dst_font->ascent + 0.5f); glyph->y1 += (dst_font->ascent + 0.5f); glyph->w = glyph->x1 - glyph->x0 + 0.5f; glyph->h = glyph->y1 - glyph->y0; if (cfg->coord_type == NK_COORD_PIXEL) { glyph->u0 = q.s0 * (float)width; glyph->v0 = q.t0 * (float)height; glyph->u1 = q.s1 * (float)width; glyph->v1 = q.t1 * (float)height; } else { glyph->u0 = q.s0; glyph->v0 = q.t0; glyph->u1 = q.s1; glyph->v1 = q.t1; } glyph->xadvance = (pc->xadvance + cfg->spacing.x); if (cfg->pixel_snap) glyph->xadvance = (float)(int)(glyph->xadvance + 0.5f); glyph_count++; } } dst_font->glyph_count = glyph_count; glyph_n += dst_font->glyph_count; } } NK_INTERN void nk_font_bake_custom_data(void *img_memory, int img_width, int img_height, struct nk_recti img_dst, const char *texture_data_mask, int tex_width, int tex_height, char white, char black) { nk_byte *pixels; int y = 0; int x = 0; int n = 0; NK_ASSERT(img_memory); NK_ASSERT(img_width); NK_ASSERT(img_height); NK_ASSERT(texture_data_mask); NK_UNUSED(tex_height); if (!img_memory || !img_width || !img_height || !texture_data_mask) return; pixels = (nk_byte*)img_memory; for (y = 0, n = 0; y < tex_height; ++y) { for (x = 0; x < tex_width; ++x, ++n) { const int off0 = ((img_dst.x + x) + (img_dst.y + y) * img_width); const int off1 = off0 + 1 + tex_width; pixels[off0] = (texture_data_mask[n] == white) ? 0xFF : 0x00; pixels[off1] = (texture_data_mask[n] == black) ? 0xFF : 0x00; } } } NK_INTERN void nk_font_bake_convert(void *out_memory, int img_width, int img_height, const void *in_memory) { int n = 0; const nk_byte *src; nk_rune *dst; NK_ASSERT(out_memory); NK_ASSERT(in_memory); NK_ASSERT(img_width); NK_ASSERT(img_height); if (!out_memory || !in_memory || !img_height || !img_width) return; dst = (nk_rune*)out_memory; src = (const nk_byte*)in_memory; for (n = (int)(img_width * img_height); n > 0; n--) *dst++ = ((nk_rune)(*src++) << 24) | 0x00FFFFFF; } /* ------------------------------------------------------------- * * FONT * * --------------------------------------------------------------*/ NK_INTERN float nk_font_text_width(nk_handle handle, float height, const char *text, int len) { nk_rune unicode; int text_len = 0; float text_width = 0; int glyph_len = 0; float scale = 0; struct nk_font *font = (struct nk_font*)handle.ptr; NK_ASSERT(font); NK_ASSERT(font->glyphs); if (!font || !text || !len) return 0; scale = height/font->info.height; glyph_len = text_len = nk_utf_decode(text, &unicode, (int)len); if (!glyph_len) return 0; while (text_len <= (int)len && glyph_len) { const struct nk_font_glyph *g; if (unicode == NK_UTF_INVALID) break; /* query currently drawn glyph information */ g = nk_font_find_glyph(font, unicode); text_width += g->xadvance * scale; /* offset next glyph */ glyph_len = nk_utf_decode(text + text_len, &unicode, (int)len - text_len); text_len += glyph_len; } return text_width; } #ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT NK_INTERN void nk_font_query_font_glyph(nk_handle handle, float height, struct nk_user_font_glyph *glyph, nk_rune codepoint, nk_rune next_codepoint) { float scale; const struct nk_font_glyph *g; struct nk_font *font; NK_ASSERT(glyph); NK_UNUSED(next_codepoint); font = (struct nk_font*)handle.ptr; NK_ASSERT(font); NK_ASSERT(font->glyphs); if (!font || !glyph) return; scale = height/font->info.height; g = nk_font_find_glyph(font, codepoint); glyph->width = (g->x1 - g->x0) * scale; glyph->height = (g->y1 - g->y0) * scale; glyph->offset = nk_vec2(g->x0 * scale, g->y0 * scale); glyph->xadvance = (g->xadvance * scale); glyph->uv[0] = nk_vec2(g->u0, g->v0); glyph->uv[1] = nk_vec2(g->u1, g->v1); } #endif NK_API const struct nk_font_glyph* nk_font_find_glyph(struct nk_font *font, nk_rune unicode) { int i = 0; int count; int total_glyphs = 0; const struct nk_font_glyph *glyph = 0; NK_ASSERT(font); NK_ASSERT(font->glyphs); glyph = font->fallback; count = nk_range_count(font->info.ranges); for (i = 0; i < count; ++i) { int diff; nk_rune f = font->info.ranges[(i*2)+0]; nk_rune t = font->info.ranges[(i*2)+1]; diff = (int)((t - f) + 1); if (unicode >= f && unicode <= t) return &font->glyphs[((nk_rune)total_glyphs + (unicode - f))]; total_glyphs += diff; } return glyph; } NK_INTERN void nk_font_init(struct nk_font *font, float pixel_height, nk_rune fallback_codepoint, struct nk_font_glyph *glyphs, const struct nk_baked_font *baked_font, nk_handle atlas) { struct nk_baked_font baked; NK_ASSERT(font); NK_ASSERT(glyphs); NK_ASSERT(baked_font); if (!font || !glyphs || !baked_font) return; baked = *baked_font; font->info = baked; font->scale = (float)pixel_height / (float)font->info.height; font->glyphs = &glyphs[baked_font->glyph_offset]; font->texture = atlas; font->fallback_codepoint = fallback_codepoint; font->fallback = nk_font_find_glyph(font, fallback_codepoint); font->handle.height = font->info.height * font->scale; font->handle.width = nk_font_text_width; font->handle.userdata.ptr = font; #ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT font->handle.query = nk_font_query_font_glyph; font->handle.texture = font->texture; #endif } /* --------------------------------------------------------------------------- * * DEFAULT FONT * * ProggyClean.ttf * Copyright (c) 2004, 2005 Tristan Grimmer * MIT license (see License.txt in http://www.upperbounds.net/download/ProggyClean.ttf.zip) * Download and more information at http://upperbounds.net *-----------------------------------------------------------------------------*/ #ifdef NK_INCLUDE_DEFAULT_FONT #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Woverlength-strings" #elif defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Woverlength-strings" #endif NK_GLOBAL const char nk_proggy_clean_ttf_compressed_data_base85[11980+1] = "7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/" "2*>]b(MC;$jPfY.;h^`IWM9<Lh2TlS+f-s$o6Q<BWH`YiU.xfLq$N;$0iR/GX:U(jcW2p/W*q?-qmnUCI;jHSAiFWM.R*kU@C=GH?a9wp8f$e.-4^Qg1)Q-GL(lf(r/7GrRgwV%MS=C#" "`8ND>Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1<q-UE31#^-V'8IRUo7Qf./L>=Ke$$'5F%)]0^#0X@U.a<r:QLtFsLcL6##lOj)#.Y5<-R&KgLwqJfLgN&;Q?gI^#DY2uL" "i@^rMl9t=cWq6##weg>$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#W@lK.N'[0#7RL_&#w+F%HtG9M#XL`N&.,GM4Pg;-<nLENhvx>-VsM.M0rJfLH2eTM`*oJMHRC`N" "kfimM2J,W-jXS:)r0wK#@Fge$U>`w'N7G#$#fB#$E^$#:9:hk+eOe--6x)F7*E%?76%^GMHePW-Z5l'&GiF#$956:rS?dA#fiK:)Yr+`&#0j@'DbG&#^$PG.Ll+DNa<XCMKEV*N)LN/N" "*b=%Q6pia-Xg8I$<MR&,VdJe$<(7G;Ckl'&hF;;$<_=X(b.RS%%)###MPBuuE1V:v&cX&#2m#(&cV]`k9OhLMbn%s$G2,B$BfD3X*sp5#l,$R#]x_X1xKX%b5U*[r5iMfUo9U`N99hG)" "tm+/Us9pG)XPu`<0s-)WTt(gCRxIg(%6sfh=ktMKn3j)<6<b5Sk_/0(^]AaN#(p/L>&VZ>1i%h1S9u5o@YaaW$e+b<TWFn/Z:Oh(Cx2$lNEoN^e)#CFY@@I;BOQ*sRwZtZxRcU7uW6CX" "ow0i(?$Q[cjOd[P4d)]>ROPOpxTO7Stwi1::iB1q)C_=dV26J;2,]7op$]uQr@_V7$q^%lQwtuHY]=DX,n3L#0PHDO4f9>dC@O>HBuKPpP*E,N+b3L#lpR/MrTEH.IAQk.a>D[.e;mc." "x]Ip.PH^'/aqUO/$1WxLoW0[iLA<QT;5HKD+@qQ'NQ(3_PLhE48R.qAPSwQ0/WK?Z,[x?-J;jQTWA0X@KJ(_Y8N-:/M74:/-ZpKrUss?d#dZq]DAbkU*JqkL+nwX@@47`5>w=4h(9.`G" "CRUxHPeR`5Mjol(dUWxZa(>STrPkrJiWx`5U7F#.g*jrohGg`cg:lSTvEY/EV_7H4Q9[Z%cnv;JQYZ5q.l7Zeas:HOIZOB?G<Nald$qs]@]L<J7bR*>gv:[7MI2k).'2($5FNP&EQ(,)" "U]W]+fh18.vsai00);D3@4ku5P?DP8aJt+;qUM]=+b'8@;mViBKx0DE[-auGl8:PJ&Dj+M6OC]O^((##]`0i)drT;-7X`=-H3[igUnPG-NZlo.#k@h#=Ork$m>a>$-?Tm$UV(?#P6YY#" "'/###xe7q.73rI3*pP/$1>s9)W,JrM7SN]'/4C#v$U`0#V.[0>xQsH$fEmPMgY2u7Kh(G%siIfLSoS+MK2eTM$=5,M8p`A.;_R%#u[K#$x4AG8.kK/HSB==-'Ie/QTtG?-.*^N-4B/ZM" "_3YlQC7(p7q)&](`6_c)$/*JL(L-^(]$wIM`dPtOdGA,U3:w2M-0<q-]L_?^)1vw'.,MRsqVr.L;aN&#/EgJ)PBc[-f>+WomX2u7lqM2iEumMTcsF?-aT=Z-97UEnXglEn1K-bnEO`gu" "Ft(c%=;Am_Qs@jLooI&NX;]0#j4#F14;gl8-GQpgwhrq8'=l_f-b49'UOqkLu7-##oDY2L(te+Mch&gLYtJ,MEtJfLh'x'M=$CS-ZZ%P]8bZ>#S?YY#%Q&q'3^Fw&?D)UDNrocM3A76/" "/oL?#h7gl85[qW/NDOk%16ij;+:1a'iNIdb-ou8.P*w,v5#EI$TWS>Pot-R*H'-SEpA:g)f+O$%%`kA#G=8RMmG1&O`>to8bC]T&$,n.LoO>29sp3dt-52U%VM#q7'DHpg+#Z9%H[K<L" "%a2E-grWVM3@2=-k22tL]4$##6We'8UJCKE[d_=%wI;'6X-GsLX4j^SgJ$##R*w,vP3wK#iiW&#*h^D&R?jp7+/u&#(AP##XU8c$fSYW-J95_-Dp[g9wcO&#M-h1OcJlc-*vpw0xUX&#" "OQFKNX@QI'IoPp7nb,QU//MQ&ZDkKP)X<WSVL(68uVl&#c'[0#(s1X&xm$Y%B7*K:eDA323j998GXbA#pwMs-jgD$9QISB-A_(aN4xoFM^@C58D0+Q+q3n0#3U1InDjF682-SjMXJK)(" "h$hxua_K]ul92%'BOU&#BRRh-slg8KDlr:%L71Ka:.A;%YULjDPmL<LYs8i#XwJOYaKPKc1h:'9Ke,g)b),78=I39B;xiY$bgGw-&.Zi9InXDuYa%G*f2Bq7mn9^#p1vv%#(Wi-;/Z5h" "o;#2:;%d&#x9v68C5g?ntX0X)pT`;%pB3q7mgGN)3%(P8nTd5L7GeA-GL@+%J3u2:(Yf>et`e;)f#Km8&+DC$I46>#Kr]]u-[=99tts1.qb#q72g1WJO81q+eN'03'eM>&1XxY-caEnO" "j%2n8)),?ILR5^.Ibn<-X-Mq7[a82Lq:F&#ce+S9wsCK*x`569E8ew'He]h:sI[2LM$[guka3ZRd6:t%IG:;$%YiJ:Nq=?eAw;/:nnDq0(CYcMpG)qLN4$##&J<j$UpK<Q4a1]MupW^-" "sj_$%[HK%'F####QRZJ::Y3EGl4'@%FkiAOg#p[##O`gukTfBHagL<LHw%q&OV0##F=6/:chIm0@eCP8X]:kFI%hl8hgO@RcBhS-@Qb$%+m=hPDLg*%K8ln(wcf3/'DW-$.lR?n[nCH-" "eXOONTJlh:.RYF%3'p6sq:UIMA945&^HFS87@$EP2iG<-lCO$%c`uKGD3rC$x0BL8aFn--`ke%#HMP'vh1/R&O_J9'um,.<tx[@%wsJk&bUT2`0uMv7gg#qp/ij.L56'hl;.s5CUrxjO" "M7-##.l+Au'A&O:-T72L]P`&=;ctp'XScX*rU.>-XTt,%OVU4)S1+R-#dg0/Nn?Ku1^0f$B*P:Rowwm-`0PKjYDDM'3]d39VZHEl4,.j']Pk-M.h^&:0FACm$maq-&sgw0t7/6(^xtk%" "LuH88Fj-ekm>GA#_>568x6(OFRl-IZp`&b,_P'$M<Jnq79VsJW/mWS*PUiq76;]/NM_>hLbxfc$mj`,O;&%W2m`Zh:/)Uetw:aJ%]K9h:TcF]u_-Sj9,VK3M.*'&0D[Ca]J9gp8,kAW]" "%(?A%R$f<->Zts'^kn=-^@c4%-pY6qI%J%1IGxfLU9CP8cbPlXv);C=b),<2mOvP8up,UVf3839acAWAW-W?#ao/^#%KYo8fRULNd2.>%m]UK:n%r$'sw]J;5pAoO_#2mO3n,'=H5(et" "Hg*`+RLgv>=4U8guD$I%D:W>-r5V*%j*W:Kvej.Lp$<M-SGZ':+Q_k+uvOSLiEo(<aD/K<CCc`'Lx>'?;++O'>()jLR-^u68PHm8ZFWe+ej8h:9r6L*0//c&iH&R8pRbA#Kjm%upV1g:" "a_#Ur7FuA#(tRh#.Y5K+@?3<-8m0$PEn;J:rh6?I6uG<-`wMU'ircp0LaE_OtlMb&1#6T.#FDKu#1Lw%u%+GM+X'e?YLfjM[VO0MbuFp7;>Q&#WIo)0@F%q7c#4XAXN-U&VB<HFF*qL(" "$/V,;(kXZejWO`<[5??ewY(*9=%wDc;,u<'9t3W-(H1th3+G]ucQ]kLs7df($/*JL]@*t7Bu_G3_7mp7<iaQjO@.kLg;x3B0lqp7Hf,^Ze7-##@/c58Mo(3;knp0%)A7?-W+eI'o8)b<" "nKnw'Ho8C=Y>pqB>0ie&jhZ[?iLR@@_AvA-iQC(=ksRZRVp7`.=+NpBC%rh&3]R:8XDmE5^V8O(x<<aG/1N$#FX$0V5Y6x'aErI3I$7x%E`v<-BY,)%-?Psf*l?%C3.mM(=/M0:JxG'?" "7WhH%o'a<-80g0NBxoO(GH<dM]n.+%q@jH?f.UsJ2Ggs&4<-e47&Kl+f//9@`b+?.TeN_&B8Ss?v;^Trk;f#YvJkl&w$]>-+k?'(<S:68tq*WoDfZu';mM?8X[ma8W%*`-=;D.(nc7/;" ")g:T1=^J$&BRV(-lTmNB6xqB[@0*o.erM*<SWF]u2=st-*(6v>^](H.aREZSi,#1:[IXaZFOm<-ui#qUq2$##Ri;u75OK#(RtaW-K-F`S+cF]uN`-KMQ%rP/Xri.LRcB##=YL3BgM/3M" "D?@f&1'BW-)Ju<L25gl8uhVm1hL$##*8###'A3/LkKW+(^rWX?5W_8g)a(m&K8P>#bmmWCMkk&#TR`C,5d>g)F;t,4:@_l8G/5h4vUd%&%950:VXD'QdWoY-F$BtUwmfe$YqL'8(PWX(" "P?^@Po3$##`MSs?DWBZ/S>+4%>fX,VWv/w'KD`LP5IbH;rTV>n3cEK8U#bX]l-/V+^lj3;vlMb&[5YQ8#pekX9JP3XUC72L,,?+Ni&co7ApnO*5NK,((W-i:$,kp'UDAO(G0Sq7MVjJs" "bIu)'Z,*[>br5fX^:FPAWr-m2KgL<LUN098kTF&#lvo58=/vjDo;.;)Ka*hLR#/k=rKbxuV`>Q_nN6'8uTG&#1T5g)uLv:873UpTLgH+#FgpH'_o1780Ph8KmxQJ8#H72L4@768@Tm&Q" "h4CB/5OvmA&,Q&QbUoi$a_%3M01H)4x7I^&KQVgtFnV+;[Pc>[m4k//,]1?#`VY[Jr*3&&slRfLiVZJ:]?=K3Sw=[$=uRB?3xk48@aeg<Z'<$#4H)6,>e0jT6'N#(q%.O=?2S]u*(m<-" "V8J'(1)G][68hW$5'q[GC&5j`TE?m'esFGNRM)j,ffZ?-qx8;->g4t*:CIP/[Qap7/9'#(1sao7w-.qNUdkJ)tCF&#B^;xGvn2r9FEPFFFcL@.iFNkTve$m%#QvQS8U@)2Z+3K:AKM5i" "sZ88+dKQ)W6>J%CL<KE>`.d*(B`-n8D9oK<Up]c$X$(,)M8Zt7/[rdkqTgl-0cuGMv'?>-XV1q['-5k'cAZ69e;D_?$ZPP&s^+7])$*$#@QYi9,5P&#9r+$%CE=68>K8r0=dSC%%(@p7" ".m7jilQ02'0-VWAg<a/''3u.=4L$Y)6k/K:_[3=&jvL<L0C/2'v:^;-DIBW,B4E68:kZ;%?8(Q8BH=kO65BW?xSG&#@uU,DS*,?.+(o(#1vCS8#CHF>TlGW'b)Tq7VT9q^*^$$.:&N@@" "$&)WHtPm*5_rO0&e%K&#-30j(E4#'Zb.o/(Tpm$>K'f@[PvFl,hfINTNU6u'0pao7%XUp9]5.>%h`8_=VYbxuel.NTSsJfLacFu3B'lQSu/m6-Oqem8T+oE--$0a/k]uj9EwsG>%veR*" "hv^BFpQj:K'#SJ,sB-'#](j.Lg92rTw-*n%@/;39rrJF,l#qV%OrtBeC6/,;qB3ebNW[?,Hqj2L.1NP&GjUR=1D8QaS3Up&@*9wP?+lo7b?@%'k4`p0Z$22%K3+iCZj?XJN4Nm&+YF]u" "@-W$U%VEQ/,,>>#)D<h#`)h0:<Q6909ua+&VU%n2:cG3FJ-%@Bj-DgLr`Hw&HAKjKjseK</xKT*)B,N9X3]krc12t'pgTV(Lv-tL[xg_%=M_q7a^x?7Ubd>#%8cY#YZ?=,`Wdxu/ae&#" "w6)R89tI#6@s'(6Bf7a&?S=^ZI_kS&ai`&=tE72L_D,;^R)7[$s<Eh#c&)q.MXI%#v9ROa5FZO%sF7q7Nwb&#ptUJ:aqJe$Sl68%.D###EC><?-aF&#RNQv>o8lKN%5/$(vdfq7+ebA#" "u1p]ovUKW&Y%q]'>$1@-[xfn$7ZTp7mM,G,Ko7a&Gu%G[RMxJs[0MM%wci.LFDK)(<c`Q8N)jEIF*+?P2a8g%)$q]o2aH8C&<SibC/q,(e:v;-b#6[$NtDZ84Je2KNvB#$P5?tQ3nt(0" "d=j.LQf./Ll33+(;q3L-w=8dX$#WF&uIJ@-bfI>%:_i2B5CsR8&9Z&#=mPEnm0f`<&c)QL5uJ#%u%lJj+D-r;BoF&#4DoS97h5g)E#o:&S4weDF,9^Hoe`h*L+_a*NrLW-1pG_&2UdB8" "6e%B/:=>)N4xeW.*wft-;$'58-ESqr<b?UI(_%@[P46>#U`'6AQ]m&6/`Z>#S?YY#Vc;r7U2&326d=w&H####?TZ`*4?&.MK?LP8Vxg>$[QXc%QJv92.(Db*B)gb*BM9dM*hJMAo*c&#" "b0v=Pjer]$gG&JXDf->'StvU7505l9$AFvgYRI^&<^b68?j#q9QX4SM'RO#&sL1IM.rJfLUAj221]d##DW=m83u5;'bYx,*Sl0hL(W;;$doB&O/TQ:(Z^xBdLjL<Lni;''X.`$#8+1GD" ":k$YUWsbn8ogh6rxZ2Z9]%nd+>V#*8U_72Lh+2Q8Cj0i:6hp&$C/:p(HK>T8Y[gHQ4`4)'$Ab(Nof%V'8hL&#<NEdtg(n'=S1A(Q1/I&4([%dM`,Iu'1:_hL>SfD07&6D<fp8dHM7/g+" "tlPN9J*rKaPct&?'uBCem^jn%9_K)<,C5K3s=5g&GmJb*[SYq7K;TRLGCsM-$$;S%:Y@r7AK0pprpL<Lrh,q7e/%KWK:50I^+m'vi`3?%Zp+<-d+$L-Sv:@.o19n$s0&39;kn;S%BSq*" "$3WoJSCLweV[aZ'MQIjO<7;X-X;&+dMLvu#^UsGEC9WEc[X(wI7#2.(F0jV*eZf<-Qv3J-c+J5AlrB#$p(H68LvEA'q3n0#m,[`*8Ft)FcYgEud]CWfm68,(aLA$@EFTgLXoBq/UPlp7" ":d[/;r_ix=:TF`S5H-b<LI&HY(K=h#)]Lk$K14lVfm:x$H<3^Ql<M`$OhapBnkup'D#L$Pb_`N*g]2e;X/Dtg,bsj&K#2[-:iYr'_wgH)NUIR8a1n#S?Yej'h8^58UbZd+^FKD*T@;6A" "7aQC[K8d-(v6GI$x:T<&'Gp5Uf>@M.*J:;$-rv29'M]8qMv-tLp,'886iaC=Hb*YJoKJ,(j%K=H`K.v9HggqBIiZu'QvBT.#=)0ukruV&.)3=(^1`o*Pj4<-<aN((^7('#Z0wK#5GX@7" "u][`*S^43933A4rl][`*O4CgLEl]v$1Q3AeF37dbXk,.)vj#x'd`;qgbQR%FW,2(?LO=s%Sc68%NP'##Aotl8x=BE#j1UD([3$M(]UI2LX3RpKN@;/#f'f/&_mt&F)XdF<9t4)Qa.*kT" "LwQ'(TTB9.xH'>#MJ+gLq9-##@HuZPN0]u:h7.T..G:;$/Usj(T7`Q8tT72LnYl<-qx8;-HV7Q-&Xdx%1a,hC=0u+HlsV>nuIQL-5<N?)NBS)QN*_I,?&)2'IM%L3I)X((e/dl2&8'<M" ":^#M*Q+[T.Xri.LYS3v%fF`68h;b-X[/En'CR.q7E)p'/kle2HM,u;^%OKC-N+Ll%F9CF<Nf'^#t2L,;27W:0O@6##U6W7:$rJfLWHj$#)woqBefIZ.PK<b*t7ed;p*_m;4ExK#h@&]>" "_>@kXQtMacfD.m-VAb8;IReM3$wf0''hra*so568'Ip&vRs849'MRYSp%:t:h5qSgwpEr$B>Q,;s(C#$)`svQuF$##-D,##,g68@2[T;.XSdN9Qe)rpt._K-#5wF)sP'##p#C0c%-Gb%" "hd+<-j'Ai*x&&HMkT]C'OSl##5RG[JXaHN;d'uA#x._U;.`PU@(Z3dt4r152@:v,'R.Sj'w#0<-;kPI)FfJ&#AYJ&#//)>-k=m=*XnK$>=)72L]0I%>.G690a:$##<,);?;72#?x9+d;" "^V'9;jY@;)br#q^YQpx:X#Te$Z^'=-=bGhLf:D6&bNwZ9-ZD#n^9HhLMr5G;']d&6'wYmTFmL<LD)F^%[tC'8;+9E#C$g%#5Y>q9wI>P(9mI[>kC-ekLC/R&CH+s'B;K-M6$EB%is00:" "+A4[7xks.LrNk0&E)wILYF@2L'0Nb$+pv<(2.768/FrY&h$^3i&@+G%JT'<-,v`3;_)I9M^AE]CN?Cl2AZg+%4iTpT3<n-&%H%b<FDj2M<hH=&Eh<2Len$b*aTX=-8QxN)k11IM1c^j%" "9s<L<NFSo)B?+<-(GxsF,^-Eh@$4dXhN$+#rxK8'je'D7k`e;)2pYwPA'_p9&@^18ml1^[@g4t*[JOa*[=Qp7(qJ_oOL^('7fB&Hq-:sf,sNj8xq^>$U4O]GKx'm9)b@p7YsvK3w^YR-" "CdQ*:Ir<($u&)#(&?L9Rg3H)4fiEp^iI9O8KnTj,]H?D*r7'M;PwZ9K0E^k&-cpI;.p/6_vwoFMV<->#%Xi.LxVnrU(4&8/P+:hLSKj$#U%]49t'I:rgMi'FL@a:0Y-uA[39',(vbma*" "hU%<-SRF`Tt:542R_VV$p@[p8DV[A,?1839FWdF<TddF<9Ah-6&9tWoDlh]&1SpGMq>Ti1O*H&#(AL8[_P%.M>v^-))qOT*F5Cq0`Ye%+$B6i:7@0IX<N+T+0MlMBPQ*Vj>SsD<U4JHY" "8kD2)2fU/M#$e.)T4,_=8hLim[&);?UkK'-x?'(:siIfL<$pFM`i<?%W(mGDHM%>iWP,##P`%/L<eXi:@Z9C.7o=@(pXdAO/NLQ8lPl+HPOQa8wD8=^GlPa8TKI1CjhsCTSLJM'/Wl>-" "S(qw%sf/@%#B6;/U7K]uZbi^Oc^2n<bhPmUkMw>%t<)'mEVE''n`WnJra$^TKvX5B>;_aSEK',(hwa0:i4G?.Bci.(X[?b*($,=-n<.Q%`(X=?+@Am*Js0&=3bh8K]mL<LoNs'6,'85`" "0?t/'_U59@]ddF<#LdF<eWdF<OuN/45rY<-L@&#+fm>69=Lb,OcZV/);TTm8VI;?%OtJ<(b4mq7M6:u?KRdF<gR@2L=FNU-<b[(9c/ML3m;Z[$oF3g)GAWqpARc=<ROu7cL5l;-[A]%/" "+fsd;l#SafT/f*W]0=O'$(Tb<[)*@e775R-:Yob%g*>l*:xP?Yb.5)%w_I?7uk5JC+FS(m#i'k.'a0i)9<7b'fs'59hq$*5Uhv##pi^8+hIEBF`nvo`;'l0.^S1<-wUK2/Coh58KKhLj" "M=SO*rfO`+qC`W-On.=AJ56>>i2@2LH6A:&5q`?9I3@@'04&p2/LVa*T-4<-i3;M9UvZd+N7>b*eIwg:CC)c<>nO&#<IGe;__.thjZl<%w(Wk2xmp4Q@I#I9,DF]u7-P=.-_:YJ]aS@V" "?6*C()dOp7:WL,b&3Rg/.cmM9&r^>$(>.Z-I&J(Q0Hd5Q%7Co-b`-c<N(6r@ip+AurK<m86QIth*#v;-OBqi+L7wDE-Ir8K['m+DDSLwK&/.?-V%U_%3:qKNu$_b*B-kp7NaD'QdWQPK" "Yq[@>P)hI;*_F]u`Rb[.j8_Q/<&>uu+VsH$sM9TA%?)(vmJ80),P7E>)tjD%2L=-t#fK[%`v=Q8<FfNkgg^oIbah*#8/Qt$F&:K*-(N/'+1vMB,u()-a.VUU*#[e%gAAO(S>WlA2);Sa" ">gXm8YB`1d@K#n]76-a$U,mF<fX]idqd)<3,]J7JmW4`6]uks=4-72L(jEk+:bJ0M^q-8Dm_Z?0olP1C9Sa&H[d&c$ooQUj]Exd*3ZM@-WGW2%s',B-_M%>%Ul:#/'xoFM9QX-$.QN'>" "[%$Z$uF6pA6Ki2O5:8w*vP1<-1`[G,)-m#>0`P&#eb#.3i)rtB61(o'$?X3B</R90;eZ]%Ncq;-Tl]#F>2Qft^ae_5tKL9MUe9b*sLEQ95C&`=G?@Mj=wh*'3E>=-<)Gt*Iw)'QG:`@I" "wOf7&]1i'S01B+Ev/Nac#9S;=;YQpg_6U`*kVY39xK,[/6Aj7:'1Bm-_1EYfa1+o&o4hp7KN_Q(OlIo@S%;jVdn0'1<Vc52=u`3^o-n1'g4v58Hj&6_t7$##?M)c<$bgQ_'SY((-xkA#" "Y(,p'H9rIVY-b,'%bCPF7.J<Up^,(dU1VY*5#WkTU>h19w,WQhLI)3S#f$2(eb,jr*b;3Vw]*7NH%$c4Vs,eD9>XW8?N]o+(*pgC%/72LV-u<Hp,3@e^9UB1J+ak9-TN/mhKPg+AJYd$" "MlvAF_jCK*.O-^(63adMT->W%iewS8W6m2rtCpo'RS1R84=@paTKt)>=%&1[)*vp'u+x,VrwN;&]kuO9JDbg=pO$J*.jVe;u'm0dr9l,<*wMK*Oe=g8lV_KEBFkO'oU]^=[-792#ok,)" "i]lR8qQ2oA8wcRCZ^7w/Njh;?.stX?Q1>S1q4Bn$)K1<-rGdO'$Wr.Lc.CG)$/*JL4tNR/,SVO3,aUw'DJN:)Ss;wGn9A32ijw%FL+Z0Fn.U9;reSq)bmI32U==5ALuG&#Vf1398/pVo" "1*c-(aY168o<`JsSbk-,1N;$>0:OUas(3:8Z972LSfF8eb=c-;>SPw7.6hn3m`9^Xkn(r.qS[0;T%&Qc=+STRxX'q1BNk3&*eu2;&8q$&x>Q#Q7^Tf+6<(d%ZVmj2bDi%.3L2n+4W'$P" "iDDG)g,r%+?,$@?uou5tSe2aN_AQU*<h`e-GI7)?OK2A.d7_c)?wQ5AS@DL3r#7fSkgl6-++D:'A,uq7SvlB$pcpH'q3n0#_%dY#xCpr-l<F0NR@-##FEV6NTF6##$l84N1w?AO>'IAO" "URQ##V^Fv-XFbGM7Fl(N<3DhLGF%q.1rC$#:T__&Pi68%0xi_&[qFJ(77j_&JWoF.V735&T,[R*:xFR*K5>>#`bW-?4Ne_&6Ne_&6Ne_&n`kr-#GJcM6X;uM6X;uM(.a..^2TkL%oR(#" ";u.T%fAr%4tJ8&><1=GHZ_+m9/#H1F^R#SC#*N=BA9(D?v[UiFY>>^8p,KKF.W]L29uLkLlu/+4T<XoIB&hx=T1PcDaB&;HH+-AFr?(m9HZV)FKS8JCw;SD=6[^/DZUL`EUDf]GGlG&>" "w$)F./^n3+rlo+DB;5sIYGNk+i1t-69Jg--0pao7Sm#K)pdHW&;LuDNH@H>#/X-TI(;P>#,Gc>#0Su>#4`1?#8lC?#<xU?#@.i?#D:%@#HF7@#LRI@#P_[@#Tkn@#Xw*A#]-=A#a9OA#" "d<F&#*;G##.GY##2Sl##6`($#:l:$#>xL$#B.`$#F:r$#JF.%#NR@%#R_R%#Vke%#Zww%#_-4&#3^Rh%Sflr-k'MS.o?.5/sWel/wpEM0%3'/1)K^f1-d>G21&v(35>V`39V7A4=onx4" "A1OY5EI0;6Ibgr6M$HS7Q<)58C5w,;WoA*#[%T*#`1g*#d=#+#hI5+#lUG+#pbY+#tnl+#x$),#&1;,#*=M,#.I`,#2Ur,#6b.-#;w[H#iQtA#m^0B#qjBB#uvTB##-hB#'9$C#+E6C#" "/QHC#3^ZC#7jmC#;v)D#?,<D#C8ND#GDaD#KPsD#O]/E#g1A5#KA*1#gC17#MGd;#8(02#L-d3#rWM4#Hga1#,<w0#T.j<#O#'2#CYN1#qa^:#_4m3#o@/=#eG8=#t8J5#`+78#4uI-#" "m3B2#SB[8#Q0@8#i[*9#iOn8#1Nm;#^sN9#qh<9#:=x-#P;K2#$%X9#bC+.#Rg;<#mN=.#MTF.#RZO.#2?)4#Y#(/#[)1/#b;L/#dAU/#0Sv;#lY$0#n`-0#sf60#(F24#wrH0#%/e0#" "TmD<#%JSMFove:CTBEXI:<eh2g)B,3h2^G3i;#d3jD>)4kMYD4lVu`4m`:&5niUA5@(A5BA1]PBB:xlBCC=2CDLXMCEUtiCf&0g2'tN?PGT4CPGT4CPGT4CPGT4CPGT4CPGT4CPGT4CP" "GT4CPGT4CPGT4CPGT4CPGT4CPGT4CP-qekC`.9kEg^+F$kwViFJTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5o,^<-28ZI'O?;xp" "O?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xp;7q-#lLYI:xvD=#"; #endif /* NK_INCLUDE_DEFAULT_FONT */ #define NK_CURSOR_DATA_W 90 #define NK_CURSOR_DATA_H 27 NK_GLOBAL const char nk_custom_cursor_data[NK_CURSOR_DATA_W * NK_CURSOR_DATA_H + 1] = { "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX" "..- -X.....X- X.X - X.X -X.....X - X.....X" "--- -XXX.XXX- X...X - X...X -X....X - X....X" "X - X.X - X.....X - X.....X -X...X - X...X" "XX - X.X -X.......X- X.......X -X..X.X - X.X..X" "X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X" "X..X - X.X - X.X - X.X -XX X.X - X.X XX" "X...X - X.X - X.X - XX X.X XX - X.X - X.X " "X....X - X.X - X.X - X.X X.X X.X - X.X - X.X " "X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X " "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X " "X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X " "X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X " "X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X " "X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X " "X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X " "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX " "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------" "X.X X..X - -X.......X- X.......X - XX XX - " "XX X..X - - X.....X - X.....X - X.X X.X - " " X..X - X...X - X...X - X..X X..X - " " XX - X.X - X.X - X...XXXXXXXXXXXXX...X - " "------------ - X - X -X.....................X- " " ----------------------------------- X...XXXXXXXXXXXXX...X - " " - X..X X..X - " " - X.X X.X - " " - XX XX - " }; #ifdef __clang__ #pragma clang diagnostic pop #elif defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic pop #endif NK_INTERN unsigned int nk_decompress_length(unsigned char *input) { return (unsigned int)((input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11]); } NK_GLOBAL unsigned char *nk__barrier; NK_GLOBAL unsigned char *nk__barrier2; NK_GLOBAL unsigned char *nk__barrier3; NK_GLOBAL unsigned char *nk__barrier4; NK_GLOBAL unsigned char *nk__dout; NK_INTERN void nk__match(unsigned char *data, unsigned int length) { /* INVERSE of memmove... write each byte before copying the next...*/ NK_ASSERT (nk__dout + length <= nk__barrier); if (nk__dout + length > nk__barrier) { nk__dout += length; return; } if (data < nk__barrier4) { nk__dout = nk__barrier+1; return; } while (length--) *nk__dout++ = *data++; } NK_INTERN void nk__lit(unsigned char *data, unsigned int length) { NK_ASSERT (nk__dout + length <= nk__barrier); if (nk__dout + length > nk__barrier) { nk__dout += length; return; } if (data < nk__barrier2) { nk__dout = nk__barrier+1; return; } NK_MEMCPY(nk__dout, data, length); nk__dout += length; } #define nk__in2(x) ((i[x] << 8) + i[(x)+1]) #define nk__in3(x) ((i[x] << 16) + nk__in2((x)+1)) #define nk__in4(x) ((i[x] << 24) + nk__in3((x)+1)) NK_INTERN unsigned char* nk_decompress_token(unsigned char *i) { if (*i >= 0x20) { /* use fewer if's for cases that expand small */ if (*i >= 0x80) nk__match(nk__dout-i[1]-1, (unsigned int)i[0] - 0x80 + 1), i += 2; else if (*i >= 0x40) nk__match(nk__dout-(nk__in2(0) - 0x4000 + 1), (unsigned int)i[2]+1), i += 3; else /* *i >= 0x20 */ nk__lit(i+1, (unsigned int)i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1); } else { /* more ifs for cases that expand large, since overhead is amortized */ if (*i >= 0x18) nk__match(nk__dout-(unsigned int)(nk__in3(0) - 0x180000 + 1), (unsigned int)i[3]+1), i += 4; else if (*i >= 0x10) nk__match(nk__dout-(unsigned int)(nk__in3(0) - 0x100000 + 1), (unsigned int)nk__in2(3)+1), i += 5; else if (*i >= 0x08) nk__lit(i+2, (unsigned int)nk__in2(0) - 0x0800 + 1), i += 2 + (nk__in2(0) - 0x0800 + 1); else if (*i == 0x07) nk__lit(i+3, (unsigned int)nk__in2(1) + 1), i += 3 + (nk__in2(1) + 1); else if (*i == 0x06) nk__match(nk__dout-(unsigned int)(nk__in3(1)+1), i[4]+1u), i += 5; else if (*i == 0x04) nk__match(nk__dout-(unsigned int)(nk__in3(1)+1), (unsigned int)nk__in2(4)+1u), i += 6; } return i; } NK_INTERN unsigned int nk_adler32(unsigned int adler32, unsigned char *buffer, unsigned int buflen) { const unsigned long ADLER_MOD = 65521; unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16; unsigned long blocklen, i; blocklen = buflen % 5552; while (buflen) { for (i=0; i + 7 < blocklen; i += 8) { s1 += buffer[0], s2 += s1; s1 += buffer[1], s2 += s1; s1 += buffer[2], s2 += s1; s1 += buffer[3], s2 += s1; s1 += buffer[4], s2 += s1; s1 += buffer[5], s2 += s1; s1 += buffer[6], s2 += s1; s1 += buffer[7], s2 += s1; buffer += 8; } for (; i < blocklen; ++i) s1 += *buffer++, s2 += s1; s1 %= ADLER_MOD, s2 %= ADLER_MOD; buflen -= (unsigned int)blocklen; blocklen = 5552; } return (unsigned int)(s2 << 16) + (unsigned int)s1; } NK_INTERN unsigned int nk_decompress(unsigned char *output, unsigned char *i, unsigned int length) { unsigned int olen; if (nk__in4(0) != 0x57bC0000) return 0; if (nk__in4(4) != 0) return 0; /* error! stream is > 4GB */ olen = nk_decompress_length(i); nk__barrier2 = i; nk__barrier3 = i+length; nk__barrier = output + olen; nk__barrier4 = output; i += 16; nk__dout = output; for (;;) { unsigned char *old_i = i; i = nk_decompress_token(i); if (i == old_i) { if (*i == 0x05 && i[1] == 0xfa) { NK_ASSERT(nk__dout == output + olen); if (nk__dout != output + olen) return 0; if (nk_adler32(1, output, olen) != (unsigned int) nk__in4(2)) return 0; return olen; } else { NK_ASSERT(0); /* NOTREACHED */ return 0; } } NK_ASSERT(nk__dout <= output + olen); if (nk__dout > output + olen) return 0; } } NK_INTERN unsigned int nk_decode_85_byte(char c) { return (unsigned int)((c >= '\\') ? c-36 : c-35); } NK_INTERN void nk_decode_85(unsigned char* dst, const unsigned char* src) { while (*src) { unsigned int tmp = nk_decode_85_byte((char)src[0]) + 85 * (nk_decode_85_byte((char)src[1]) + 85 * (nk_decode_85_byte((char)src[2]) + 85 * (nk_decode_85_byte((char)src[3]) + 85 * nk_decode_85_byte((char)src[4])))); /* we can't assume little-endianess. */ dst[0] = (unsigned char)((tmp >> 0) & 0xFF); dst[1] = (unsigned char)((tmp >> 8) & 0xFF); dst[2] = (unsigned char)((tmp >> 16) & 0xFF); dst[3] = (unsigned char)((tmp >> 24) & 0xFF); src += 5; dst += 4; } } /* ------------------------------------------------------------- * * FONT ATLAS * * --------------------------------------------------------------*/ NK_API struct nk_font_config nk_font_config(float pixel_height) { struct nk_font_config cfg; nk_zero_struct(cfg); cfg.ttf_blob = 0; cfg.ttf_size = 0; cfg.ttf_data_owned_by_atlas = 0; cfg.size = pixel_height; cfg.oversample_h = 3; cfg.oversample_v = 1; cfg.pixel_snap = 0; cfg.coord_type = NK_COORD_UV; cfg.spacing = nk_vec2(0,0); cfg.range = nk_font_default_glyph_ranges(); cfg.merge_mode = 0; cfg.fallback_glyph = '?'; cfg.font = 0; return cfg; } #ifdef NK_INCLUDE_DEFAULT_ALLOCATOR NK_API void nk_font_atlas_init_default(struct nk_font_atlas *atlas) { NK_ASSERT(atlas); if (!atlas) return; nk_zero_struct(*atlas); atlas->temporary.userdata.ptr = 0; atlas->temporary.alloc = nk_malloc; atlas->temporary.free = nk_mfree; atlas->permanent.userdata.ptr = 0; atlas->permanent.alloc = nk_malloc; atlas->permanent.free = nk_mfree; } #endif NK_API void nk_font_atlas_init(struct nk_font_atlas *atlas, struct nk_allocator *alloc) { NK_ASSERT(atlas); NK_ASSERT(alloc); if (!atlas || !alloc) return; nk_zero_struct(*atlas); atlas->permanent = *alloc; atlas->temporary = *alloc; } NK_API void nk_font_atlas_init_custom(struct nk_font_atlas *atlas, struct nk_allocator *permanent, struct nk_allocator *temporary) { NK_ASSERT(atlas); NK_ASSERT(permanent); NK_ASSERT(temporary); if (!atlas || !permanent || !temporary) return; nk_zero_struct(*atlas); atlas->permanent = *permanent; atlas->temporary = *temporary; } NK_API void nk_font_atlas_begin(struct nk_font_atlas *atlas) { NK_ASSERT(atlas); NK_ASSERT(atlas->temporary.alloc && atlas->temporary.free); NK_ASSERT(atlas->permanent.alloc && atlas->permanent.free); if (!atlas || !atlas->permanent.alloc || !atlas->permanent.free || !atlas->temporary.alloc || !atlas->temporary.free) return; if (atlas->glyphs) { atlas->permanent.free(atlas->permanent.userdata, atlas->glyphs); atlas->glyphs = 0; } if (atlas->pixel) { atlas->permanent.free(atlas->permanent.userdata, atlas->pixel); atlas->pixel = 0; } } NK_API struct nk_font* nk_font_atlas_add(struct nk_font_atlas *atlas, const struct nk_font_config *config) { struct nk_font *font = 0; struct nk_font_config *cfg; NK_ASSERT(atlas); NK_ASSERT(config); NK_ASSERT(atlas->permanent.alloc); NK_ASSERT(atlas->permanent.free); NK_ASSERT(atlas->temporary.alloc); NK_ASSERT(atlas->temporary.free); NK_ASSERT(config->ttf_blob); NK_ASSERT(config->ttf_size); NK_ASSERT(config->size > 0.0f); if (!atlas || !config || !config->ttf_blob || !config->ttf_size || config->size <= 0.0f|| !atlas->permanent.alloc || !atlas->permanent.free || !atlas->temporary.alloc || !atlas->temporary.free) return 0; /* allocate and insert font config into list */ cfg = (struct nk_font_config*) atlas->permanent.alloc(atlas->permanent.userdata,0, sizeof(struct nk_font_config)); NK_MEMCPY(cfg, config, sizeof(*config)); if (!atlas->config) { atlas->config = cfg; cfg->next = 0; } else { cfg->next = atlas->config; atlas->config = cfg; } /* allocate new font */ if (!config->merge_mode) { font = (struct nk_font*) atlas->permanent.alloc(atlas->permanent.userdata,0, sizeof(struct nk_font)); NK_ASSERT(font); if (!font) return 0; font->config = cfg; } else { NK_ASSERT(atlas->font_num); font = atlas->fonts; font->config = cfg; } /* insert font into list */ if (!config->merge_mode) { if (!atlas->fonts) { atlas->fonts = font; font->next = 0; } else { font->next = atlas->fonts; atlas->fonts = font; } cfg->font = &font->info; } /* create own copy of .TTF font blob */ if (!config->ttf_data_owned_by_atlas) { cfg->ttf_blob = atlas->permanent.alloc(atlas->permanent.userdata,0, cfg->ttf_size); NK_ASSERT(cfg->ttf_blob); if (!cfg->ttf_blob) { atlas->font_num++; return 0; } NK_MEMCPY(cfg->ttf_blob, config->ttf_blob, cfg->ttf_size); cfg->ttf_data_owned_by_atlas = 1; } atlas->font_num++; return font; } NK_API struct nk_font* nk_font_atlas_add_from_memory(struct nk_font_atlas *atlas, void *memory, nk_size size, float height, const struct nk_font_config *config) { struct nk_font_config cfg; NK_ASSERT(memory); NK_ASSERT(size); NK_ASSERT(atlas); NK_ASSERT(atlas->temporary.alloc); NK_ASSERT(atlas->temporary.free); NK_ASSERT(atlas->permanent.alloc); NK_ASSERT(atlas->permanent.free); if (!atlas || !atlas->temporary.alloc || !atlas->temporary.free || !memory || !size || !atlas->permanent.alloc || !atlas->permanent.free) return 0; cfg = (config) ? *config: nk_font_config(height); cfg.ttf_blob = memory; cfg.ttf_size = size; cfg.size = height; cfg.ttf_data_owned_by_atlas = 0; return nk_font_atlas_add(atlas, &cfg); } #ifdef NK_INCLUDE_STANDARD_IO NK_API struct nk_font* nk_font_atlas_add_from_file(struct nk_font_atlas *atlas, const char *file_path, float height, const struct nk_font_config *config) { nk_size size; char *memory; struct nk_font_config cfg; NK_ASSERT(atlas); NK_ASSERT(atlas->temporary.alloc); NK_ASSERT(atlas->temporary.free); NK_ASSERT(atlas->permanent.alloc); NK_ASSERT(atlas->permanent.free); if (!atlas || !file_path) return 0; memory = nk_file_load(file_path, &size, &atlas->permanent); if (!memory) return 0; cfg = (config) ? *config: nk_font_config(height); cfg.ttf_blob = memory; cfg.ttf_size = size; cfg.size = height; cfg.ttf_data_owned_by_atlas = 1; return nk_font_atlas_add(atlas, &cfg); } #endif NK_API struct nk_font* nk_font_atlas_add_compressed(struct nk_font_atlas *atlas, void *compressed_data, nk_size compressed_size, float height, const struct nk_font_config *config) { unsigned int decompressed_size; void *decompressed_data; struct nk_font_config cfg; NK_ASSERT(compressed_data); NK_ASSERT(compressed_size); NK_ASSERT(atlas); NK_ASSERT(atlas->temporary.alloc); NK_ASSERT(atlas->temporary.free); NK_ASSERT(atlas->permanent.alloc); NK_ASSERT(atlas->permanent.free); if (!atlas || !compressed_data || !atlas->temporary.alloc || !atlas->temporary.free || !atlas->permanent.alloc || !atlas->permanent.free) return 0; decompressed_size = nk_decompress_length((unsigned char*)compressed_data); decompressed_data = atlas->permanent.alloc(atlas->permanent.userdata,0,decompressed_size); NK_ASSERT(decompressed_data); if (!decompressed_data) return 0; nk_decompress((unsigned char*)decompressed_data, (unsigned char*)compressed_data, (unsigned int)compressed_size); cfg = (config) ? *config: nk_font_config(height); cfg.ttf_blob = decompressed_data; cfg.ttf_size = decompressed_size; cfg.size = height; cfg.ttf_data_owned_by_atlas = 1; return nk_font_atlas_add(atlas, &cfg); } NK_API struct nk_font* nk_font_atlas_add_compressed_base85(struct nk_font_atlas *atlas, const char *data_base85, float height, const struct nk_font_config *config) { int compressed_size; void *compressed_data; struct nk_font *font; NK_ASSERT(data_base85); NK_ASSERT(atlas); NK_ASSERT(atlas->temporary.alloc); NK_ASSERT(atlas->temporary.free); NK_ASSERT(atlas->permanent.alloc); NK_ASSERT(atlas->permanent.free); if (!atlas || !data_base85 || !atlas->temporary.alloc || !atlas->temporary.free || !atlas->permanent.alloc || !atlas->permanent.free) return 0; compressed_size = (((int)nk_strlen(data_base85) + 4) / 5) * 4; compressed_data = atlas->temporary.alloc(atlas->temporary.userdata,0, (nk_size)compressed_size); NK_ASSERT(compressed_data); if (!compressed_data) return 0; nk_decode_85((unsigned char*)compressed_data, (const unsigned char*)data_base85); font = nk_font_atlas_add_compressed(atlas, compressed_data, (nk_size)compressed_size, height, config); atlas->temporary.free(atlas->temporary.userdata, compressed_data); return font; } #ifdef NK_INCLUDE_DEFAULT_FONT NK_API struct nk_font* nk_font_atlas_add_default(struct nk_font_atlas *atlas, float pixel_height, const struct nk_font_config *config) { NK_ASSERT(atlas); NK_ASSERT(atlas->temporary.alloc); NK_ASSERT(atlas->temporary.free); NK_ASSERT(atlas->permanent.alloc); NK_ASSERT(atlas->permanent.free); return nk_font_atlas_add_compressed_base85(atlas, nk_proggy_clean_ttf_compressed_data_base85, pixel_height, config); } #endif NK_API const void* nk_font_atlas_bake(struct nk_font_atlas *atlas, int *width, int *height, enum nk_font_atlas_format fmt) { int i = 0; void *tmp = 0; nk_size tmp_size, img_size; struct nk_font *font_iter; struct nk_font_baker *baker; NK_ASSERT(width); NK_ASSERT(height); NK_ASSERT(atlas); NK_ASSERT(atlas->temporary.alloc); NK_ASSERT(atlas->temporary.free); NK_ASSERT(atlas->permanent.alloc); NK_ASSERT(atlas->permanent.free); if (!atlas || !width || !height || !atlas->temporary.alloc || !atlas->temporary.free || !atlas->permanent.alloc || !atlas->permanent.free) return 0; #ifdef NK_INCLUDE_DEFAULT_FONT /* no font added so just use default font */ if (!atlas->font_num) atlas->default_font = nk_font_atlas_add_default(atlas, 13.0f, 0); #endif NK_ASSERT(atlas->font_num); if (!atlas->font_num) return 0; /* allocate temporary baker memory required for the baking process */ nk_font_baker_memory(&tmp_size, &atlas->glyph_count, atlas->config, atlas->font_num); tmp = atlas->temporary.alloc(atlas->temporary.userdata,0, tmp_size); NK_ASSERT(tmp); if (!tmp) goto failed; /* allocate glyph memory for all fonts */ baker = nk_font_baker(tmp, atlas->glyph_count, atlas->font_num, &atlas->temporary); atlas->glyphs = (struct nk_font_glyph*) atlas->permanent.alloc(atlas->permanent.userdata,0, sizeof(struct nk_font_glyph) * (nk_size)atlas->glyph_count); NK_ASSERT(atlas->glyphs); if (!atlas->glyphs) goto failed; /* pack all glyphs into a tight fit space */ atlas->custom.w = (NK_CURSOR_DATA_W*2)+1; atlas->custom.h = NK_CURSOR_DATA_H + 1; if (!nk_font_bake_pack(baker, &img_size, width, height, &atlas->custom, atlas->config, atlas->font_num, &atlas->temporary)) goto failed; /* allocate memory for the baked image font atlas */ atlas->pixel = atlas->temporary.alloc(atlas->temporary.userdata,0, img_size); NK_ASSERT(atlas->pixel); if (!atlas->pixel) goto failed; /* bake glyphs and custom white pixel into image */ nk_font_bake(baker, atlas->pixel, *width, *height, atlas->glyphs, atlas->glyph_count, atlas->config, atlas->font_num); nk_font_bake_custom_data(atlas->pixel, *width, *height, atlas->custom, nk_custom_cursor_data, NK_CURSOR_DATA_W, NK_CURSOR_DATA_H, '.', 'X'); /* convert alpha8 image into rgba32 image */ if (fmt == NK_FONT_ATLAS_RGBA32) { void *img_rgba = atlas->temporary.alloc(atlas->temporary.userdata,0, (nk_size)(*width * *height * 4)); NK_ASSERT(img_rgba); if (!img_rgba) goto failed; nk_font_bake_convert(img_rgba, *width, *height, atlas->pixel); atlas->temporary.free(atlas->temporary.userdata, atlas->pixel); atlas->pixel = img_rgba; } atlas->tex_width = *width; atlas->tex_height = *height; /* initialize each font */ for (font_iter = atlas->fonts; font_iter; font_iter = font_iter->next) { struct nk_font *font = font_iter; struct nk_font_config *config = font->config; nk_font_init(font, config->size, config->fallback_glyph, atlas->glyphs, config->font, nk_handle_ptr(0)); } /* initialize each cursor */ {NK_STORAGE const struct nk_vec2 nk_cursor_data[NK_CURSOR_COUNT][3] = { /* Pos ----- Size ------- Offset --*/ {{ 0, 3}, {12,19}, { 0, 0}}, {{13, 0}, { 7,16}, { 4, 8}}, {{31, 0}, {23,23}, {11,11}}, {{21, 0}, { 9, 23}, { 5,11}}, {{55,18}, {23, 9}, {11, 5}}, {{73, 0}, {17,17}, { 9, 9}}, {{55, 0}, {17,17}, { 9, 9}} }; for (i = 0; i < NK_CURSOR_COUNT; ++i) { struct nk_cursor *cursor = &atlas->cursors[i]; cursor->img.w = (unsigned short)*width; cursor->img.h = (unsigned short)*height; cursor->img.region[0] = (unsigned short)(atlas->custom.x + nk_cursor_data[i][0].x); cursor->img.region[1] = (unsigned short)(atlas->custom.y + nk_cursor_data[i][0].y); cursor->img.region[2] = (unsigned short)nk_cursor_data[i][1].x; cursor->img.region[3] = (unsigned short)nk_cursor_data[i][1].y; cursor->size = nk_cursor_data[i][1]; cursor->offset = nk_cursor_data[i][2]; }} /* free temporary memory */ atlas->temporary.free(atlas->temporary.userdata, tmp); return atlas->pixel; failed: /* error so cleanup all memory */ if (tmp) atlas->temporary.free(atlas->temporary.userdata, tmp); if (atlas->glyphs) { atlas->permanent.free(atlas->permanent.userdata, atlas->glyphs); atlas->glyphs = 0; } if (atlas->pixel) { atlas->temporary.free(atlas->temporary.userdata, atlas->pixel); atlas->pixel = 0; } return 0; } NK_API void nk_font_atlas_end(struct nk_font_atlas *atlas, nk_handle texture, struct nk_draw_null_texture *null) { int i = 0; struct nk_font *font_iter; NK_ASSERT(atlas); if (!atlas) { if (!null) return; null->texture = texture; null->uv = nk_vec2(0.5f,0.5f); } if (null) { null->texture = texture; null->uv = nk_vec2((atlas->custom.x + 0.5f)/(float)atlas->tex_width, (atlas->custom.y + 0.5f)/(float)atlas->tex_height); } for (font_iter = atlas->fonts; font_iter; font_iter = font_iter->next) { font_iter->texture = texture; #ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT font_iter->handle.texture = texture; #endif } for (i = 0; i < NK_CURSOR_COUNT; ++i) atlas->cursors[i].img.handle = texture; atlas->temporary.free(atlas->temporary.userdata, atlas->pixel); atlas->pixel = 0; atlas->tex_width = 0; atlas->tex_height = 0; atlas->custom.x = 0; atlas->custom.y = 0; atlas->custom.w = 0; atlas->custom.h = 0; } NK_API void nk_font_atlas_clear(struct nk_font_atlas *atlas) { NK_ASSERT(atlas); NK_ASSERT(atlas->temporary.alloc); NK_ASSERT(atlas->temporary.free); NK_ASSERT(atlas->permanent.alloc); NK_ASSERT(atlas->permanent.free); if (!atlas || !atlas->temporary.alloc || !atlas->temporary.free || !atlas->permanent.alloc || !atlas->permanent.free) return; if (atlas->fonts) { struct nk_font *iter, *next; for (iter = atlas->fonts; iter; iter = next) { next = iter->next; atlas->permanent.free(atlas->permanent.userdata, iter); } atlas->fonts = 0; } if (atlas->config) { struct nk_font_config *iter, *next; for (iter = atlas->config; iter; iter = next) { next = iter->next; atlas->permanent.free(atlas->permanent.userdata, iter->ttf_blob); atlas->permanent.free(atlas->permanent.userdata, iter); } } if (atlas->glyphs) atlas->permanent.free(atlas->permanent.userdata, atlas->glyphs); nk_zero_struct(*atlas); } #endif /* ============================================================== * * INPUT * * ===============================================================*/ NK_API void nk_input_begin(struct nk_context *ctx) { int i; struct nk_input *in; NK_ASSERT(ctx); if (!ctx) return; in = &ctx->input; for (i = 0; i < NK_BUTTON_MAX; ++i) in->mouse.buttons[i].clicked = 0; in->keyboard.text_len = 0; in->mouse.scroll_delta = 0; in->mouse.prev.x = in->mouse.pos.x; in->mouse.prev.y = in->mouse.pos.y; in->mouse.delta.x = 0; in->mouse.delta.y = 0; for (i = 0; i < NK_KEY_MAX; i++) in->keyboard.keys[i].clicked = 0; } NK_API void nk_input_end(struct nk_context *ctx) { struct nk_input *in; NK_ASSERT(ctx); if (!ctx) return; in = &ctx->input; if (in->mouse.grab) in->mouse.grab = 0; if (in->mouse.ungrab) { in->mouse.grabbed = 0; in->mouse.ungrab = 0; in->mouse.grab = 0; } } NK_API void nk_input_motion(struct nk_context *ctx, int x, int y) { struct nk_input *in; NK_ASSERT(ctx); if (!ctx) return; in = &ctx->input; in->mouse.pos.x = (float)x; in->mouse.pos.y = (float)y; in->mouse.delta.x = in->mouse.pos.x - in->mouse.prev.x; in->mouse.delta.y = in->mouse.pos.y - in->mouse.prev.y; } NK_API void nk_input_key(struct nk_context *ctx, enum nk_keys key, int down) { struct nk_input *in; NK_ASSERT(ctx); if (!ctx) return; in = &ctx->input; in->keyboard.keys[key].down = down; in->keyboard.keys[key].clicked++; } NK_API void nk_input_button(struct nk_context *ctx, enum nk_buttons id, int x, int y, int down) { struct nk_mouse_button *btn; struct nk_input *in; NK_ASSERT(ctx); if (!ctx) return; in = &ctx->input; if (in->mouse.buttons[id].down == down) return; btn = &in->mouse.buttons[id]; btn->clicked_pos.x = (float)x; btn->clicked_pos.y = (float)y; btn->down = down; btn->clicked++; } NK_API void nk_input_scroll(struct nk_context *ctx, float y) { NK_ASSERT(ctx); if (!ctx) return; ctx->input.mouse.scroll_delta += y; } NK_API void nk_input_glyph(struct nk_context *ctx, const nk_glyph glyph) { int len = 0; nk_rune unicode; struct nk_input *in; NK_ASSERT(ctx); if (!ctx) return; in = &ctx->input; len = nk_utf_decode(glyph, &unicode, NK_UTF_SIZE); if (len && ((in->keyboard.text_len + len) < NK_INPUT_MAX)) { nk_utf_encode(unicode, &in->keyboard.text[in->keyboard.text_len], NK_INPUT_MAX - in->keyboard.text_len); in->keyboard.text_len += len; } } NK_API void nk_input_char(struct nk_context *ctx, char c) { nk_glyph glyph; NK_ASSERT(ctx); if (!ctx) return; glyph[0] = c; nk_input_glyph(ctx, glyph); } NK_API void nk_input_unicode(struct nk_context *ctx, nk_rune unicode) { nk_glyph rune; NK_ASSERT(ctx); if (!ctx) return; nk_utf_encode(unicode, rune, NK_UTF_SIZE); nk_input_glyph(ctx, rune); } NK_API int nk_input_has_mouse_click(const struct nk_input *i, enum nk_buttons id) { const struct nk_mouse_button *btn; if (!i) return nk_false; btn = &i->mouse.buttons[id]; return (btn->clicked && btn->down == nk_false) ? nk_true : nk_false; } NK_API int nk_input_has_mouse_click_in_rect(const struct nk_input *i, enum nk_buttons id, struct nk_rect b) { const struct nk_mouse_button *btn; if (!i) return nk_false; btn = &i->mouse.buttons[id]; if (!NK_INBOX(btn->clicked_pos.x,btn->clicked_pos.y,b.x,b.y,b.w,b.h)) return nk_false; return nk_true; } NK_API int nk_input_has_mouse_click_down_in_rect(const struct nk_input *i, enum nk_buttons id, struct nk_rect b, int down) { const struct nk_mouse_button *btn; if (!i) return nk_false; btn = &i->mouse.buttons[id]; return nk_input_has_mouse_click_in_rect(i, id, b) && (btn->down == down); } NK_API int nk_input_is_mouse_click_in_rect(const struct nk_input *i, enum nk_buttons id, struct nk_rect b) { const struct nk_mouse_button *btn; if (!i) return nk_false; btn = &i->mouse.buttons[id]; return (nk_input_has_mouse_click_down_in_rect(i, id, b, nk_false) && btn->clicked) ? nk_true : nk_false; } NK_API int nk_input_is_mouse_click_down_in_rect(const struct nk_input *i, enum nk_buttons id, struct nk_rect b, int down) { const struct nk_mouse_button *btn; if (!i) return nk_false; btn = &i->mouse.buttons[id]; return (nk_input_has_mouse_click_down_in_rect(i, id, b, down) && btn->clicked) ? nk_true : nk_false; } NK_API int nk_input_any_mouse_click_in_rect(const struct nk_input *in, struct nk_rect b) { int i, down = 0; for (i = 0; i < NK_BUTTON_MAX; ++i) down = down || nk_input_is_mouse_click_in_rect(in, (enum nk_buttons)i, b); return down; } NK_API int nk_input_is_mouse_hovering_rect(const struct nk_input *i, struct nk_rect rect) { if (!i) return nk_false; return NK_INBOX(i->mouse.pos.x, i->mouse.pos.y, rect.x, rect.y, rect.w, rect.h); } NK_API int nk_input_is_mouse_prev_hovering_rect(const struct nk_input *i, struct nk_rect rect) { if (!i) return nk_false; return NK_INBOX(i->mouse.prev.x, i->mouse.prev.y, rect.x, rect.y, rect.w, rect.h); } NK_API int nk_input_mouse_clicked(const struct nk_input *i, enum nk_buttons id, struct nk_rect rect) { if (!i) return nk_false; if (!nk_input_is_mouse_hovering_rect(i, rect)) return nk_false; return nk_input_is_mouse_click_in_rect(i, id, rect); } NK_API int nk_input_is_mouse_down(const struct nk_input *i, enum nk_buttons id) { if (!i) return nk_false; return i->mouse.buttons[id].down; } NK_API int nk_input_is_mouse_pressed(const struct nk_input *i, enum nk_buttons id) { const struct nk_mouse_button *b; if (!i) return nk_false; b = &i->mouse.buttons[id]; if (b->down && b->clicked) return nk_true; return nk_false; } NK_API int nk_input_is_mouse_released(const struct nk_input *i, enum nk_buttons id) { if (!i) return nk_false; return (!i->mouse.buttons[id].down && i->mouse.buttons[id].clicked); } NK_API int nk_input_is_key_pressed(const struct nk_input *i, enum nk_keys key) { const struct nk_key *k; if (!i) return nk_false; k = &i->keyboard.keys[key]; if ((k->down && k->clicked) || (!k->down && k->clicked >= 2)) return nk_true; return nk_false; } NK_API int nk_input_is_key_released(const struct nk_input *i, enum nk_keys key) { const struct nk_key *k; if (!i) return nk_false; k = &i->keyboard.keys[key]; if ((!k->down && k->clicked) || (k->down && k->clicked >= 2)) return nk_true; return nk_false; } NK_API int nk_input_is_key_down(const struct nk_input *i, enum nk_keys key) { const struct nk_key *k; if (!i) return nk_false; k = &i->keyboard.keys[key]; if (k->down) return nk_true; return nk_false; } /* * ============================================================== * * TEXT EDITOR * * =============================================================== */ /* stb_textedit.h - v1.8 - public domain - Sean Barrett */ struct nk_text_find { float x,y; /* position of n'th character */ float height; /* height of line */ int first_char, length; /* first char of row, and length */ int prev_first; /*_ first char of previous row */ }; struct nk_text_edit_row { float x0,x1; /* starting x location, end x location (allows for align=right, etc) */ float baseline_y_delta; /* position of baseline relative to previous row's baseline*/ float ymin,ymax; /* height of row above and below baseline */ int num_chars; }; /* forward declarations */ NK_INTERN void nk_textedit_makeundo_delete(struct nk_text_edit*, int, int); NK_INTERN void nk_textedit_makeundo_insert(struct nk_text_edit*, int, int); NK_INTERN void nk_textedit_makeundo_replace(struct nk_text_edit*, int, int, int); #define NK_TEXT_HAS_SELECTION(s) ((s)->select_start != (s)->select_end) NK_INTERN float nk_textedit_get_width(const struct nk_text_edit *edit, int line_start, int char_id, const struct nk_user_font *font) { int len = 0; nk_rune unicode = 0; const char *str = nk_str_at_const(&edit->string, line_start + char_id, &unicode, &len); return font->width(font->userdata, font->height, str, len); } NK_INTERN void nk_textedit_layout_row(struct nk_text_edit_row *r, struct nk_text_edit *edit, int line_start_id, float row_height, const struct nk_user_font *font) { int l; int glyphs = 0; nk_rune unicode; const char *remaining; int len = nk_str_len_char(&edit->string); const char *end = nk_str_get_const(&edit->string) + len; const char *text = nk_str_at_const(&edit->string, line_start_id, &unicode, &l); const struct nk_vec2 size = nk_text_calculate_text_bounds(font, text, (int)(end - text), row_height, &remaining, 0, &glyphs, NK_STOP_ON_NEW_LINE); r->x0 = 0.0f; r->x1 = size.x; r->baseline_y_delta = size.y; r->ymin = 0.0f; r->ymax = size.y; r->num_chars = glyphs; } NK_INTERN int nk_textedit_locate_coord(struct nk_text_edit *edit, float x, float y, const struct nk_user_font *font, float row_height) { struct nk_text_edit_row r; int n = edit->string.len; float base_y = 0, prev_x; int i=0, k; r.x0 = r.x1 = 0; r.ymin = r.ymax = 0; r.num_chars = 0; /* search rows to find one that straddles 'y' */ while (i < n) { nk_textedit_layout_row(&r, edit, i, row_height, font); if (r.num_chars <= 0) return n; if (i==0 && y < base_y + r.ymin) return 0; if (y < base_y + r.ymax) break; i += r.num_chars; base_y += r.baseline_y_delta; } /* below all text, return 'after' last character */ if (i >= n) return n; /* check if it's before the beginning of the line */ if (x < r.x0) return i; /* check if it's before the end of the line */ if (x < r.x1) { /* search characters in row for one that straddles 'x' */ k = i; prev_x = r.x0; for (i=0; i < r.num_chars; ++i) { float w = nk_textedit_get_width(edit, k, i, font); if (x < prev_x+w) { if (x < prev_x+w/2) return k+i; else return k+i+1; } prev_x += w; } /* shouldn't happen, but if it does, fall through to end-of-line case */ } /* if the last character is a newline, return that. * otherwise return 'after' the last character */ if (nk_str_rune_at(&edit->string, i+r.num_chars-1) == '\n') return i+r.num_chars-1; else return i+r.num_chars; } NK_INTERN void nk_textedit_click(struct nk_text_edit *state, float x, float y, const struct nk_user_font *font, float row_height) { /* API click: on mouse down, move the cursor to the clicked location, * and reset the selection */ state->cursor = nk_textedit_locate_coord(state, x, y, font, row_height); state->select_start = state->cursor; state->select_end = state->cursor; state->has_preferred_x = 0; } NK_INTERN void nk_textedit_drag(struct nk_text_edit *state, float x, float y, const struct nk_user_font *font, float row_height) { /* API drag: on mouse drag, move the cursor and selection endpoint * to the clicked location */ int p = nk_textedit_locate_coord(state, x, y, font, row_height); if (state->select_start == state->select_end) state->select_start = state->cursor; state->cursor = state->select_end = p; } NK_INTERN void nk_textedit_find_charpos(struct nk_text_find *find, struct nk_text_edit *state, int n, int single_line, const struct nk_user_font *font, float row_height) { /* find the x/y location of a character, and remember info about the previous * row in case we get a move-up event (for page up, we'll have to rescan) */ struct nk_text_edit_row r; int prev_start = 0; int z = state->string.len; int i=0, first; if (n == z) { /* if it's at the end, then find the last line -- simpler than trying to explicitly handle this case in the regular code */ if (single_line) { nk_textedit_layout_row(&r, state, 0, row_height, font); find->y = 0; find->first_char = 0; find->length = z; find->height = r.ymax - r.ymin; find->x = r.x1; } else { find->y = 0; find->x = 0; find->height = 1; while (i < z) { nk_textedit_layout_row(&r, state, i, row_height, font); prev_start = i; i += r.num_chars; } find->first_char = i; find->length = 0; find->prev_first = prev_start; } return; } /* search rows to find the one that straddles character n */ find->y = 0; for(;;) { nk_textedit_layout_row(&r, state, i, row_height, font); if (n < i + r.num_chars) break; prev_start = i; i += r.num_chars; find->y += r.baseline_y_delta; } find->first_char = first = i; find->length = r.num_chars; find->height = r.ymax - r.ymin; find->prev_first = prev_start; /* now scan to find xpos */ find->x = r.x0; for (i=0; first+i < n; ++i) find->x += nk_textedit_get_width(state, first, i, font); } NK_INTERN void nk_textedit_clamp(struct nk_text_edit *state) { /* make the selection/cursor state valid if client altered the string */ int n = state->string.len; if (NK_TEXT_HAS_SELECTION(state)) { if (state->select_start > n) state->select_start = n; if (state->select_end > n) state->select_end = n; /* if clamping forced them to be equal, move the cursor to match */ if (state->select_start == state->select_end) state->cursor = state->select_start; } if (state->cursor > n) state->cursor = n; } NK_API void nk_textedit_delete(struct nk_text_edit *state, int where, int len) { /* delete characters while updating undo */ nk_textedit_makeundo_delete(state, where, len); nk_str_delete_runes(&state->string, where, len); state->has_preferred_x = 0; } NK_API void nk_textedit_delete_selection(struct nk_text_edit *state) { /* delete the section */ nk_textedit_clamp(state); if (NK_TEXT_HAS_SELECTION(state)) { if (state->select_start < state->select_end) { nk_textedit_delete(state, state->select_start, state->select_end - state->select_start); state->select_end = state->cursor = state->select_start; } else { nk_textedit_delete(state, state->select_end, state->select_start - state->select_end); state->select_start = state->cursor = state->select_end; } state->has_preferred_x = 0; } } NK_INTERN void nk_textedit_sortselection(struct nk_text_edit *state) { /* canonicalize the selection so start <= end */ if (state->select_end < state->select_start) { int temp = state->select_end; state->select_end = state->select_start; state->select_start = temp; } } NK_INTERN void nk_textedit_move_to_first(struct nk_text_edit *state) { /* move cursor to first character of selection */ if (NK_TEXT_HAS_SELECTION(state)) { nk_textedit_sortselection(state); state->cursor = state->select_start; state->select_end = state->select_start; state->has_preferred_x = 0; } } NK_INTERN void nk_textedit_move_to_last(struct nk_text_edit *state) { /* move cursor to last character of selection */ if (NK_TEXT_HAS_SELECTION(state)) { nk_textedit_sortselection(state); nk_textedit_clamp(state); state->cursor = state->select_end; state->select_start = state->select_end; state->has_preferred_x = 0; } } NK_INTERN int nk_is_word_boundary( struct nk_text_edit *state, int idx) { int len; nk_rune c; if (idx <= 0) return 1; if (!nk_str_at_rune(&state->string, idx, &c, &len)) return 1; return (c == ' ' || c == '\t' ||c == 0x3000 || c == ',' || c == ';' || c == '(' || c == ')' || c == '{' || c == '}' || c == '[' || c == ']' || c == '|'); } NK_INTERN int nk_textedit_move_to_word_previous(struct nk_text_edit *state) { int c = state->cursor - 1; while( c >= 0 && !nk_is_word_boundary(state, c)) --c; if( c < 0 ) c = 0; return c; } NK_INTERN int nk_textedit_move_to_word_next(struct nk_text_edit *state) { const int len = state->string.len; int c = state->cursor+1; while( c < len && !nk_is_word_boundary(state, c)) ++c; if( c > len ) c = len; return c; } NK_INTERN void nk_textedit_prep_selection_at_cursor(struct nk_text_edit *state) { /* update selection and cursor to match each other */ if (!NK_TEXT_HAS_SELECTION(state)) state->select_start = state->select_end = state->cursor; else state->cursor = state->select_end; } NK_API int nk_textedit_cut(struct nk_text_edit *state) { /* API cut: delete selection */ if (state->mode == NK_TEXT_EDIT_MODE_VIEW) return 0; if (NK_TEXT_HAS_SELECTION(state)) { nk_textedit_delete_selection(state); /* implicitly clamps */ state->has_preferred_x = 0; return 1; } return 0; } NK_API int nk_textedit_paste(struct nk_text_edit *state, char const *ctext, int len) { /* API paste: replace existing selection with passed-in text */ int glyphs; const char *text = (const char *) ctext; if (state->mode == NK_TEXT_EDIT_MODE_VIEW) return 0; /* if there's a selection, the paste should delete it */ nk_textedit_clamp(state); nk_textedit_delete_selection(state); /* try to insert the characters */ glyphs = nk_utf_len(ctext, len); if (nk_str_insert_text_char(&state->string, state->cursor, text, len)) { nk_textedit_makeundo_insert(state, state->cursor, glyphs); state->cursor += len; state->has_preferred_x = 0; return 1; } /* remove the undo since we didn't actually insert the characters */ if (state->undo.undo_point) --state->undo.undo_point; return 0; } NK_API void nk_textedit_text(struct nk_text_edit *state, const char *text, int total_len) { nk_rune unicode; int glyph_len; int text_len = 0; NK_ASSERT(state); NK_ASSERT(text); if (!text || !total_len || state->mode == NK_TEXT_EDIT_MODE_VIEW) return; glyph_len = nk_utf_decode(text, &unicode, total_len); if (!glyph_len) return; while ((text_len < total_len) && glyph_len) { /* don't insert a backward delete, just process the event */ if (unicode == 127) break; /* can't add newline in single-line mode */ if (unicode == '\n' && state->single_line) break; /* filter incoming text */ if (state->filter && !state->filter(state, unicode)) { glyph_len = nk_utf_decode(text + text_len, &unicode, total_len-text_len); text_len += glyph_len; continue; } if (!NK_TEXT_HAS_SELECTION(state) && state->cursor < state->string.len) { if (state->mode == NK_TEXT_EDIT_MODE_REPLACE) { nk_textedit_makeundo_replace(state, state->cursor, 1, 1); nk_str_delete_runes(&state->string, state->cursor, 1); } if (nk_str_insert_text_char(&state->string, state->cursor, text+text_len, glyph_len)) { ++state->cursor; state->has_preferred_x = 0; } } else { nk_textedit_delete_selection(state); /* implicitly clamps */ if (nk_str_insert_text_char(&state->string, state->cursor, text+text_len, glyph_len)) { nk_textedit_makeundo_insert(state, state->cursor, 1); ++state->cursor; state->has_preferred_x = 0; } } glyph_len = nk_utf_decode(text + text_len, &unicode, total_len-text_len); text_len += glyph_len; } } NK_INTERN void nk_textedit_key(struct nk_text_edit *state, enum nk_keys key, int shift_mod, const struct nk_user_font *font, float row_height) { retry: switch (key) { case NK_KEY_NONE: case NK_KEY_CTRL: case NK_KEY_ENTER: case NK_KEY_SHIFT: case NK_KEY_TAB: case NK_KEY_COPY: case NK_KEY_CUT: case NK_KEY_PASTE: case NK_KEY_MAX: default: break; case NK_KEY_TEXT_UNDO: nk_textedit_undo(state); state->has_preferred_x = 0; break; case NK_KEY_TEXT_REDO: nk_textedit_redo(state); state->has_preferred_x = 0; break; case NK_KEY_TEXT_INSERT_MODE: if (state->mode == NK_TEXT_EDIT_MODE_VIEW) state->mode = NK_TEXT_EDIT_MODE_INSERT; break; case NK_KEY_TEXT_REPLACE_MODE: if (state->mode == NK_TEXT_EDIT_MODE_VIEW) state->mode = NK_TEXT_EDIT_MODE_REPLACE; break; case NK_KEY_TEXT_RESET_MODE: if (state->mode == NK_TEXT_EDIT_MODE_INSERT || state->mode == NK_TEXT_EDIT_MODE_REPLACE) state->mode = NK_TEXT_EDIT_MODE_VIEW; break; case NK_KEY_LEFT: if (shift_mod) { nk_textedit_clamp(state); nk_textedit_prep_selection_at_cursor(state); /* move selection left */ if (state->select_end > 0) --state->select_end; state->cursor = state->select_end; state->has_preferred_x = 0; } else { /* if currently there's a selection, * move cursor to start of selection */ if (NK_TEXT_HAS_SELECTION(state)) nk_textedit_move_to_first(state); else if (state->cursor > 0) --state->cursor; state->has_preferred_x = 0; } break; case NK_KEY_RIGHT: if (shift_mod) { nk_textedit_prep_selection_at_cursor(state); /* move selection right */ ++state->select_end; nk_textedit_clamp(state); state->cursor = state->select_end; state->has_preferred_x = 0; } else { /* if currently there's a selection, * move cursor to end of selection */ if (NK_TEXT_HAS_SELECTION(state)) nk_textedit_move_to_last(state); else ++state->cursor; nk_textedit_clamp(state); state->has_preferred_x = 0; } break; case NK_KEY_TEXT_WORD_LEFT: if (shift_mod) { if( !NK_TEXT_HAS_SELECTION( state ) ) nk_textedit_prep_selection_at_cursor(state); state->cursor = nk_textedit_move_to_word_previous(state); state->select_end = state->cursor; nk_textedit_clamp(state ); } else { if (NK_TEXT_HAS_SELECTION(state)) nk_textedit_move_to_first(state); else { state->cursor = nk_textedit_move_to_word_previous(state); nk_textedit_clamp(state ); } } break; case NK_KEY_TEXT_WORD_RIGHT: if (shift_mod) { if( !NK_TEXT_HAS_SELECTION( state ) ) nk_textedit_prep_selection_at_cursor(state); state->cursor = nk_textedit_move_to_word_next(state); state->select_end = state->cursor; nk_textedit_clamp(state); } else { if (NK_TEXT_HAS_SELECTION(state)) nk_textedit_move_to_last(state); else { state->cursor = nk_textedit_move_to_word_next(state); nk_textedit_clamp(state ); } } break; case NK_KEY_DOWN: { struct nk_text_find find; struct nk_text_edit_row row; int i, sel = shift_mod; if (state->single_line) { /* on windows, up&down in single-line behave like left&right */ key = NK_KEY_RIGHT; goto retry; } if (sel) nk_textedit_prep_selection_at_cursor(state); else if (NK_TEXT_HAS_SELECTION(state)) nk_textedit_move_to_last(state); /* compute current position of cursor point */ nk_textedit_clamp(state); nk_textedit_find_charpos(&find, state, state->cursor, state->single_line, font, row_height); /* now find character position down a row */ if (find.length) { float x; float goal_x = state->has_preferred_x ? state->preferred_x : find.x; int start = find.first_char + find.length; state->cursor = start; nk_textedit_layout_row(&row, state, state->cursor, row_height, font); x = row.x0; for (i=0; i < row.num_chars; ++i) { float dx = nk_textedit_get_width(state, start, i, font); x += dx; if (x > goal_x) break; ++state->cursor; } nk_textedit_clamp(state); state->has_preferred_x = 1; state->preferred_x = goal_x; if (sel) state->select_end = state->cursor; } } break; case NK_KEY_UP: { struct nk_text_find find; struct nk_text_edit_row row; int i, sel = shift_mod; if (state->single_line) { /* on windows, up&down become left&right */ key = NK_KEY_LEFT; goto retry; } if (sel) nk_textedit_prep_selection_at_cursor(state); else if (NK_TEXT_HAS_SELECTION(state)) nk_textedit_move_to_first(state); /* compute current position of cursor point */ nk_textedit_clamp(state); nk_textedit_find_charpos(&find, state, state->cursor, state->single_line, font, row_height); /* can only go up if there's a previous row */ if (find.prev_first != find.first_char) { /* now find character position up a row */ float x; float goal_x = state->has_preferred_x ? state->preferred_x : find.x; state->cursor = find.prev_first; nk_textedit_layout_row(&row, state, state->cursor, row_height, font); x = row.x0; for (i=0; i < row.num_chars; ++i) { float dx = nk_textedit_get_width(state, find.prev_first, i, font); x += dx; if (x > goal_x) break; ++state->cursor; } nk_textedit_clamp(state); state->has_preferred_x = 1; state->preferred_x = goal_x; if (sel) state->select_end = state->cursor; } } break; case NK_KEY_DEL: if (state->mode == NK_TEXT_EDIT_MODE_VIEW) break; if (NK_TEXT_HAS_SELECTION(state)) nk_textedit_delete_selection(state); else { int n = state->string.len; if (state->cursor < n) nk_textedit_delete(state, state->cursor, 1); } state->has_preferred_x = 0; break; case NK_KEY_BACKSPACE: if (state->mode == NK_TEXT_EDIT_MODE_VIEW) break; if (NK_TEXT_HAS_SELECTION(state)) nk_textedit_delete_selection(state); else { nk_textedit_clamp(state); if (state->cursor > 0) { nk_textedit_delete(state, state->cursor-1, 1); --state->cursor; } } state->has_preferred_x = 0; break; case NK_KEY_TEXT_START: if (shift_mod) { nk_textedit_prep_selection_at_cursor(state); state->cursor = state->select_end = 0; state->has_preferred_x = 0; } else { state->cursor = state->select_start = state->select_end = 0; state->has_preferred_x = 0; } break; case NK_KEY_TEXT_END: if (shift_mod) { nk_textedit_prep_selection_at_cursor(state); state->cursor = state->select_end = state->string.len; state->has_preferred_x = 0; } else { state->cursor = state->string.len; state->select_start = state->select_end = 0; state->has_preferred_x = 0; } break; case NK_KEY_TEXT_LINE_START: { if (shift_mod) { struct nk_text_find find; nk_textedit_clamp(state); nk_textedit_prep_selection_at_cursor(state); if (state->string.len && state->cursor == state->string.len) --state->cursor; nk_textedit_find_charpos(&find, state,state->cursor, state->single_line, font, row_height); state->cursor = state->select_end = find.first_char; state->has_preferred_x = 0; } else { struct nk_text_find find; if (state->string.len && state->cursor == state->string.len) --state->cursor; nk_textedit_clamp(state); nk_textedit_move_to_first(state); nk_textedit_find_charpos(&find, state, state->cursor, state->single_line, font, row_height); state->cursor = find.first_char; state->has_preferred_x = 0; } } break; case NK_KEY_TEXT_LINE_END: { if (shift_mod) { struct nk_text_find find; nk_textedit_clamp(state); nk_textedit_prep_selection_at_cursor(state); nk_textedit_find_charpos(&find, state, state->cursor, state->single_line, font, row_height); state->has_preferred_x = 0; state->cursor = find.first_char + find.length; if (find.length > 0 && nk_str_rune_at(&state->string, state->cursor-1) == '\n') --state->cursor; state->select_end = state->cursor; } else { struct nk_text_find find; nk_textedit_clamp(state); nk_textedit_move_to_first(state); nk_textedit_find_charpos(&find, state, state->cursor, state->single_line, font, row_height); state->has_preferred_x = 0; state->cursor = find.first_char + find.length; if (find.length > 0 && nk_str_rune_at(&state->string, state->cursor-1) == '\n') --state->cursor; }} break; } } NK_INTERN void nk_textedit_flush_redo(struct nk_text_undo_state *state) { state->redo_point = NK_TEXTEDIT_UNDOSTATECOUNT; state->redo_char_point = NK_TEXTEDIT_UNDOCHARCOUNT; } NK_INTERN void nk_textedit_discard_undo(struct nk_text_undo_state *state) { /* discard the oldest entry in the undo list */ if (state->undo_point > 0) { /* if the 0th undo state has characters, clean those up */ if (state->undo_rec[0].char_storage >= 0) { int n = state->undo_rec[0].insert_length, i; /* delete n characters from all other records */ state->undo_char_point = (short)(state->undo_char_point - n); NK_MEMCPY(state->undo_char, state->undo_char + n, (nk_size)state->undo_char_point*sizeof(nk_rune)); for (i=0; i < state->undo_point; ++i) { if (state->undo_rec[i].char_storage >= 0) state->undo_rec[i].char_storage = (short) (state->undo_rec[i].char_storage - n); } } --state->undo_point; NK_MEMCPY(state->undo_rec, state->undo_rec+1, (nk_size)((nk_size)state->undo_point * sizeof(state->undo_rec[0]))); } } NK_INTERN void nk_textedit_discard_redo(struct nk_text_undo_state *state) { /* discard the oldest entry in the redo list--it's bad if this ever happens, but because undo & redo have to store the actual characters in different cases, the redo character buffer can fill up even though the undo buffer didn't */ nk_size num; int k = NK_TEXTEDIT_UNDOSTATECOUNT-1; if (state->redo_point <= k) { /* if the k'th undo state has characters, clean those up */ if (state->undo_rec[k].char_storage >= 0) { int n = state->undo_rec[k].insert_length, i; /* delete n characters from all other records */ state->redo_char_point = (short)(state->redo_char_point + n); num = (nk_size)(NK_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point); NK_MEMCPY(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, num * sizeof(char)); for (i = state->redo_point; i < k; ++i) { if (state->undo_rec[i].char_storage >= 0) { state->undo_rec[i].char_storage = (short) (state->undo_rec[i].char_storage + n); } } } ++state->redo_point; num = (nk_size)(NK_TEXTEDIT_UNDOSTATECOUNT - state->redo_point); if (num) NK_MEMCPY(state->undo_rec + state->redo_point-1, state->undo_rec + state->redo_point, num * sizeof(state->undo_rec[0])); } } NK_INTERN struct nk_text_undo_record* nk_textedit_create_undo_record(struct nk_text_undo_state *state, int numchars) { /* any time we create a new undo record, we discard redo*/ nk_textedit_flush_redo(state); /* if we have no free records, we have to make room, * by sliding the existing records down */ if (state->undo_point == NK_TEXTEDIT_UNDOSTATECOUNT) nk_textedit_discard_undo(state); /* if the characters to store won't possibly fit in the buffer, * we can't undo */ if (numchars > NK_TEXTEDIT_UNDOCHARCOUNT) { state->undo_point = 0; state->undo_char_point = 0; return 0; } /* if we don't have enough free characters in the buffer, * we have to make room */ while (state->undo_char_point + numchars > NK_TEXTEDIT_UNDOCHARCOUNT) nk_textedit_discard_undo(state); return &state->undo_rec[state->undo_point++]; } NK_INTERN nk_rune* nk_textedit_createundo(struct nk_text_undo_state *state, int pos, int insert_len, int delete_len) { struct nk_text_undo_record *r = nk_textedit_create_undo_record(state, insert_len); if (r == 0) return 0; r->where = pos; r->insert_length = (short) insert_len; r->delete_length = (short) delete_len; if (insert_len == 0) { r->char_storage = -1; return 0; } else { r->char_storage = state->undo_char_point; state->undo_char_point = (short)(state->undo_char_point + insert_len); return &state->undo_char[r->char_storage]; } } NK_API void nk_textedit_undo(struct nk_text_edit *state) { struct nk_text_undo_state *s = &state->undo; struct nk_text_undo_record u, *r; if (s->undo_point == 0) return; /* we need to do two things: apply the undo record, and create a redo record */ u = s->undo_rec[s->undo_point-1]; r = &s->undo_rec[s->redo_point-1]; r->char_storage = -1; r->insert_length = u.delete_length; r->delete_length = u.insert_length; r->where = u.where; if (u.delete_length) { /* if the undo record says to delete characters, then the redo record will need to re-insert the characters that get deleted, so we need to store them. there are three cases: - there's enough room to store the characters - characters stored for *redoing* don't leave room for redo - characters stored for *undoing* don't leave room for redo if the last is true, we have to bail */ if (s->undo_char_point + u.delete_length >= NK_TEXTEDIT_UNDOCHARCOUNT) { /* the undo records take up too much character space; there's no space * to store the redo characters */ r->insert_length = 0; } else { int i; /* there's definitely room to store the characters eventually */ while (s->undo_char_point + u.delete_length > s->redo_char_point) { /* there's currently not enough room, so discard a redo record */ nk_textedit_discard_redo(s); /* should never happen: */ if (s->redo_point == NK_TEXTEDIT_UNDOSTATECOUNT) return; } r = &s->undo_rec[s->redo_point-1]; r->char_storage = (short)(s->redo_char_point - u.delete_length); s->redo_char_point = (short)(s->redo_char_point - u.delete_length); /* now save the characters */ for (i=0; i < u.delete_length; ++i) s->undo_char[r->char_storage + i] = nk_str_rune_at(&state->string, u.where + i); } /* now we can carry out the deletion */ nk_str_delete_runes(&state->string, u.where, u.delete_length); } /* check type of recorded action: */ if (u.insert_length) { /* easy case: was a deletion, so we need to insert n characters */ nk_str_insert_text_runes(&state->string, u.where, &s->undo_char[u.char_storage], u.insert_length); s->undo_char_point = (short)(s->undo_char_point - u.insert_length); } state->cursor = (short)(u.where + u.insert_length); s->undo_point--; s->redo_point--; } NK_API void nk_textedit_redo(struct nk_text_edit *state) { struct nk_text_undo_state *s = &state->undo; struct nk_text_undo_record *u, r; if (s->redo_point == NK_TEXTEDIT_UNDOSTATECOUNT) return; /* we need to do two things: apply the redo record, and create an undo record */ u = &s->undo_rec[s->undo_point]; r = s->undo_rec[s->redo_point]; /* we KNOW there must be room for the undo record, because the redo record was derived from an undo record */ u->delete_length = r.insert_length; u->insert_length = r.delete_length; u->where = r.where; u->char_storage = -1; if (r.delete_length) { /* the redo record requires us to delete characters, so the undo record needs to store the characters */ if (s->undo_char_point + u->insert_length > s->redo_char_point) { u->insert_length = 0; u->delete_length = 0; } else { int i; u->char_storage = s->undo_char_point; s->undo_char_point = (short)(s->undo_char_point + u->insert_length); /* now save the characters */ for (i=0; i < u->insert_length; ++i) { s->undo_char[u->char_storage + i] = nk_str_rune_at(&state->string, u->where + i); } } nk_str_delete_runes(&state->string, r.where, r.delete_length); } if (r.insert_length) { /* easy case: need to insert n characters */ nk_str_insert_text_runes(&state->string, r.where, &s->undo_char[r.char_storage], r.insert_length); } state->cursor = r.where + r.insert_length; s->undo_point++; s->redo_point++; } NK_INTERN void nk_textedit_makeundo_insert(struct nk_text_edit *state, int where, int length) { nk_textedit_createundo(&state->undo, where, 0, length); } NK_INTERN void nk_textedit_makeundo_delete(struct nk_text_edit *state, int where, int length) { int i; nk_rune *p = nk_textedit_createundo(&state->undo, where, length, 0); if (p) { for (i=0; i < length; ++i) p[i] = nk_str_rune_at(&state->string, where+i); } } NK_INTERN void nk_textedit_makeundo_replace(struct nk_text_edit *state, int where, int old_length, int new_length) { int i; nk_rune *p = nk_textedit_createundo(&state->undo, where, old_length, new_length); if (p) { for (i=0; i < old_length; ++i) p[i] = nk_str_rune_at(&state->string, where+i); } } NK_INTERN void nk_textedit_clear_state(struct nk_text_edit *state, enum nk_text_edit_type type, nk_plugin_filter filter) { /* reset the state to default */ state->undo.undo_point = 0; state->undo.undo_char_point = 0; state->undo.redo_point = NK_TEXTEDIT_UNDOSTATECOUNT; state->undo.redo_char_point = NK_TEXTEDIT_UNDOCHARCOUNT; state->select_end = state->select_start = 0; state->cursor = 0; state->has_preferred_x = 0; state->preferred_x = 0; state->cursor_at_end_of_line = 0; state->initialized = 1; state->single_line = (unsigned char)(type == NK_TEXT_EDIT_SINGLE_LINE); state->mode = NK_TEXT_EDIT_MODE_VIEW; state->filter = filter; } NK_API void nk_textedit_init_fixed(struct nk_text_edit *state, void *memory, nk_size size) { NK_ASSERT(state); NK_ASSERT(memory); if (!state || !memory || !size) return; nk_textedit_clear_state(state, NK_TEXT_EDIT_SINGLE_LINE, 0); nk_str_init_fixed(&state->string, memory, size); } NK_API void nk_textedit_init(struct nk_text_edit *state, struct nk_allocator *alloc, nk_size size) { NK_ASSERT(state); NK_ASSERT(alloc); if (!state || !alloc) return; nk_textedit_clear_state(state, NK_TEXT_EDIT_SINGLE_LINE, 0); nk_str_init(&state->string, alloc, size); } #ifdef NK_INCLUDE_DEFAULT_ALLOCATOR NK_API void nk_textedit_init_default(struct nk_text_edit *state) { NK_ASSERT(state); if (!state) return; nk_textedit_clear_state(state, NK_TEXT_EDIT_SINGLE_LINE, 0); nk_str_init_default(&state->string); } #endif NK_API void nk_textedit_select_all(struct nk_text_edit *state) { NK_ASSERT(state); state->select_start = 0; state->select_end = state->string.len; } NK_API void nk_textedit_free(struct nk_text_edit *state) { NK_ASSERT(state); if (!state) return; nk_str_free(&state->string); } /* =============================================================== * * TEXT WIDGET * * ===============================================================*/ #define nk_widget_state_reset(s)\ if ((*(s)) & NK_WIDGET_STATE_MODIFIED)\ (*(s)) = NK_WIDGET_STATE_INACTIVE|NK_WIDGET_STATE_MODIFIED;\ else (*(s)) = NK_WIDGET_STATE_INACTIVE; struct nk_text { struct nk_vec2 padding; struct nk_color background; struct nk_color text; }; NK_INTERN void nk_widget_text(struct nk_command_buffer *o, struct nk_rect b, const char *string, int len, const struct nk_text *t, nk_flags a, const struct nk_user_font *f) { struct nk_rect label; float text_width; NK_ASSERT(o); NK_ASSERT(t); if (!o || !t) return; b.h = NK_MAX(b.h, 2 * t->padding.y); label.x = 0; label.w = 0; label.y = b.y + t->padding.y; label.h = b.h - 2 * t->padding.y; text_width = f->width(f->userdata, f->height, (const char*)string, len); text_width += (2.0f * t->padding.x); /* align in x-axis */ if (a & NK_TEXT_ALIGN_LEFT) { label.x = b.x + t->padding.x; label.w = NK_MAX(0, b.w - 2 * t->padding.x); } else if (a & NK_TEXT_ALIGN_CENTERED) { label.w = NK_MAX(1, 2 * t->padding.x + (float)text_width); label.x = (b.x + t->padding.x + ((b.w - 2 * t->padding.x) - label.w) / 2); label.x = NK_MAX(b.x + t->padding.x, label.x); label.w = NK_MIN(b.x + b.w, label.x + label.w); if (label.w >= label.x) label.w -= label.x; } else if (a & NK_TEXT_ALIGN_RIGHT) { label.x = NK_MAX(b.x + t->padding.x, (b.x + b.w) - (2 * t->padding.x + (float)text_width)); label.w = (float)text_width + 2 * t->padding.x; } else return; /* align in y-axis */ if (a & NK_TEXT_ALIGN_MIDDLE) { label.y = b.y + b.h/2.0f - (float)f->height/2.0f; label.h = NK_MAX(b.h/2.0f, b.h - (b.h/2.0f + f->height/2.0f)); } else if (a & NK_TEXT_ALIGN_BOTTOM) { label.y = b.y + b.h - f->height; label.h = f->height; } nk_draw_text(o, label, (const char*)string, len, f, t->background, t->text); } NK_INTERN void nk_widget_text_wrap(struct nk_command_buffer *o, struct nk_rect b, const char *string, int len, const struct nk_text *t, const struct nk_user_font *f) { float width; int glyphs = 0; int fitting = 0; int done = 0; struct nk_rect line; struct nk_text text; NK_ASSERT(o); NK_ASSERT(t); if (!o || !t) return; text.padding = nk_vec2(0,0); text.background = t->background; text.text = t->text; b.w = NK_MAX(b.w, 2 * t->padding.x); b.h = NK_MAX(b.h, 2 * t->padding.y); b.h = b.h - 2 * t->padding.y; line.x = b.x + t->padding.x; line.y = b.y + t->padding.y; line.w = b.w - 2 * t->padding.x; line.h = 2 * t->padding.y + f->height; fitting = nk_text_clamp(f, string, len, line.w, &glyphs, &width); while (done < len) { if (!fitting || line.y + line.h >= (b.y + b.h)) break; nk_widget_text(o, line, &string[done], fitting, &text, NK_TEXT_LEFT, f); done += fitting; line.y += f->height + 2 * t->padding.y; fitting = nk_text_clamp(f, &string[done], len - done, line.w, &glyphs, &width); } } /* =============================================================== * * BUTTON * * ===============================================================*/ NK_INTERN void nk_draw_symbol(struct nk_command_buffer *out, enum nk_symbol_type type, struct nk_rect content, struct nk_color background, struct nk_color foreground, float border_width, const struct nk_user_font *font) { switch (type) { case NK_SYMBOL_X: case NK_SYMBOL_UNDERSCORE: case NK_SYMBOL_PLUS: case NK_SYMBOL_MINUS: { /* single character text symbol */ const char *X = (type == NK_SYMBOL_X) ? "x": (type == NK_SYMBOL_UNDERSCORE) ? "_": (type == NK_SYMBOL_PLUS) ? "+": "-"; struct nk_text text; text.padding = nk_vec2(0,0); text.background = background; text.text = foreground; nk_widget_text(out, content, X, 1, &text, NK_TEXT_CENTERED, font); } break; case NK_SYMBOL_CIRCLE_SOLID: case NK_SYMBOL_CIRCLE_OUTLINE: case NK_SYMBOL_RECT_SOLID: case NK_SYMBOL_RECT_OUTLINE: { /* simple empty/filled shapes */ if (type == NK_SYMBOL_RECT_SOLID || type == NK_SYMBOL_RECT_OUTLINE) { nk_fill_rect(out, content, 0, foreground); if (type == NK_SYMBOL_RECT_OUTLINE) nk_fill_rect(out, nk_shrink_rect(content, border_width), 0, background); } else { nk_fill_circle(out, content, foreground); if (type == NK_SYMBOL_CIRCLE_OUTLINE) nk_fill_circle(out, nk_shrink_rect(content, 1), background); } } break; case NK_SYMBOL_TRIANGLE_UP: case NK_SYMBOL_TRIANGLE_DOWN: case NK_SYMBOL_TRIANGLE_LEFT: case NK_SYMBOL_TRIANGLE_RIGHT: { enum nk_heading heading; struct nk_vec2 points[3]; heading = (type == NK_SYMBOL_TRIANGLE_RIGHT) ? NK_RIGHT : (type == NK_SYMBOL_TRIANGLE_LEFT) ? NK_LEFT: (type == NK_SYMBOL_TRIANGLE_UP) ? NK_UP: NK_DOWN; nk_triangle_from_direction(points, content, 0, 0, heading); nk_fill_triangle(out, points[0].x, points[0].y, points[1].x, points[1].y, points[2].x, points[2].y, foreground); } break; default: case NK_SYMBOL_NONE: case NK_SYMBOL_MAX: break; } } NK_INTERN int nk_button_behavior(nk_flags *state, struct nk_rect r, const struct nk_input *i, enum nk_button_behavior behavior) { int ret = 0; nk_widget_state_reset(state); if (!i) return 0; if (nk_input_is_mouse_hovering_rect(i, r)) { *state = NK_WIDGET_STATE_HOVERED; if (nk_input_is_mouse_down(i, NK_BUTTON_LEFT)) *state = NK_WIDGET_STATE_ACTIVE; if (nk_input_has_mouse_click_in_rect(i, NK_BUTTON_LEFT, r)) { ret = (behavior != NK_BUTTON_DEFAULT) ? nk_input_is_mouse_down(i, NK_BUTTON_LEFT): #ifdef NK_BUTTON_TRIGGER_ON_RELEASE nk_input_is_mouse_released(i, NK_BUTTON_LEFT); #else nk_input_is_mouse_pressed(i, NK_BUTTON_LEFT); #endif } } if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(i, r)) *state |= NK_WIDGET_STATE_ENTERED; else if (nk_input_is_mouse_prev_hovering_rect(i, r)) *state |= NK_WIDGET_STATE_LEFT; return ret; } NK_INTERN const struct nk_style_item* nk_draw_button(struct nk_command_buffer *out, const struct nk_rect *bounds, nk_flags state, const struct nk_style_button *style) { const struct nk_style_item *background; if (state & NK_WIDGET_STATE_HOVER) background = &style->hover; else if (state & NK_WIDGET_STATE_ACTIVED) background = &style->active; else background = &style->normal; if (background->type == NK_STYLE_ITEM_IMAGE) { nk_draw_image(out, *bounds, &background->data.image, nk_white); } else { nk_fill_rect(out, *bounds, style->rounding, style->border_color); nk_fill_rect(out, nk_shrink_rect(*bounds, style->border), style->rounding, background->data.color); } return background; } NK_INTERN int nk_do_button(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, const struct nk_style_button *style, const struct nk_input *in, enum nk_button_behavior behavior, struct nk_rect *content) { struct nk_rect bounds; NK_ASSERT(style); NK_ASSERT(state); NK_ASSERT(out); if (!out || !style) return nk_false; /* calculate button content space */ content->x = r.x + style->padding.x + style->border + style->rounding; content->y = r.y + style->padding.y + style->border + style->rounding; content->w = r.w - (2 * style->padding.x + style->border + style->rounding*2); content->h = r.h - (2 * style->padding.y + style->border + style->rounding*2); /* execute button behavior */ bounds.x = r.x - style->touch_padding.x; bounds.y = r.y - style->touch_padding.y; bounds.w = r.w + 2 * style->touch_padding.x; bounds.h = r.h + 2 * style->touch_padding.y; return nk_button_behavior(state, bounds, in, behavior); } NK_INTERN void nk_draw_button_text(struct nk_command_buffer *out, const struct nk_rect *bounds, const struct nk_rect *content, nk_flags state, const struct nk_style_button *style, const char *txt, int len, nk_flags text_alignment, const struct nk_user_font *font) { struct nk_text text; const struct nk_style_item *background; background = nk_draw_button(out, bounds, state, style); /* select correct colors/images */ if (background->type == NK_STYLE_ITEM_COLOR) text.background = background->data.color; else text.background = style->text_background; if (state & NK_WIDGET_STATE_HOVER) text.text = style->text_hover; else if (state & NK_WIDGET_STATE_ACTIVED) text.text = style->text_active; else text.text = style->text_normal; text.padding = nk_vec2(0,0); nk_widget_text(out, *content, txt, len, &text, text_alignment, font); } NK_INTERN int nk_do_button_text(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, const char *string, int len, nk_flags align, enum nk_button_behavior behavior, const struct nk_style_button *style, const struct nk_input *in, const struct nk_user_font *font) { struct nk_rect content; int ret = nk_false; NK_ASSERT(state); NK_ASSERT(style); NK_ASSERT(out); NK_ASSERT(string); NK_ASSERT(font); if (!out || !style || !font || !string) return nk_false; ret = nk_do_button(state, out, bounds, style, in, behavior, &content); if (style->draw_begin) style->draw_begin(out, style->userdata); nk_draw_button_text(out, &bounds, &content, *state, style, string, len, align, font); if (style->draw_end) style->draw_end(out, style->userdata); return ret; } NK_INTERN void nk_draw_button_symbol(struct nk_command_buffer *out, const struct nk_rect *bounds, const struct nk_rect *content, nk_flags state, const struct nk_style_button *style, enum nk_symbol_type type, const struct nk_user_font *font) { struct nk_color sym, bg; const struct nk_style_item *background; /* select correct colors/images */ background = nk_draw_button(out, bounds, state, style); if (background->type == NK_STYLE_ITEM_COLOR) bg = background->data.color; else bg = style->text_background; if (state & NK_WIDGET_STATE_HOVER) sym = style->text_hover; else if (state & NK_WIDGET_STATE_ACTIVED) sym = style->text_active; else sym = style->text_normal; nk_draw_symbol(out, type, *content, bg, sym, 1, font); } NK_INTERN int nk_do_button_symbol(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, enum nk_symbol_type symbol, enum nk_button_behavior behavior, const struct nk_style_button *style, const struct nk_input *in, const struct nk_user_font *font) { int ret; struct nk_rect content; NK_ASSERT(state); NK_ASSERT(style); NK_ASSERT(font); NK_ASSERT(out); if (!out || !style || !font || !state) return nk_false; ret = nk_do_button(state, out, bounds, style, in, behavior, &content); if (style->draw_begin) style->draw_begin(out, style->userdata); nk_draw_button_symbol(out, &bounds, &content, *state, style, symbol, font); if (style->draw_end) style->draw_end(out, style->userdata); return ret; } NK_INTERN void nk_draw_button_image(struct nk_command_buffer *out, const struct nk_rect *bounds, const struct nk_rect *content, nk_flags state, const struct nk_style_button *style, const struct nk_image *img) { nk_draw_button(out, bounds, state, style); nk_draw_image(out, *content, img, nk_white); } NK_INTERN int nk_do_button_image(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, struct nk_image img, enum nk_button_behavior b, const struct nk_style_button *style, const struct nk_input *in) { int ret; struct nk_rect content; NK_ASSERT(state); NK_ASSERT(style); NK_ASSERT(out); if (!out || !style || !state) return nk_false; ret = nk_do_button(state, out, bounds, style, in, b, &content); content.x += style->image_padding.x; content.y += style->image_padding.y; content.w -= 2 * style->image_padding.x; content.h -= 2 * style->image_padding.y; if (style->draw_begin) style->draw_begin(out, style->userdata); nk_draw_button_image(out, &bounds, &content, *state, style, &img); if (style->draw_end) style->draw_end(out, style->userdata); return ret; } NK_INTERN void nk_draw_button_text_symbol(struct nk_command_buffer *out, const struct nk_rect *bounds, const struct nk_rect *label, const struct nk_rect *symbol, nk_flags state, const struct nk_style_button *style, const char *str, int len, enum nk_symbol_type type, const struct nk_user_font *font) { struct nk_color sym; struct nk_text text; const struct nk_style_item *background; /* select correct background colors/images */ background = nk_draw_button(out, bounds, state, style); if (background->type == NK_STYLE_ITEM_COLOR) text.background = background->data.color; else text.background = style->text_background; /* select correct text colors */ if (state & NK_WIDGET_STATE_HOVER) { sym = style->text_hover; text.text = style->text_hover; } else if (state & NK_WIDGET_STATE_ACTIVED) { sym = style->text_active; text.text = style->text_active; } else { sym = style->text_normal; text.text = style->text_normal; } text.padding = nk_vec2(0,0); nk_draw_symbol(out, type, *symbol, style->text_background, sym, 0, font); nk_widget_text(out, *label, str, len, &text, NK_TEXT_CENTERED, font); } NK_INTERN int nk_do_button_text_symbol(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, enum nk_symbol_type symbol, const char *str, int len, nk_flags align, enum nk_button_behavior behavior, const struct nk_style_button *style, const struct nk_user_font *font, const struct nk_input *in) { int ret; struct nk_rect tri = {0,0,0,0}; struct nk_rect content; NK_ASSERT(style); NK_ASSERT(out); NK_ASSERT(font); if (!out || !style || !font) return nk_false; ret = nk_do_button(state, out, bounds, style, in, behavior, &content); tri.y = content.y + (content.h/2) - font->height/2; tri.w = font->height; tri.h = font->height; if (align & NK_TEXT_ALIGN_LEFT) { tri.x = (content.x + content.w) - (2 * style->padding.x + tri.w); tri.x = NK_MAX(tri.x, 0); } else tri.x = content.x + 2 * style->padding.x; /* draw button */ if (style->draw_begin) style->draw_begin(out, style->userdata); nk_draw_button_text_symbol(out, &bounds, &content, &tri, *state, style, str, len, symbol, font); if (style->draw_end) style->draw_end(out, style->userdata); return ret; } NK_INTERN void nk_draw_button_text_image(struct nk_command_buffer *out, const struct nk_rect *bounds, const struct nk_rect *label, const struct nk_rect *image, nk_flags state, const struct nk_style_button *style, const char *str, int len, const struct nk_user_font *font, const struct nk_image *img) { struct nk_text text; const struct nk_style_item *background; background = nk_draw_button(out, bounds, state, style); /* select correct colors */ if (background->type == NK_STYLE_ITEM_COLOR) text.background = background->data.color; else text.background = style->text_background; if (state & NK_WIDGET_STATE_HOVER) text.text = style->text_hover; else if (state & NK_WIDGET_STATE_ACTIVED) text.text = style->text_active; else text.text = style->text_normal; text.padding = nk_vec2(0,0); nk_widget_text(out, *label, str, len, &text, NK_TEXT_CENTERED, font); nk_draw_image(out, *image, img, nk_white); } NK_INTERN int nk_do_button_text_image(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, struct nk_image img, const char* str, int len, nk_flags align, enum nk_button_behavior behavior, const struct nk_style_button *style, const struct nk_user_font *font, const struct nk_input *in) { int ret; struct nk_rect icon; struct nk_rect content; NK_ASSERT(style); NK_ASSERT(state); NK_ASSERT(font); NK_ASSERT(out); if (!out || !font || !style || !str) return nk_false; ret = nk_do_button(state, out, bounds, style, in, behavior, &content); icon.y = bounds.y + style->padding.y; icon.w = icon.h = bounds.h - 2 * style->padding.y; if (align & NK_TEXT_ALIGN_LEFT) { icon.x = (bounds.x + bounds.w) - (2 * style->padding.x + icon.w); icon.x = NK_MAX(icon.x, 0); } else icon.x = bounds.x + 2 * style->padding.x; icon.x += style->image_padding.x; icon.y += style->image_padding.y; icon.w -= 2 * style->image_padding.x; icon.h -= 2 * style->image_padding.y; if (style->draw_begin) style->draw_begin(out, style->userdata); nk_draw_button_text_image(out, &bounds, &content, &icon, *state, style, str, len, font, &img); if (style->draw_end) style->draw_end(out, style->userdata); return ret; } /* =============================================================== * * TOGGLE * * ===============================================================*/ enum nk_toggle_type { NK_TOGGLE_CHECK, NK_TOGGLE_OPTION }; NK_INTERN int nk_toggle_behavior(const struct nk_input *in, struct nk_rect select, nk_flags *state, int active) { nk_widget_state_reset(state); if (nk_button_behavior(state, select, in, NK_BUTTON_DEFAULT)) { *state = NK_WIDGET_STATE_ACTIVE; active = !active; } if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(in, select)) *state |= NK_WIDGET_STATE_ENTERED; else if (nk_input_is_mouse_prev_hovering_rect(in, select)) *state |= NK_WIDGET_STATE_LEFT; return active; } NK_INTERN void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, int active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font) { const struct nk_style_item *background; const struct nk_style_item *cursor; struct nk_text text; /* select correct colors/images */ if (state & NK_WIDGET_STATE_HOVER) { background = &style->hover; cursor = &style->cursor_hover; text.text = style->text_hover; } else if (state & NK_WIDGET_STATE_ACTIVED) { background = &style->hover; cursor = &style->cursor_hover; text.text = style->text_active; } else { background = &style->normal; cursor = &style->cursor_normal; text.text = style->text_normal; } /* draw background and cursor */ if (background->type == NK_STYLE_ITEM_COLOR) { nk_fill_rect(out, *selector, 0, style->border_color); nk_fill_rect(out, nk_shrink_rect(*selector, style->border), 0, background->data.color); } else nk_draw_image(out, *selector, &background->data.image, nk_white); if (active) { if (cursor->type == NK_STYLE_ITEM_IMAGE) nk_draw_image(out, *cursors, &cursor->data.image, nk_white); else nk_fill_rect(out, *cursors, 0, cursor->data.color); } text.padding.x = 0; text.padding.y = 0; text.background = style->text_background; nk_widget_text(out, *label, string, len, &text, NK_TEXT_LEFT, font); } NK_INTERN void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, int active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font) { const struct nk_style_item *background; const struct nk_style_item *cursor; struct nk_text text; /* select correct colors/images */ if (state & NK_WIDGET_STATE_HOVER) { background = &style->hover; cursor = &style->cursor_hover; text.text = style->text_hover; } else if (state & NK_WIDGET_STATE_ACTIVED) { background = &style->hover; cursor = &style->cursor_hover; text.text = style->text_active; } else { background = &style->normal; cursor = &style->cursor_normal; text.text = style->text_normal; } /* draw background and cursor */ if (background->type == NK_STYLE_ITEM_COLOR) { nk_fill_circle(out, *selector, style->border_color); nk_fill_circle(out, nk_shrink_rect(*selector, style->border), background->data.color); } else nk_draw_image(out, *selector, &background->data.image, nk_white); if (active) { if (cursor->type == NK_STYLE_ITEM_IMAGE) nk_draw_image(out, *cursors, &cursor->data.image, nk_white); else nk_fill_circle(out, *cursors, cursor->data.color); } text.padding.x = 0; text.padding.y = 0; text.background = style->text_background; nk_widget_text(out, *label, string, len, &text, NK_TEXT_LEFT, font); } NK_INTERN int nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, int *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font) { int was_active; struct nk_rect bounds; struct nk_rect select; struct nk_rect cursor; struct nk_rect label; NK_ASSERT(style); NK_ASSERT(out); NK_ASSERT(font); if (!out || !style || !font || !active) return 0; r.w = NK_MAX(r.w, font->height + 2 * style->padding.x); r.h = NK_MAX(r.h, font->height + 2 * style->padding.y); /* add additional touch padding for touch screen devices */ bounds.x = r.x - style->touch_padding.x; bounds.y = r.y - style->touch_padding.y; bounds.w = r.w + 2 * style->touch_padding.x; bounds.h = r.h + 2 * style->touch_padding.y; /* calculate the selector space */ select.w = font->height; select.h = select.w; select.y = r.y + r.h/2.0f - select.h/2.0f; select.x = r.x; /* calculate the bounds of the cursor inside the selector */ cursor.x = select.x + style->padding.x + style->border; cursor.y = select.y + style->padding.y + style->border; cursor.w = select.w - (2 * style->padding.x + 2 * style->border); cursor.h = select.h - (2 * style->padding.y + 2 * style->border); /* label behind the selector */ label.x = select.x + select.w + style->spacing; label.y = select.y; label.w = NK_MAX(r.x + r.w, label.x) - label.x; label.h = select.w; /* update selector */ was_active = *active; *active = nk_toggle_behavior(in, bounds, state, *active); /* draw selector */ if (style->draw_begin) style->draw_begin(out, style->userdata); if (type == NK_TOGGLE_CHECK) { nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font); } else { nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font); } if (style->draw_end) style->draw_end(out, style->userdata); return (was_active != *active); } /* =============================================================== * * SELECTABLE * * ===============================================================*/ NK_INTERN void nk_draw_selectable(struct nk_command_buffer *out, nk_flags state, const struct nk_style_selectable *style, int active, const struct nk_rect *bounds, const struct nk_rect *icon, const struct nk_image *img, const char *string, int len, nk_flags align, const struct nk_user_font *font) { const struct nk_style_item *background; struct nk_text text; text.padding = style->padding; /* select correct colors/images */ if (!active) { if (state & NK_WIDGET_STATE_ACTIVED) { background = &style->pressed; text.text = style->text_pressed; } else if (state & NK_WIDGET_STATE_HOVER) { background = &style->hover; text.text = style->text_hover; } else { background = &style->normal; text.text = style->text_normal; } } else { if (state & NK_WIDGET_STATE_ACTIVED) { background = &style->pressed_active; text.text = style->text_pressed_active; } else if (state & NK_WIDGET_STATE_HOVER) { background = &style->hover_active; text.text = style->text_hover_active; } else { background = &style->normal_active; text.text = style->text_normal_active; } } /* draw selectable background and text */ if (background->type == NK_STYLE_ITEM_IMAGE) { nk_draw_image(out, *bounds, &background->data.image, nk_white); text.background = nk_rgba(0,0,0,0); } else { nk_fill_rect(out, *bounds, style->rounding, background->data.color); text.background = background->data.color; } if (img && icon) nk_draw_image(out, *icon, img, nk_white); nk_widget_text(out, *bounds, string, len, &text, align, font); } NK_INTERN int nk_do_selectable(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, const char *str, int len, nk_flags align, int *value, const struct nk_style_selectable *style, const struct nk_input *in, const struct nk_user_font *font) { int old_value; struct nk_rect touch; NK_ASSERT(state); NK_ASSERT(out); NK_ASSERT(str); NK_ASSERT(len); NK_ASSERT(value); NK_ASSERT(style); NK_ASSERT(font); if (!state || !out || !str || !len || !value || !style || !font) return 0; old_value = *value; /* remove padding */ touch.x = bounds.x - style->touch_padding.x; touch.y = bounds.y - style->touch_padding.y; touch.w = bounds.w + style->touch_padding.x * 2; touch.h = bounds.h + style->touch_padding.y * 2; /* update button */ if (nk_button_behavior(state, touch, in, NK_BUTTON_DEFAULT)) *value = !(*value); /* draw selectable */ if (style->draw_begin) style->draw_begin(out, style->userdata); nk_draw_selectable(out, *state, style, *value, &bounds, 0,0, str, len, align, font); if (style->draw_end) style->draw_end(out, style->userdata); return old_value != *value; } NK_INTERN int nk_do_selectable_image(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, const char *str, int len, nk_flags align, int *value, const struct nk_image *img, const struct nk_style_selectable *style, const struct nk_input *in, const struct nk_user_font *font) { int old_value; struct nk_rect touch; struct nk_rect icon; NK_ASSERT(state); NK_ASSERT(out); NK_ASSERT(str); NK_ASSERT(len); NK_ASSERT(value); NK_ASSERT(style); NK_ASSERT(font); if (!state || !out || !str || !len || !value || !style || !font) return 0; old_value = *value; /* toggle behavior */ touch.x = bounds.x - style->touch_padding.x; touch.y = bounds.y - style->touch_padding.y; touch.w = bounds.w + style->touch_padding.x * 2; touch.h = bounds.h + style->touch_padding.y * 2; if (nk_button_behavior(state, touch, in, NK_BUTTON_DEFAULT)) *value = !(*value); icon.y = bounds.y + style->padding.y; icon.w = icon.h = bounds.h - 2 * style->padding.y; if (align & NK_TEXT_ALIGN_LEFT) { icon.x = (bounds.x + bounds.w) - (2 * style->padding.x + icon.w); icon.x = NK_MAX(icon.x, 0); } else icon.x = bounds.x + 2 * style->padding.x; icon.x += style->image_padding.x; icon.y += style->image_padding.y; icon.w -= 2 * style->image_padding.x; icon.h -= 2 * style->image_padding.y; /* draw selectable */ if (style->draw_begin) style->draw_begin(out, style->userdata); nk_draw_selectable(out, *state, style, *value, &bounds, &icon, img, str, len, align, font); if (style->draw_end) style->draw_end(out, style->userdata); return old_value != *value; } /* =============================================================== * * SLIDER * * ===============================================================*/ NK_INTERN float nk_slider_behavior(nk_flags *state, struct nk_rect *logical_cursor, struct nk_rect *visual_cursor, struct nk_input *in, const struct nk_style_slider *style, struct nk_rect bounds, float slider_min, float slider_max, float slider_value, float slider_step, float slider_steps) { int left_mouse_down; int left_mouse_click_in_cursor; /* check if visual cursor is being dragged */ nk_widget_state_reset(state); left_mouse_down = in && in->mouse.buttons[NK_BUTTON_LEFT].down; left_mouse_click_in_cursor = in && nk_input_has_mouse_click_down_in_rect(in, NK_BUTTON_LEFT, *visual_cursor, nk_true); if (left_mouse_down && left_mouse_click_in_cursor) { float ratio = 0; const float d = in->mouse.pos.x - (visual_cursor->x + visual_cursor->w / 2.0f); const float pxstep = (bounds.w - (2 * style->padding.x)) / slider_steps; /* only update value if the next slider step is reached */ *state = NK_WIDGET_STATE_ACTIVE; if (NK_ABS(d) >= pxstep) { const float steps = (float)((int)(NK_ABS(d) / pxstep)); slider_value += (d > 0) ? (slider_step*steps) : -(slider_step*steps); slider_value = NK_CLAMP(slider_min, slider_value, slider_max); ratio = (slider_value - slider_min)/slider_step; logical_cursor->x = bounds.x + (logical_cursor->w * ratio); in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.x = logical_cursor->x + logical_cursor->w/2.0f; } } /* slider widget state */ if (nk_input_is_mouse_hovering_rect(in, bounds)) *state = NK_WIDGET_STATE_HOVERED; if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(in, bounds)) *state |= NK_WIDGET_STATE_ENTERED; else if (nk_input_is_mouse_prev_hovering_rect(in, bounds)) *state |= NK_WIDGET_STATE_LEFT; return slider_value; } NK_INTERN void nk_draw_slider(struct nk_command_buffer *out, nk_flags state, const struct nk_style_slider *style, const struct nk_rect *bounds, const struct nk_rect *visual_cursor, float min, float value, float max) { struct nk_rect fill; struct nk_rect bar; const struct nk_style_item *background; /* select correct slider images/colors */ struct nk_color bar_color; const struct nk_style_item *cursor; NK_UNUSED(min); NK_UNUSED(max); NK_UNUSED(value); if (state & NK_WIDGET_STATE_ACTIVED) { background = &style->active; bar_color = style->bar_active; cursor = &style->cursor_active; } else if (state & NK_WIDGET_STATE_HOVER) { background = &style->hover; bar_color = style->bar_hover; cursor = &style->cursor_hover; } else { background = &style->normal; bar_color = style->bar_normal; cursor = &style->cursor_normal; } /* calculate slider background bar */ bar.x = bounds->x; bar.y = (visual_cursor->y + visual_cursor->h/2) - bounds->h/12; bar.w = bounds->w; bar.h = bounds->h/6; /* filled background bar style */ fill.w = (visual_cursor->x + (visual_cursor->w/2.0f)) - bar.x; fill.x = bar.x; fill.y = bar.y; fill.h = bar.h; /* draw background */ if (background->type == NK_STYLE_ITEM_IMAGE) { nk_draw_image(out, *bounds, &background->data.image, nk_white); } else { nk_fill_rect(out, *bounds, style->rounding, style->border_color); nk_fill_rect(out, nk_shrink_rect(*bounds, style->border), style->rounding, background->data.color); } /* draw slider bar */ nk_fill_rect(out, bar, style->rounding, bar_color); nk_fill_rect(out, fill, style->rounding, style->bar_filled); /* draw cursor */ if (cursor->type == NK_STYLE_ITEM_IMAGE) nk_draw_image(out, *visual_cursor, &cursor->data.image, nk_white); else nk_fill_circle(out, *visual_cursor, cursor->data.color); } NK_INTERN float nk_do_slider(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, float min, float val, float max, float step, const struct nk_style_slider *style, struct nk_input *in, const struct nk_user_font *font) { float slider_range; float slider_min; float slider_max; float slider_value; float slider_steps; float cursor_offset; struct nk_rect visual_cursor; struct nk_rect logical_cursor; NK_ASSERT(style); NK_ASSERT(out); if (!out || !style) return 0; /* remove padding from slider bounds */ bounds.x = bounds.x + style->padding.x; bounds.y = bounds.y + style->padding.y; bounds.h = NK_MAX(bounds.h, 2*style->padding.y); bounds.w = NK_MAX(bounds.w, 2*style->padding.x + style->cursor_size.x); bounds.w -= 2 * style->padding.x; bounds.h -= 2 * style->padding.y; /* optional buttons */ if (style->show_buttons) { nk_flags ws; struct nk_rect button; button.y = bounds.y; button.w = bounds.h; button.h = bounds.h; /* decrement button */ button.x = bounds.x; if (nk_do_button_symbol(&ws, out, button, style->dec_symbol, NK_BUTTON_DEFAULT, &style->dec_button, in, font)) val -= step; /* increment button */ button.x = (bounds.x + bounds.w) - button.w; if (nk_do_button_symbol(&ws, out, button, style->inc_symbol, NK_BUTTON_DEFAULT, &style->inc_button, in, font)) val += step; bounds.x = bounds.x + button.w + style->spacing.x; bounds.w = bounds.w - (2*button.w + 2*style->spacing.x); } /* make sure the provided values are correct */ slider_max = NK_MAX(min, max); slider_min = NK_MIN(min, max); slider_value = NK_CLAMP(slider_min, val, slider_max); slider_range = slider_max - slider_min; slider_steps = slider_range / step; cursor_offset = (slider_value - slider_min) / step; /* remove one cursor size to support visual cursor */ bounds.x += style->cursor_size.x*0.5f; bounds.w -= style->cursor_size.x; /* calculate cursor Basically you have two cursors. One for visual representation and interaction and one for updating the actual cursor value. */ logical_cursor.h = bounds.h; logical_cursor.w = bounds.w / slider_steps; logical_cursor.x = bounds.x + (logical_cursor.w * cursor_offset); logical_cursor.y = bounds.y; visual_cursor.h = style->cursor_size.y; visual_cursor.w = style->cursor_size.x; visual_cursor.y = (bounds.y + bounds.h*0.5f) - visual_cursor.h*0.5f; visual_cursor.x = (logical_cursor.x + logical_cursor.w*0.5f) - visual_cursor.w*0.5f; slider_value = nk_slider_behavior(state, &logical_cursor, &visual_cursor, in, style, bounds, slider_min, slider_max, slider_value, step, slider_steps); visual_cursor.x = logical_cursor.x - visual_cursor.w*0.5f; /* draw slider */ if (style->draw_begin) style->draw_begin(out, style->userdata); nk_draw_slider(out, *state, style, &bounds, &visual_cursor, slider_min, slider_value, slider_max); if (style->draw_end) style->draw_end(out, style->userdata); return slider_value; } /* =============================================================== * * PROGRESSBAR * * ===============================================================*/ NK_INTERN nk_size nk_progress_behavior(nk_flags *state, const struct nk_input *in, struct nk_rect r, nk_size max, nk_size value, int modifiable) { nk_widget_state_reset(state); if (in && modifiable && nk_input_is_mouse_hovering_rect(in, r)) { int left_mouse_down = in->mouse.buttons[NK_BUTTON_LEFT].down; int left_mouse_click_in_cursor = nk_input_has_mouse_click_down_in_rect(in, NK_BUTTON_LEFT, r, nk_true); if (left_mouse_down && left_mouse_click_in_cursor) { float ratio = NK_MAX(0, (float)(in->mouse.pos.x - r.x)) / (float)r.w; value = (nk_size)NK_MAX(0,((float)max * ratio)); *state = NK_WIDGET_STATE_ACTIVE; } else *state = NK_WIDGET_STATE_HOVERED; } /* set progressbar widget state */ if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(in, r)) *state |= NK_WIDGET_STATE_ENTERED; else if (nk_input_is_mouse_prev_hovering_rect(in, r)) *state |= NK_WIDGET_STATE_LEFT; if (!max) return value; value = NK_MIN(value, max); return value; } NK_INTERN void nk_draw_progress(struct nk_command_buffer *out, nk_flags state, const struct nk_style_progress *style, const struct nk_rect *bounds, const struct nk_rect *scursor, nk_size value, nk_size max) { const struct nk_style_item *background; const struct nk_style_item *cursor; NK_UNUSED(max); NK_UNUSED(value); /* select correct colors/images to draw */ if (state & NK_WIDGET_STATE_ACTIVED) { background = &style->active; cursor = &style->cursor_active; } else if (state & NK_WIDGET_STATE_HOVER){ background = &style->hover; cursor = &style->cursor_hover; } else { background = &style->normal; cursor = &style->cursor_normal; } /* draw background */ if (background->type == NK_STYLE_ITEM_COLOR) { nk_fill_rect(out, *bounds, style->rounding, style->border_color); nk_fill_rect(out, nk_shrink_rect(*bounds, style->border), style->rounding, background->data.color); } else nk_draw_image(out, *bounds, &background->data.image, nk_white); /* draw cursor */ if (background->type == NK_STYLE_ITEM_COLOR) { nk_fill_rect(out, *scursor, style->rounding, style->cursor_border_color); nk_fill_rect(out, nk_shrink_rect(*scursor, style->cursor_border), style->rounding, cursor->data.color); } else nk_draw_image(out, *scursor, &cursor->data.image, nk_white); } NK_INTERN nk_size nk_do_progress(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, nk_size value, nk_size max, int modifiable, const struct nk_style_progress *style, const struct nk_input *in) { float prog_scale; nk_size prog_value; struct nk_rect cursor; NK_ASSERT(style); NK_ASSERT(out); if (!out || !style) return 0; /* calculate progressbar cursor */ cursor.w = NK_MAX(bounds.w, 2 * style->padding.x + 2 * style->border); cursor.h = NK_MAX(bounds.h, 2 * style->padding.y + 2 * style->border); cursor = nk_pad_rect(bounds, nk_vec2(style->padding.x + style->border, style->padding.y + style->border)); prog_scale = (float)value / (float)max; cursor.w = (bounds.w - 2) * prog_scale; /* update progressbar */ prog_value = NK_MIN(value, max); prog_value = nk_progress_behavior(state, in, bounds, max, prog_value, modifiable); /* draw progressbar */ if (style->draw_begin) style->draw_begin(out, style->userdata); nk_draw_progress(out, *state, style, &bounds, &cursor, value, max); if (style->draw_end) style->draw_end(out, style->userdata); return prog_value; } /* =============================================================== * * SCROLLBAR * * ===============================================================*/ NK_INTERN float nk_scrollbar_behavior(nk_flags *state, struct nk_input *in, int has_scrolling, const struct nk_rect *scroll, const struct nk_rect *cursor, const struct nk_rect *empty0, const struct nk_rect *empty1, float scroll_offset, float target, float scroll_step, enum nk_orientation o) { nk_flags ws; int left_mouse_down; int left_mouse_click_in_cursor; nk_widget_state_reset(state); if (!in) return scroll_offset; left_mouse_down = in->mouse.buttons[NK_BUTTON_LEFT].down; left_mouse_click_in_cursor = nk_input_has_mouse_click_down_in_rect(in, NK_BUTTON_LEFT, *cursor, nk_true); if (nk_input_is_mouse_hovering_rect(in, *scroll)) *state = NK_WIDGET_STATE_HOVERED; if (left_mouse_down && left_mouse_click_in_cursor) { /* update cursor by mouse dragging */ float pixel, delta; *state = NK_WIDGET_STATE_ACTIVE; if (o == NK_VERTICAL) { float cursor_y; pixel = in->mouse.delta.y; delta = (pixel / scroll->h) * target; scroll_offset = NK_CLAMP(0, scroll_offset + delta, target - scroll->h); cursor_y = scroll->y + ((scroll_offset/target) * scroll->h); in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.y = cursor_y + cursor->h/2.0f; } else { float cursor_x; pixel = in->mouse.delta.x; delta = (pixel / scroll->w) * target; scroll_offset = NK_CLAMP(0, scroll_offset + delta, target - scroll->w); cursor_x = scroll->x + ((scroll_offset/target) * scroll->w); in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.x = cursor_x + cursor->w/2.0f; } } else if ((nk_input_is_key_pressed(in, NK_KEY_SCROLL_UP) && o == NK_VERTICAL && has_scrolling)|| nk_button_behavior(&ws, *empty0, in, NK_BUTTON_DEFAULT)) { /* scroll page up by click on empty space or shortcut */ if (o == NK_VERTICAL) scroll_offset = NK_MAX(0, scroll_offset - scroll->h); else scroll_offset = NK_MAX(0, scroll_offset - scroll->w); } else if ((nk_input_is_key_pressed(in, NK_KEY_SCROLL_DOWN) && o == NK_VERTICAL && has_scrolling) || nk_button_behavior(&ws, *empty1, in, NK_BUTTON_DEFAULT)) { /* scroll page down by click on empty space or shortcut */ if (o == NK_VERTICAL) scroll_offset = NK_MIN(scroll_offset + scroll->h, target - scroll->h); else scroll_offset = NK_MIN(scroll_offset + scroll->w, target - scroll->w); } else if (has_scrolling) { if ((in->mouse.scroll_delta<0 || (in->mouse.scroll_delta>0))) { /* update cursor by mouse scrolling */ scroll_offset = scroll_offset + scroll_step * (-in->mouse.scroll_delta); if (o == NK_VERTICAL) scroll_offset = NK_CLAMP(0, scroll_offset, target - scroll->h); else scroll_offset = NK_CLAMP(0, scroll_offset, target - scroll->w); } else if (nk_input_is_key_pressed(in, NK_KEY_SCROLL_START)) { /* update cursor to the beginning */ if (o == NK_VERTICAL) scroll_offset = 0; } else if (nk_input_is_key_pressed(in, NK_KEY_SCROLL_END)) { /* update cursor to the end */ if (o == NK_VERTICAL) scroll_offset = target - scroll->h; } } if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(in, *scroll)) *state |= NK_WIDGET_STATE_ENTERED; else if (nk_input_is_mouse_prev_hovering_rect(in, *scroll)) *state |= NK_WIDGET_STATE_LEFT; return scroll_offset; } NK_INTERN void nk_draw_scrollbar(struct nk_command_buffer *out, nk_flags state, const struct nk_style_scrollbar *style, const struct nk_rect *bounds, const struct nk_rect *scroll) { const struct nk_style_item *background; const struct nk_style_item *cursor; /* select correct colors/images to draw */ if (state & NK_WIDGET_STATE_ACTIVED) { background = &style->active; cursor = &style->cursor_active; } else if (state & NK_WIDGET_STATE_HOVER) { background = &style->hover; cursor = &style->cursor_hover; } else { background = &style->normal; cursor = &style->cursor_normal; } /* draw background */ if (background->type == NK_STYLE_ITEM_COLOR) { nk_fill_rect(out, *bounds, style->rounding, style->border_color); nk_fill_rect(out, nk_shrink_rect(*bounds,style->border), style->rounding, background->data.color); } else { nk_draw_image(out, *bounds, &background->data.image, nk_white); } /* draw cursor */ if (background->type == NK_STYLE_ITEM_COLOR) { nk_fill_rect(out, *scroll, style->rounding_cursor, style->cursor_border_color); nk_fill_rect(out, nk_shrink_rect(*scroll, style->border_cursor), style->rounding_cursor, cursor->data.color); } else nk_draw_image(out, *scroll, &cursor->data.image, nk_white); } NK_INTERN float nk_do_scrollbarv(nk_flags *state, struct nk_command_buffer *out, struct nk_rect scroll, int has_scrolling, float offset, float target, float step, float button_pixel_inc, const struct nk_style_scrollbar *style, struct nk_input *in, const struct nk_user_font *font) { struct nk_rect empty_north; struct nk_rect empty_south; struct nk_rect cursor; float scroll_step; float scroll_offset; float scroll_off; float scroll_ratio; NK_ASSERT(out); NK_ASSERT(style); NK_ASSERT(state); if (!out || !style) return 0; scroll.w = NK_MAX(scroll.w, 1); scroll.h = NK_MAX(scroll.h, 2 * scroll.w); if (target <= scroll.h) return 0; /* optional scrollbar buttons */ if (style->show_buttons) { nk_flags ws; float scroll_h; struct nk_rect button; button.x = scroll.x; button.w = scroll.w; button.h = scroll.w; scroll_h = scroll.h - 2 * button.h; scroll_step = NK_MIN(step, button_pixel_inc); /* decrement button */ button.y = scroll.y; if (nk_do_button_symbol(&ws, out, button, style->dec_symbol, NK_BUTTON_REPEATER, &style->dec_button, in, font)) offset = offset - scroll_step; /* increment button */ button.y = scroll.y + scroll.h - button.h; if (nk_do_button_symbol(&ws, out, button, style->inc_symbol, NK_BUTTON_REPEATER, &style->inc_button, in, font)) offset = offset + scroll_step; scroll.y = scroll.y + button.h; scroll.h = scroll_h; } /* calculate scrollbar constants */ scroll_step = NK_MIN(step, scroll.h); scroll_offset = NK_CLAMP(0, offset, target - scroll.h); scroll_ratio = scroll.h / target; scroll_off = scroll_offset / target; /* calculate scrollbar cursor bounds */ cursor.h = (scroll_ratio * scroll.h) - (2*style->border + 2*style->padding.y); cursor.y = scroll.y + (scroll_off * scroll.h) + style->border + style->padding.y; cursor.w = scroll.w - (2 * style->border + 2 * style->padding.x); cursor.x = scroll.x + style->border + style->padding.x; /* calculate empty space around cursor */ empty_north.x = scroll.x; empty_north.y = scroll.y; empty_north.w = scroll.w; empty_north.h = cursor.y - scroll.y; empty_south.x = scroll.x; empty_south.y = cursor.y + cursor.h; empty_south.w = scroll.w; empty_south.h = (scroll.y + scroll.h) - (cursor.y + cursor.h); /* update scrollbar */ scroll_offset = nk_scrollbar_behavior(state, in, has_scrolling, &scroll, &cursor, &empty_north, &empty_south, scroll_offset, target, scroll_step, NK_VERTICAL); scroll_off = scroll_offset / target; cursor.y = scroll.y + (scroll_off * scroll.h) + style->border_cursor + style->padding.y; /* draw scrollbar */ if (style->draw_begin) style->draw_begin(out, style->userdata); nk_draw_scrollbar(out, *state, style, &scroll, &cursor); if (style->draw_end) style->draw_end(out, style->userdata); return scroll_offset; } NK_INTERN float nk_do_scrollbarh(nk_flags *state, struct nk_command_buffer *out, struct nk_rect scroll, int has_scrolling, float offset, float target, float step, float button_pixel_inc, const struct nk_style_scrollbar *style, struct nk_input *in, const struct nk_user_font *font) { struct nk_rect cursor; struct nk_rect empty_west; struct nk_rect empty_east; float scroll_step; float scroll_offset; float scroll_off; float scroll_ratio; NK_ASSERT(out); NK_ASSERT(style); if (!out || !style) return 0; /* scrollbar background */ scroll.h = NK_MAX(scroll.h, 1); scroll.w = NK_MAX(scroll.w, 2 * scroll.h); if (target <= scroll.w) return 0; /* optional scrollbar buttons */ if (style->show_buttons) { nk_flags ws; float scroll_w; struct nk_rect button; button.y = scroll.y; button.w = scroll.h; button.h = scroll.h; scroll_w = scroll.w - 2 * button.w; scroll_step = NK_MIN(step, button_pixel_inc); /* decrement button */ button.x = scroll.x; if (nk_do_button_symbol(&ws, out, button, style->dec_symbol, NK_BUTTON_REPEATER, &style->dec_button, in, font)) offset = offset - scroll_step; /* increment button */ button.x = scroll.x + scroll.w - button.w; if (nk_do_button_symbol(&ws, out, button, style->inc_symbol, NK_BUTTON_REPEATER, &style->inc_button, in, font)) offset = offset + scroll_step; scroll.x = scroll.x + button.w; scroll.w = scroll_w; } /* calculate scrollbar constants */ scroll_step = NK_MIN(step, scroll.w); scroll_offset = NK_CLAMP(0, offset, target - scroll.w); scroll_ratio = scroll.w / target; scroll_off = scroll_offset / target; /* calculate cursor bounds */ cursor.w = (scroll_ratio * scroll.w) - (2*style->border + 2*style->padding.x); cursor.x = scroll.x + (scroll_off * scroll.w) + style->border + style->padding.x; cursor.h = scroll.h - (2 * style->border + 2 * style->padding.y); cursor.y = scroll.y + style->border + style->padding.y; /* calculate empty space around cursor */ empty_west.x = scroll.x; empty_west.y = scroll.y; empty_west.w = cursor.x - scroll.x; empty_west.h = scroll.h; empty_east.x = cursor.x + cursor.w; empty_east.y = scroll.y; empty_east.w = (scroll.x + scroll.w) - (cursor.x + cursor.w); empty_east.h = scroll.h; /* update scrollbar */ scroll_offset = nk_scrollbar_behavior(state, in, has_scrolling, &scroll, &cursor, &empty_west, &empty_east, scroll_offset, target, scroll_step, NK_HORIZONTAL); scroll_off = scroll_offset / target; cursor.x = scroll.x + (scroll_off * scroll.w); /* draw scrollbar */ if (style->draw_begin) style->draw_begin(out, style->userdata); nk_draw_scrollbar(out, *state, style, &scroll, &cursor); if (style->draw_end) style->draw_end(out, style->userdata); return scroll_offset; } /* =============================================================== * * FILTER * * ===============================================================*/ NK_API int nk_filter_default(const struct nk_text_edit *box, nk_rune unicode) {(void)unicode;NK_UNUSED(box);return nk_true;} NK_API int nk_filter_ascii(const struct nk_text_edit *box, nk_rune unicode) { NK_UNUSED(box); if (unicode > 128) return nk_false; else return nk_true; } NK_API int nk_filter_float(const struct nk_text_edit *box, nk_rune unicode) { NK_UNUSED(box); if ((unicode < '0' || unicode > '9') && unicode != '.' && unicode != '-') return nk_false; else return nk_true; } NK_API int nk_filter_decimal(const struct nk_text_edit *box, nk_rune unicode) { NK_UNUSED(box); if ((unicode < '0' || unicode > '9') && unicode != '-') return nk_false; else return nk_true; } NK_API int nk_filter_hex(const struct nk_text_edit *box, nk_rune unicode) { NK_UNUSED(box); if ((unicode < '0' || unicode > '9') && (unicode < 'a' || unicode > 'f') && (unicode < 'A' || unicode > 'F')) return nk_false; else return nk_true; } NK_API int nk_filter_oct(const struct nk_text_edit *box, nk_rune unicode) { NK_UNUSED(box); if (unicode < '0' || unicode > '7') return nk_false; else return nk_true; } NK_API int nk_filter_binary(const struct nk_text_edit *box, nk_rune unicode) { NK_UNUSED(box); if (unicode != '0' && unicode != '1') return nk_false; else return nk_true; } /* =============================================================== * * EDIT * * ===============================================================*/ NK_INTERN void nk_edit_draw_text(struct nk_command_buffer *out, const struct nk_style_edit *style, float pos_x, float pos_y, float x_offset, const char *text, int byte_len, float row_height, const struct nk_user_font *font, struct nk_color background, struct nk_color foreground, int is_selected) { NK_ASSERT(out); NK_ASSERT(font); NK_ASSERT(style); if (!text || !byte_len || !out || !style) return; {int glyph_len = 0; nk_rune unicode = 0; int text_len = 0; float line_width = 0; float glyph_width; const char *line = text; float line_offset = 0; int line_count = 0; struct nk_text txt; txt.padding = nk_vec2(0,0); txt.background = background; txt.text = foreground; glyph_len = nk_utf_decode(text+text_len, &unicode, byte_len-text_len); if (!glyph_len) return; while ((text_len < byte_len) && glyph_len) { if (unicode == '\n') { /* new line sepeator so draw previous line */ struct nk_rect label; label.y = pos_y + line_offset; label.h = row_height; label.w = line_width; label.x = pos_x; if (!line_count) label.x += x_offset; if (is_selected) /* selection needs to draw different background color */ nk_fill_rect(out, label, 0, background); nk_widget_text(out, label, line, (int)((text + text_len) - line), &txt, NK_TEXT_CENTERED, font); text_len++; line_count++; line_width = 0; line = text + text_len; line_offset += row_height; glyph_len = nk_utf_decode(text + text_len, &unicode, (int)(byte_len-text_len)); continue; } if (unicode == '\r') { text_len++; glyph_len = nk_utf_decode(text + text_len, &unicode, byte_len-text_len); continue; } glyph_width = font->width(font->userdata, font->height, text+text_len, glyph_len); line_width += (float)glyph_width; text_len += glyph_len; glyph_len = nk_utf_decode(text + text_len, &unicode, byte_len-text_len); continue; } if (line_width > 0) { /* draw last line */ struct nk_rect label; label.y = pos_y + line_offset; label.h = row_height; label.w = line_width; label.x = pos_x; if (!line_count) label.x += x_offset; if (is_selected) nk_fill_rect(out, label, 0, background); nk_widget_text(out, label, line, (int)((text + text_len) - line), &txt, NK_TEXT_LEFT, font); }} } NK_INTERN nk_flags nk_do_edit(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, nk_flags flags, nk_plugin_filter filter, struct nk_text_edit *edit, const struct nk_style_edit *style, struct nk_input *in, const struct nk_user_font *font) { struct nk_rect area; nk_flags ret = 0; float row_height; char prev_state = 0; char is_hovered = 0; char select_all = 0; char cursor_follow = 0; struct nk_rect old_clip; struct nk_rect clip; NK_ASSERT(state); NK_ASSERT(out); NK_ASSERT(style); if (!state || !out || !style) return ret; /* visible text area calculation */ area.x = bounds.x + style->padding.x + style->border; area.y = bounds.y + style->padding.y + style->border; area.w = bounds.w - (2.0f * style->padding.x + 2 * style->border); area.h = bounds.h - (2.0f * style->padding.y + 2 * style->border); if (flags & NK_EDIT_MULTILINE) area.w = area.h - style->scrollbar_size.y; row_height = (flags & NK_EDIT_MULTILINE)? font->height + style->row_padding: area.h; /* calculate clipping rectangle */ old_clip = out->clip; nk_unify(&clip, &old_clip, area.x, area.y, area.x + area.w, area.y + area.h); /* update edit state */ prev_state = (char)edit->active; is_hovered = (char)nk_input_is_mouse_hovering_rect(in, bounds); if (in && in->mouse.buttons[NK_BUTTON_LEFT].clicked && in->mouse.buttons[NK_BUTTON_LEFT].down) { edit->active = NK_INBOX(in->mouse.pos.x, in->mouse.pos.y, bounds.x, bounds.y, bounds.w, bounds.h); } /* (de)activate text editor */ if (!prev_state && edit->active) { const enum nk_text_edit_type type = (flags & NK_EDIT_MULTILINE) ? NK_TEXT_EDIT_MULTI_LINE: NK_TEXT_EDIT_SINGLE_LINE; nk_textedit_clear_state(edit, type, filter); if (flags & NK_EDIT_ALWAYS_INSERT_MODE) edit->mode = NK_TEXT_EDIT_MODE_INSERT; if (flags & NK_EDIT_AUTO_SELECT) select_all = nk_true; if (flags & NK_EDIT_GOTO_END_ON_ACTIVATE) { edit->cursor = edit->string.len; in = 0; } } else if (!edit->active) edit->mode = NK_TEXT_EDIT_MODE_VIEW; if (flags & NK_EDIT_READ_ONLY) edit->mode = NK_TEXT_EDIT_MODE_VIEW; ret = (edit->active) ? NK_EDIT_ACTIVE: NK_EDIT_INACTIVE; if (prev_state != edit->active) ret |= (edit->active) ? NK_EDIT_ACTIVATED: NK_EDIT_DEACTIVATED; /* handle user input */ if (edit->active && in) { int shift_mod = in->keyboard.keys[NK_KEY_SHIFT].down; const float mouse_x = (in->mouse.pos.x - area.x) + edit->scrollbar.x; const float mouse_y = (!(flags & NK_EDIT_MULTILINE)) ? (in->mouse.pos.y - (area.y + area.h * 0.5f)) + edit->scrollbar.y: (in->mouse.pos.y - area.y) + edit->scrollbar.y; /* mouse click handler */ is_hovered = (char)nk_input_is_mouse_hovering_rect(in, area); if (select_all) { nk_textedit_select_all(edit); } else if (is_hovered && in->mouse.buttons[NK_BUTTON_LEFT].down && in->mouse.buttons[NK_BUTTON_LEFT].clicked) { nk_textedit_click(edit, mouse_x, mouse_y, font, row_height); } else if (is_hovered && in->mouse.buttons[NK_BUTTON_LEFT].down && (in->mouse.delta.x != 0.0f || in->mouse.delta.y != 0.0f)) { nk_textedit_drag(edit, mouse_x, mouse_y, font, row_height); cursor_follow = nk_true; } else if (is_hovered && in->mouse.buttons[NK_BUTTON_RIGHT].clicked && in->mouse.buttons[NK_BUTTON_RIGHT].down) { nk_textedit_key(edit, NK_KEY_TEXT_WORD_LEFT, nk_false, font, row_height); nk_textedit_key(edit, NK_KEY_TEXT_WORD_RIGHT, nk_true, font, row_height); cursor_follow = nk_true; } {int i; /* keyboard input */ int old_mode = edit->mode; for (i = 0; i < NK_KEY_MAX; ++i) { if (i == NK_KEY_ENTER || i == NK_KEY_TAB) continue; /* special case */ if (nk_input_is_key_pressed(in, (enum nk_keys)i)) { nk_textedit_key(edit, (enum nk_keys)i, shift_mod, font, row_height); cursor_follow = nk_true; } } if (old_mode != edit->mode) { in->keyboard.text_len = 0; }} /* text input */ edit->filter = filter; if (in->keyboard.text_len) { nk_textedit_text(edit, in->keyboard.text, in->keyboard.text_len); cursor_follow = nk_true; in->keyboard.text_len = 0; } /* enter key handler */ if (nk_input_is_key_pressed(in, NK_KEY_ENTER)) { cursor_follow = nk_true; if (flags & NK_EDIT_CTRL_ENTER_NEWLINE && shift_mod) nk_textedit_text(edit, "\n", 1); else if (flags & NK_EDIT_SIG_ENTER) ret |= NK_EDIT_COMMITED; else nk_textedit_text(edit, "\n", 1); } /* cut & copy handler */ {int copy= nk_input_is_key_pressed(in, NK_KEY_COPY); int cut = nk_input_is_key_pressed(in, NK_KEY_CUT); if ((copy || cut) && (flags & NK_EDIT_CLIPBOARD)) { int glyph_len; nk_rune unicode; const char *text; int b = edit->select_start; int e = edit->select_end; int begin = NK_MIN(b, e); int end = NK_MAX(b, e); text = nk_str_at_const(&edit->string, begin, &unicode, &glyph_len); if (edit->clip.copy) edit->clip.copy(edit->clip.userdata, text, end - begin); if (cut && !(flags & NK_EDIT_READ_ONLY)){ nk_textedit_cut(edit); cursor_follow = nk_true; } }} /* paste handler */ {int paste = nk_input_is_key_pressed(in, NK_KEY_PASTE); if (paste && (flags & NK_EDIT_CLIPBOARD) && edit->clip.paste) { edit->clip.paste(edit->clip.userdata, edit); cursor_follow = nk_true; }} /* tab handler */ {int tab = nk_input_is_key_pressed(in, NK_KEY_TAB); if (tab && (flags & NK_EDIT_ALLOW_TAB)) { nk_textedit_text(edit, " ", 4); cursor_follow = nk_true; }} } /* set widget state */ if (edit->active) *state = NK_WIDGET_STATE_ACTIVE; else nk_widget_state_reset(state); if (is_hovered) *state |= NK_WIDGET_STATE_HOVERED; /* DRAW EDIT */ {const char *text = nk_str_get_const(&edit->string); int len = nk_str_len_char(&edit->string); {/* select background colors/images */ const struct nk_style_item *background; if (*state & NK_WIDGET_STATE_ACTIVED) background = &style->active; else if (*state & NK_WIDGET_STATE_HOVER) background = &style->hover; else background = &style->normal; /* draw background frame */ if (background->type == NK_STYLE_ITEM_COLOR) { nk_fill_rect(out, bounds, style->rounding, style->border_color); nk_fill_rect(out, nk_shrink_rect(bounds,style->border), style->rounding, background->data.color); } else nk_draw_image(out, bounds, &background->data.image, nk_white);} area.w -= style->cursor_size + style->scrollbar_size.x; if (edit->active) { int total_lines = 1; struct nk_vec2 text_size = nk_vec2(0,0); /* text pointer positions */ const char *cursor_ptr = 0; const char *select_begin_ptr = 0; const char *select_end_ptr = 0; /* 2D pixel positions */ struct nk_vec2 cursor_pos = nk_vec2(0,0); struct nk_vec2 selection_offset_start = nk_vec2(0,0); struct nk_vec2 selection_offset_end = nk_vec2(0,0); int selection_begin = NK_MIN(edit->select_start, edit->select_end); int selection_end = NK_MAX(edit->select_start, edit->select_end); /* calculate total line count + total space + cursor/selection position */ float line_width = 0.0f; if (text && len) { /* utf8 encoding */ float glyph_width; int glyph_len = 0; nk_rune unicode = 0; int text_len = 0; int glyphs = 0; int row_begin = 0; glyph_len = nk_utf_decode(text, &unicode, len); glyph_width = font->width(font->userdata, font->height, text, glyph_len); line_width = 0; /* iterate all lines */ while ((text_len < len) && glyph_len) { /* set cursor 2D position and line */ if (!cursor_ptr && glyphs == edit->cursor) { int glyph_offset; struct nk_vec2 out_offset; struct nk_vec2 row_size; const char *remaining; /* calculate 2d position */ cursor_pos.y = (float)(total_lines-1) * row_height; row_size = nk_text_calculate_text_bounds(font, text+row_begin, text_len-row_begin, row_height, &remaining, &out_offset, &glyph_offset, NK_STOP_ON_NEW_LINE); cursor_pos.x = row_size.x; cursor_ptr = text + text_len; } /* set start selection 2D position and line */ if (!select_begin_ptr && edit->select_start != edit->select_end && glyphs == selection_begin) { int glyph_offset; struct nk_vec2 out_offset; struct nk_vec2 row_size; const char *remaining; /* calculate 2d position */ selection_offset_start.y = (float)(total_lines-1) * row_height; row_size = nk_text_calculate_text_bounds(font, text+row_begin, text_len-row_begin, row_height, &remaining, &out_offset, &glyph_offset, NK_STOP_ON_NEW_LINE); selection_offset_start.x = row_size.x; select_begin_ptr = text + text_len; } /* set end selection 2D position and line */ if (!select_end_ptr && edit->select_start != edit->select_end && glyphs == selection_end) { int glyph_offset; struct nk_vec2 out_offset; struct nk_vec2 row_size; const char *remaining; /* calculate 2d position */ selection_offset_end.y = (float)(total_lines-1) * row_height; row_size = nk_text_calculate_text_bounds(font, text+row_begin, text_len-row_begin, row_height, &remaining, &out_offset, &glyph_offset, NK_STOP_ON_NEW_LINE); selection_offset_end.x = row_size.x; select_end_ptr = text + text_len; } if (unicode == '\n') { text_size.x = NK_MAX(text_size.x, line_width); total_lines++; line_width = 0; text_len++; glyphs++; row_begin = text_len; glyph_len = nk_utf_decode(text + text_len, &unicode, len-text_len); continue; } glyphs++; text_len += glyph_len; line_width += (float)glyph_width; glyph_width = font->width(font->userdata, font->height, text+text_len, glyph_len); glyph_len = nk_utf_decode(text + text_len, &unicode, len-text_len); continue; } text_size.y = (float)total_lines * row_height; /* handle case if cursor is at end of text buffer */ if (!cursor_ptr && edit->cursor == edit->string.len) { cursor_pos.x = line_width; cursor_pos.y = text_size.y - row_height; } } { /* scrollbar */ if (cursor_follow) { /* update scrollbar to follow cursor */ if (!(flags & NK_EDIT_NO_HORIZONTAL_SCROLL)) { /* horizontal scroll */ const float scroll_increment = area.w * 0.25f; if (cursor_pos.x < edit->scrollbar.x) edit->scrollbar.x = (float)(int)NK_MAX(0.0f, cursor_pos.x - scroll_increment); if (cursor_pos.x >= edit->scrollbar.x + area.w) edit->scrollbar.x = (float)(int)NK_MAX(0.0f, cursor_pos.x); } else edit->scrollbar.x = 0; if (flags & NK_EDIT_MULTILINE) { /* vertical scroll */ if (cursor_pos.y < edit->scrollbar.y) edit->scrollbar.y = NK_MAX(0.0f, cursor_pos.y - row_height); if (cursor_pos.y >= edit->scrollbar.y + area.h) edit->scrollbar.y = edit->scrollbar.y + row_height; } else edit->scrollbar.y = 0; } /* scrollbar widget */ if (flags & NK_EDIT_MULTILINE) { nk_flags ws; struct nk_rect scroll; float scroll_target; float scroll_offset; float scroll_step; float scroll_inc; scroll = area; scroll.x = (bounds.x + bounds.w - style->border) - style->scrollbar_size.x; scroll.w = style->scrollbar_size.x; scroll_offset = edit->scrollbar.y; scroll_step = scroll.h * 0.10f; scroll_inc = scroll.h * 0.01f; scroll_target = text_size.y; edit->scrollbar.y = nk_do_scrollbarv(&ws, out, scroll, 0, scroll_offset, scroll_target, scroll_step, scroll_inc, &style->scrollbar, in, font); } } /* draw text */ {struct nk_color background_color; struct nk_color text_color; struct nk_color sel_background_color; struct nk_color sel_text_color; struct nk_color cursor_color; struct nk_color cursor_text_color; const struct nk_style_item *background; nk_push_scissor(out, clip); /* select correct colors to draw */ if (*state & NK_WIDGET_STATE_ACTIVED) { background = &style->active; text_color = style->text_active; sel_text_color = style->selected_text_hover; sel_background_color = style->selected_hover; cursor_color = style->cursor_hover; cursor_text_color = style->cursor_text_hover; } else if (*state & NK_WIDGET_STATE_HOVER) { background = &style->hover; text_color = style->text_hover; sel_text_color = style->selected_text_hover; sel_background_color = style->selected_hover; cursor_text_color = style->cursor_text_hover; cursor_color = style->cursor_hover; } else { background = &style->normal; text_color = style->text_normal; sel_text_color = style->selected_text_normal; sel_background_color = style->selected_normal; cursor_color = style->cursor_normal; cursor_text_color = style->cursor_text_normal; } if (background->type == NK_STYLE_ITEM_IMAGE) background_color = nk_rgba(0,0,0,0); else background_color = background->data.color; if (edit->select_start == edit->select_end) { /* no selection so just draw the complete text */ const char *begin = nk_str_get_const(&edit->string); int l = nk_str_len_char(&edit->string); nk_edit_draw_text(out, style, area.x - edit->scrollbar.x, area.y - edit->scrollbar.y, 0, begin, l, row_height, font, background_color, text_color, nk_false); } else { /* edit has selection so draw 1-3 text chunks */ if (edit->select_start != edit->select_end && selection_begin > 0){ /* draw unselected text before selection */ const char *begin = nk_str_get_const(&edit->string); NK_ASSERT(select_begin_ptr); nk_edit_draw_text(out, style, area.x - edit->scrollbar.x, area.y - edit->scrollbar.y, 0, begin, (int)(select_begin_ptr - begin), row_height, font, background_color, text_color, nk_false); } if (edit->select_start != edit->select_end) { /* draw selected text */ NK_ASSERT(select_begin_ptr); if (!select_end_ptr) { const char *begin = nk_str_get_const(&edit->string); select_end_ptr = begin + nk_str_len_char(&edit->string); } nk_edit_draw_text(out, style, area.x - edit->scrollbar.x, area.y + selection_offset_start.y - edit->scrollbar.y, selection_offset_start.x, select_begin_ptr, (int)(select_end_ptr - select_begin_ptr), row_height, font, sel_background_color, sel_text_color, nk_true); } if ((edit->select_start != edit->select_end && selection_end < edit->string.len)) { /* draw unselected text after selected text */ const char *begin = select_end_ptr; const char *end = nk_str_get_const(&edit->string) + nk_str_len_char(&edit->string); NK_ASSERT(select_end_ptr); nk_edit_draw_text(out, style, area.x - edit->scrollbar.x, area.y + selection_offset_end.y - edit->scrollbar.y, selection_offset_end.x, begin, (int)(end - begin), row_height, font, background_color, text_color, nk_true); } } /* cursor */ if (edit->select_start == edit->select_end) { if (edit->cursor >= nk_str_len(&edit->string) || (cursor_ptr && *cursor_ptr == '\n')) { /* draw cursor at end of line */ struct nk_rect cursor; cursor.w = style->cursor_size; cursor.h = font->height; cursor.x = area.x + cursor_pos.x - edit->scrollbar.x; cursor.y = area.y + cursor_pos.y + row_height/2.0f - cursor.h/2.0f; cursor.y -= edit->scrollbar.y; nk_fill_rect(out, cursor, 0, cursor_color); } else { /* draw cursor inside text */ int glyph_len; struct nk_rect label; struct nk_text txt; nk_rune unicode; NK_ASSERT(cursor_ptr); glyph_len = nk_utf_decode(cursor_ptr, &unicode, 4); label.x = area.x + cursor_pos.x - edit->scrollbar.x; label.y = area.y + cursor_pos.y - edit->scrollbar.y; label.w = font->width(font->userdata, font->height, cursor_ptr, glyph_len); label.h = row_height; txt.padding = nk_vec2(0,0); txt.background = cursor_color; txt.text = cursor_text_color; nk_fill_rect(out, label, 0, cursor_color); nk_widget_text(out, label, cursor_ptr, glyph_len, &txt, NK_TEXT_LEFT, font); } }} } else { /* not active so just draw text */ int l = nk_str_len(&edit->string); const char *begin = nk_str_get_const(&edit->string); const struct nk_style_item *background; struct nk_color background_color; struct nk_color text_color; if (*state & NK_WIDGET_STATE_ACTIVED) { background = &style->active; text_color = style->text_active; } else if (*state & NK_WIDGET_STATE_HOVER) { background = &style->hover; text_color = style->text_hover; } else { background = &style->normal; text_color = style->text_normal; } if (background->type == NK_STYLE_ITEM_IMAGE) background_color = nk_rgba(0,0,0,0); else background_color = background->data.color; nk_edit_draw_text(out, style, area.x - edit->scrollbar.x, area.y - edit->scrollbar.y, 0, begin, l, row_height, font, background_color, text_color, nk_false); } nk_push_scissor(out, old_clip);} return ret; } /* =============================================================== * * PROPERTY * * ===============================================================*/ enum nk_property_status { NK_PROPERTY_DEFAULT, NK_PROPERTY_EDIT, NK_PROPERTY_DRAG }; enum nk_property_filter { NK_FILTER_INT, NK_FILTER_FLOAT }; enum nk_property_kind { NK_PROPERTY_INT, NK_PROPERTY_FLOAT, NK_PROPERTY_DOUBLE }; union nk_property { int i; float f; double d; }; struct nk_property_variant { enum nk_property_kind kind; union nk_property value; union nk_property min_value; union nk_property max_value; union nk_property step; }; NK_INTERN void nk_drag_behavior(nk_flags *state, const struct nk_input *in, struct nk_rect drag, struct nk_property_variant *variant, float inc_per_pixel) { int left_mouse_down = in && in->mouse.buttons[NK_BUTTON_LEFT].down; int left_mouse_click_in_cursor = in && nk_input_has_mouse_click_down_in_rect(in, NK_BUTTON_LEFT, drag, nk_true); nk_widget_state_reset(state); if (nk_input_is_mouse_hovering_rect(in, drag)) *state = NK_WIDGET_STATE_HOVERED; if (left_mouse_down && left_mouse_click_in_cursor) { float delta, pixels; pixels = in->mouse.delta.x; delta = pixels * inc_per_pixel; switch (variant->kind) { default: break; case NK_PROPERTY_INT: variant->value.i = variant->value.i + (int)delta; variant->value.i = NK_CLAMP(variant->min_value.i, variant->value.i, variant->max_value.i); break; case NK_PROPERTY_FLOAT: variant->value.f = variant->value.f + (float)delta; variant->value.f = NK_CLAMP(variant->min_value.f, variant->value.f, variant->max_value.f); break; case NK_PROPERTY_DOUBLE: variant->value.d = variant->value.d + (double)delta; variant->value.d = NK_CLAMP(variant->min_value.d, variant->value.d, variant->max_value.d); break; } *state = NK_WIDGET_STATE_ACTIVE; } if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(in, drag)) *state |= NK_WIDGET_STATE_ENTERED; else if (nk_input_is_mouse_prev_hovering_rect(in, drag)) *state |= NK_WIDGET_STATE_LEFT; } NK_INTERN void nk_property_behavior(nk_flags *ws, const struct nk_input *in, struct nk_rect property, struct nk_rect label, struct nk_rect edit, struct nk_rect empty, int *state, struct nk_property_variant *variant, float inc_per_pixel) { if (in && *state == NK_PROPERTY_DEFAULT) { if (nk_button_behavior(ws, edit, in, NK_BUTTON_DEFAULT)) *state = NK_PROPERTY_EDIT; else if (nk_input_is_mouse_click_down_in_rect(in, NK_BUTTON_LEFT, label, nk_true)) *state = NK_PROPERTY_DRAG; else if (nk_input_is_mouse_click_down_in_rect(in, NK_BUTTON_LEFT, empty, nk_true)) *state = NK_PROPERTY_DRAG; } if (*state == NK_PROPERTY_DRAG) { nk_drag_behavior(ws, in, property, variant, inc_per_pixel); if (!(*ws & NK_WIDGET_STATE_ACTIVED)) *state = NK_PROPERTY_DEFAULT; } } NK_INTERN void nk_draw_property(struct nk_command_buffer *out, const struct nk_style_property *style, const struct nk_rect *bounds, const struct nk_rect *label, nk_flags state, const char *name, int len, const struct nk_user_font *font) { struct nk_text text; const struct nk_style_item *background; /* select correct background and text color */ if (state & NK_WIDGET_STATE_ACTIVED) { background = &style->active; text.text = style->label_active; } else if (state & NK_WIDGET_STATE_HOVER) { background = &style->hover; text.text = style->label_hover; } else { background = &style->normal; text.text = style->label_normal; } /* draw background */ if (background->type == NK_STYLE_ITEM_IMAGE) { nk_draw_image(out, *bounds, &background->data.image, nk_white); text.background = nk_rgba(0,0,0,0); } else { text.background = background->data.color; nk_fill_rect(out, *bounds, style->rounding, style->border_color); nk_fill_rect(out, nk_shrink_rect(*bounds,style->border), style->rounding, background->data.color); } /* draw label */ text.padding = nk_vec2(0,0); nk_widget_text(out, *label, name, len, &text, NK_TEXT_CENTERED, font); } NK_INTERN void nk_do_property(nk_flags *ws, struct nk_command_buffer *out, struct nk_rect property, const char *name, struct nk_property_variant *variant, float inc_per_pixel, char *buffer, int *len, int *state, int *cursor, const struct nk_style_property *style, enum nk_property_filter filter, struct nk_input *in, const struct nk_user_font *font, struct nk_text_edit *text_edit) { const nk_plugin_filter filters[] = { nk_filter_decimal, nk_filter_float }; int active, old; int num_len, name_len; char string[NK_MAX_NUMBER_BUFFER]; float size; char *dst = 0; int *length; struct nk_rect left; struct nk_rect right; struct nk_rect label; struct nk_rect edit; struct nk_rect empty; /* left decrement button */ left.h = font->height/2; left.w = left.h; left.x = property.x + style->border + style->padding.x; left.y = property.y + style->border + property.h/2.0f - left.h/2; /* text label */ name_len = nk_strlen(name); size = font->width(font->userdata, font->height, name, name_len); label.x = left.x + left.w + style->padding.x; label.w = (float)size + 2 * style->padding.x; label.y = property.y + style->border + style->padding.y; label.h = property.h - (2 * style->border + 2 * style->padding.y); /* right increment button */ right.y = left.y; right.w = left.w; right.h = left.h; right.x = property.x + property.w - (right.w + style->padding.x); /* edit */ if (*state == NK_PROPERTY_EDIT) { size = font->width(font->userdata, font->height, buffer, *len); size += style->edit.cursor_size; length = len; dst = buffer; } else { switch (variant->kind) { default: num_len = 0; break; case NK_PROPERTY_INT: nk_itoa(string, variant->value.i); num_len = nk_strlen(string); break; case NK_PROPERTY_FLOAT: nk_dtoa(string, (double)variant->value.f); num_len = nk_string_float_limit(string, NK_MAX_FLOAT_PRECISION); break; case NK_PROPERTY_DOUBLE: nk_dtoa(string, variant->value.d); num_len = nk_string_float_limit(string, NK_MAX_FLOAT_PRECISION); break; } size = font->width(font->userdata, font->height, string, num_len); dst = string; length = &num_len; } edit.w = (float)size + 2 * style->padding.x; edit.w = NK_MIN(edit.w, right.x - (label.x + label.w)); edit.x = right.x - (edit.w + style->padding.x); edit.y = property.y + style->border; edit.h = property.h - (2 * style->border); /* empty left space activator */ empty.w = edit.x - (label.x + label.w); empty.x = label.x + label.w; empty.y = property.y; empty.h = property.h; /* update property */ old = (*state == NK_PROPERTY_EDIT); nk_property_behavior(ws, in, property, label, edit, empty, state, variant, inc_per_pixel); /* draw property */ if (style->draw_begin) style->draw_begin(out, style->userdata); nk_draw_property(out, style, &property, &label, *ws, name, name_len, font); if (style->draw_end) style->draw_end(out, style->userdata); /* execute right button */ if (nk_do_button_symbol(ws, out, left, style->sym_left, NK_BUTTON_DEFAULT, &style->dec_button, in, font)) { switch (variant->kind) { default: break; case NK_PROPERTY_INT: variant->value.i = NK_CLAMP(variant->min_value.i, variant->value.i - variant->step.i, variant->max_value.i); break; case NK_PROPERTY_FLOAT: variant->value.f = NK_CLAMP(variant->min_value.f, variant->value.f - variant->step.f, variant->max_value.f); break; case NK_PROPERTY_DOUBLE: variant->value.d = NK_CLAMP(variant->min_value.d, variant->value.d - variant->step.d, variant->max_value.d); break; } } /* execute left button */ if (nk_do_button_symbol(ws, out, right, style->sym_right, NK_BUTTON_DEFAULT, &style->inc_button, in, font)) { switch (variant->kind) { default: break; case NK_PROPERTY_INT: variant->value.i = NK_CLAMP(variant->min_value.i, variant->value.i + variant->step.i, variant->max_value.i); break; case NK_PROPERTY_FLOAT: variant->value.f = NK_CLAMP(variant->min_value.f, variant->value.f + variant->step.f, variant->max_value.f); break; case NK_PROPERTY_DOUBLE: variant->value.d = NK_CLAMP(variant->min_value.d, variant->value.d + variant->step.d, variant->max_value.d); break; } } active = (*state == NK_PROPERTY_EDIT); if (old != NK_PROPERTY_EDIT && active) { /* property has been activated so setup buffer */ NK_MEMCPY(buffer, dst, (nk_size)*length); *cursor = nk_utf_len(buffer, *length); *len = *length; length = len; dst = buffer; } /* execute and run text edit field */ nk_textedit_clear_state(text_edit, NK_TEXT_EDIT_SINGLE_LINE, filters[filter]); text_edit->active = (unsigned char)active; text_edit->string.len = *length; text_edit->cursor = NK_CLAMP(0, *cursor, *length); text_edit->string.buffer.allocated = (nk_size)*length; text_edit->string.buffer.memory.size = NK_MAX_NUMBER_BUFFER; text_edit->string.buffer.memory.ptr = dst; text_edit->string.buffer.size = NK_MAX_NUMBER_BUFFER; text_edit->mode = NK_TEXT_EDIT_MODE_INSERT; nk_do_edit(ws, out, edit, NK_EDIT_ALWAYS_INSERT_MODE, filters[filter], text_edit, &style->edit, (*state == NK_PROPERTY_EDIT) ? in: 0, font); *length = text_edit->string.len; active = text_edit->active; *cursor = text_edit->cursor; if (active && nk_input_is_key_pressed(in, NK_KEY_ENTER)) active = !active; if (old && !active) { /* property is now not active so convert edit text to value*/ *state = NK_PROPERTY_DEFAULT; buffer[*len] = '\0'; switch (variant->kind) { default: break; case NK_PROPERTY_INT: variant->value.i = nk_strtoi(buffer, 0); variant->value.i = NK_CLAMP(variant->min_value.i, variant->value.i, variant->max_value.i); break; case NK_PROPERTY_FLOAT: nk_string_float_limit(buffer, NK_MAX_FLOAT_PRECISION); variant->value.f = nk_strtof(buffer, 0); variant->value.f = NK_CLAMP(variant->min_value.f, variant->value.f, variant->max_value.f); break; case NK_PROPERTY_DOUBLE: nk_string_float_limit(buffer, NK_MAX_FLOAT_PRECISION); variant->value.d = nk_strtod(buffer, 0); variant->value.d = NK_CLAMP(variant->min_value.d, variant->value.d, variant->max_value.d); break; } } } /* =============================================================== * * COLOR PICKER * * ===============================================================*/ NK_INTERN int nk_color_picker_behavior(nk_flags *state, const struct nk_rect *bounds, const struct nk_rect *matrix, const struct nk_rect *hue_bar, const struct nk_rect *alpha_bar, struct nk_color *color, const struct nk_input *in) { float hsva[4]; int value_changed = 0; int hsv_changed = 0; NK_ASSERT(state); NK_ASSERT(matrix); NK_ASSERT(hue_bar); NK_ASSERT(color); /* color matrix */ nk_color_hsva_fv(hsva, *color); if (nk_button_behavior(state, *matrix, in, NK_BUTTON_REPEATER)) { hsva[1] = NK_SATURATE((in->mouse.pos.x - matrix->x) / (matrix->w-1)); hsva[2] = 1.0f - NK_SATURATE((in->mouse.pos.y - matrix->y) / (matrix->h-1)); value_changed = hsv_changed = 1; } /* hue bar */ if (nk_button_behavior(state, *hue_bar, in, NK_BUTTON_REPEATER)) { hsva[0] = NK_SATURATE((in->mouse.pos.y - hue_bar->y) / (hue_bar->h-1)); value_changed = hsv_changed = 1; } /* alpha bar */ if (alpha_bar) { if (nk_button_behavior(state, *alpha_bar, in, NK_BUTTON_REPEATER)) { hsva[3] = 1.0f - NK_SATURATE((in->mouse.pos.y - alpha_bar->y) / (alpha_bar->h-1)); value_changed = 1; } } nk_widget_state_reset(state); if (hsv_changed) { *color = nk_hsva_fv(hsva); *state = NK_WIDGET_STATE_ACTIVE; } if (value_changed) { color->a = (nk_byte)(hsva[3] * 255.0f); *state = NK_WIDGET_STATE_ACTIVE; } /* set color picker widget state */ if (nk_input_is_mouse_hovering_rect(in, *bounds)) *state = NK_WIDGET_STATE_HOVERED; if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(in, *bounds)) *state |= NK_WIDGET_STATE_ENTERED; else if (nk_input_is_mouse_prev_hovering_rect(in, *bounds)) *state |= NK_WIDGET_STATE_LEFT; return value_changed; } NK_INTERN void nk_draw_color_picker(struct nk_command_buffer *o, const struct nk_rect *matrix, const struct nk_rect *hue_bar, const struct nk_rect *alpha_bar, struct nk_color color) { NK_STORAGE const struct nk_color black = {0,0,0,255}; NK_STORAGE const struct nk_color white = {255, 255, 255, 255}; NK_STORAGE const struct nk_color black_trans = {0,0,0,0}; const float crosshair_size = 7.0f; struct nk_color temp; float hsva[4]; float line_y; int i; NK_ASSERT(o); NK_ASSERT(matrix); NK_ASSERT(hue_bar); /* draw hue bar */ nk_color_hsv_fv(hsva, color); for (i = 0; i < 6; ++i) { NK_GLOBAL const struct nk_color hue_colors[] = { {255, 0, 0, 255}, {255,255,0,255}, {0,255,0,255}, {0, 255,255,255}, {0,0,255,255}, {255, 0, 255, 255}, {255, 0, 0, 255} }; nk_fill_rect_multi_color(o, nk_rect(hue_bar->x, hue_bar->y + (float)i * (hue_bar->h/6.0f) + 0.5f, hue_bar->w, (hue_bar->h/6.0f) + 0.5f), hue_colors[i], hue_colors[i], hue_colors[i+1], hue_colors[i+1]); } line_y = (float)(int)(hue_bar->y + hsva[0] * matrix->h + 0.5f); nk_stroke_line(o, hue_bar->x-1, line_y, hue_bar->x + hue_bar->w + 2, line_y, 1, nk_rgb(255,255,255)); /* draw alpha bar */ if (alpha_bar) { float alpha = NK_SATURATE((float)color.a/255.0f); line_y = (float)(int)(alpha_bar->y + (1.0f - alpha) * matrix->h + 0.5f); nk_fill_rect_multi_color(o, *alpha_bar, white, white, black, black); nk_stroke_line(o, alpha_bar->x-1, line_y, alpha_bar->x + alpha_bar->w + 2, line_y, 1, nk_rgb(255,255,255)); } /* draw color matrix */ temp = nk_hsv_f(hsva[0], 1.0f, 1.0f); nk_fill_rect_multi_color(o, *matrix, white, temp, temp, white); nk_fill_rect_multi_color(o, *matrix, black_trans, black_trans, black, black); /* draw cross-hair */ {struct nk_vec2 p; float S = hsva[1]; float V = hsva[2]; p.x = (float)(int)(matrix->x + S * matrix->w); p.y = (float)(int)(matrix->y + (1.0f - V) * matrix->h); nk_stroke_line(o, p.x - crosshair_size, p.y, p.x-2, p.y, 1.0f, white); nk_stroke_line(o, p.x + crosshair_size + 1, p.y, p.x+3, p.y, 1.0f, white); nk_stroke_line(o, p.x, p.y + crosshair_size + 1, p.x, p.y+3, 1.0f, white); nk_stroke_line(o, p.x, p.y - crosshair_size, p.x, p.y-2, 1.0f, white);} } NK_INTERN int nk_do_color_picker(nk_flags *state, struct nk_command_buffer *out, struct nk_color *color, enum nk_color_format fmt, struct nk_rect bounds, struct nk_vec2 padding, const struct nk_input *in, const struct nk_user_font *font) { int ret = 0; struct nk_rect matrix; struct nk_rect hue_bar; struct nk_rect alpha_bar; float bar_w; NK_ASSERT(out); NK_ASSERT(color); NK_ASSERT(state); NK_ASSERT(font); if (!out || !color || !state || !font) return ret; bar_w = font->height; bounds.x += padding.x; bounds.y += padding.x; bounds.w -= 2 * padding.x; bounds.h -= 2 * padding.y; matrix.x = bounds.x; matrix.y = bounds.y; matrix.h = bounds.h; matrix.w = bounds.w - (3 * padding.x + 2 * bar_w); hue_bar.w = bar_w; hue_bar.y = bounds.y; hue_bar.h = matrix.h; hue_bar.x = matrix.x + matrix.w + padding.x; alpha_bar.x = hue_bar.x + hue_bar.w + padding.x; alpha_bar.y = bounds.y; alpha_bar.w = bar_w; alpha_bar.h = matrix.h; ret = nk_color_picker_behavior(state, &bounds, &matrix, &hue_bar, (fmt == NK_RGBA) ? &alpha_bar:0, color, in); nk_draw_color_picker(out, &matrix, &hue_bar, (fmt == NK_RGBA) ? &alpha_bar:0, *color); return ret; } /* ============================================================== * * STYLE * * ===============================================================*/ NK_API void nk_style_default(struct nk_context *ctx){nk_style_from_table(ctx, 0);} #define NK_COLOR_MAP(NK_COLOR)\ NK_COLOR(NK_COLOR_TEXT, 175,175,175,255) \ NK_COLOR(NK_COLOR_WINDOW, 45, 45, 45, 255) \ NK_COLOR(NK_COLOR_HEADER, 40, 40, 40, 255) \ NK_COLOR(NK_COLOR_BORDER, 65, 65, 65, 255) \ NK_COLOR(NK_COLOR_BUTTON, 50, 50, 50, 255) \ NK_COLOR(NK_COLOR_BUTTON_HOVER, 40, 40, 40, 255) \ NK_COLOR(NK_COLOR_BUTTON_ACTIVE, 35, 35, 35, 255) \ NK_COLOR(NK_COLOR_TOGGLE, 100,100,100,255) \ NK_COLOR(NK_COLOR_TOGGLE_HOVER, 120,120,120,255) \ NK_COLOR(NK_COLOR_TOGGLE_CURSOR, 45, 45, 45, 255) \ NK_COLOR(NK_COLOR_SELECT, 45, 45, 45, 255) \ NK_COLOR(NK_COLOR_SELECT_ACTIVE, 35, 35, 35,255) \ NK_COLOR(NK_COLOR_SLIDER, 38, 38, 38, 255) \ NK_COLOR(NK_COLOR_SLIDER_CURSOR, 100,100,100,255) \ NK_COLOR(NK_COLOR_SLIDER_CURSOR_HOVER, 120,120,120,255) \ NK_COLOR(NK_COLOR_SLIDER_CURSOR_ACTIVE, 150,150,150,255) \ NK_COLOR(NK_COLOR_PROPERTY, 38, 38, 38, 255) \ NK_COLOR(NK_COLOR_EDIT, 38, 38, 38, 255) \ NK_COLOR(NK_COLOR_EDIT_CURSOR, 175,175,175,255) \ NK_COLOR(NK_COLOR_COMBO, 45, 45, 45, 255) \ NK_COLOR(NK_COLOR_CHART, 120,120,120,255) \ NK_COLOR(NK_COLOR_CHART_COLOR, 45, 45, 45, 255) \ NK_COLOR(NK_COLOR_CHART_COLOR_HIGHLIGHT,255, 0, 0, 255) \ NK_COLOR(NK_COLOR_SCROLLBAR, 40, 40, 40, 255) \ NK_COLOR(NK_COLOR_SCROLLBAR_CURSOR, 100,100,100,255) \ NK_COLOR(NK_COLOR_SCROLLBAR_CURSOR_HOVER,120,120,120,255) \ NK_COLOR(NK_COLOR_SCROLLBAR_CURSOR_ACTIVE,150,150,150,255) \ NK_COLOR(NK_COLOR_TAB_HEADER, 40, 40, 40,255) NK_GLOBAL const struct nk_color nk_default_color_style[NK_COLOR_COUNT] = { #define NK_COLOR(a,b,c,d,e) {b,c,d,e}, NK_COLOR_MAP(NK_COLOR) #undef NK_COLOR }; NK_GLOBAL const char *nk_color_names[NK_COLOR_COUNT] = { #define NK_COLOR(a,b,c,d,e) #a, NK_COLOR_MAP(NK_COLOR) #undef NK_COLOR }; NK_API const char *nk_style_get_color_by_name(enum nk_style_colors c) {return nk_color_names[c];} NK_API struct nk_style_item nk_style_item_image(struct nk_image img) {struct nk_style_item i; i.type = NK_STYLE_ITEM_IMAGE; i.data.image = img; return i;} NK_API struct nk_style_item nk_style_item_color(struct nk_color col) {struct nk_style_item i; i.type = NK_STYLE_ITEM_COLOR; i.data.color = col; return i;} NK_API struct nk_style_item nk_style_item_hide(void) {struct nk_style_item i; i.type = NK_STYLE_ITEM_COLOR; i.data.color = nk_rgba(0,0,0,0); return i;} NK_API void nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) { struct nk_style *style; struct nk_style_text *text; struct nk_style_button *button; struct nk_style_toggle *toggle; struct nk_style_selectable *select; struct nk_style_slider *slider; struct nk_style_progress *prog; struct nk_style_scrollbar *scroll; struct nk_style_edit *edit; struct nk_style_property *property; struct nk_style_combo *combo; struct nk_style_chart *chart; struct nk_style_tab *tab; struct nk_style_window *win; NK_ASSERT(ctx); if (!ctx) return; style = &ctx->style; table = (!table) ? nk_default_color_style: table; /* default text */ text = &style->text; text->color = table[NK_COLOR_TEXT]; text->padding = nk_vec2(4,4); /* default button */ button = &style->button; nk_zero_struct(*button); button->normal = nk_style_item_color(table[NK_COLOR_BUTTON]); button->hover = nk_style_item_color(table[NK_COLOR_BUTTON_HOVER]); button->active = nk_style_item_color(table[NK_COLOR_BUTTON_ACTIVE]); button->border_color = table[NK_COLOR_BORDER]; button->text_background = table[NK_COLOR_BUTTON]; button->text_normal = table[NK_COLOR_TEXT]; button->text_hover = table[NK_COLOR_TEXT]; button->text_active = table[NK_COLOR_TEXT]; button->padding = nk_vec2(2.0f,2.0f); button->image_padding = nk_vec2(0.0f,0.0f); button->touch_padding = nk_vec2(0.0f, 0.0f); button->userdata = nk_handle_ptr(0); button->text_alignment = NK_TEXT_CENTERED; button->border = 1.0f; button->rounding = 4.0f; button->draw_begin = 0; button->draw_end = 0; /* contextual button */ button = &style->contextual_button; nk_zero_struct(*button); button->normal = nk_style_item_color(table[NK_COLOR_WINDOW]); button->hover = nk_style_item_color(table[NK_COLOR_BUTTON_HOVER]); button->active = nk_style_item_color(table[NK_COLOR_BUTTON_ACTIVE]); button->border_color = table[NK_COLOR_WINDOW]; button->text_background = table[NK_COLOR_WINDOW]; button->text_normal = table[NK_COLOR_TEXT]; button->text_hover = table[NK_COLOR_TEXT]; button->text_active = table[NK_COLOR_TEXT]; button->padding = nk_vec2(2.0f,2.0f); button->touch_padding = nk_vec2(0.0f,0.0f); button->userdata = nk_handle_ptr(0); button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; button->draw_begin = 0; button->draw_end = 0; /* menu button */ button = &style->menu_button; nk_zero_struct(*button); button->normal = nk_style_item_color(table[NK_COLOR_WINDOW]); button->hover = nk_style_item_color(table[NK_COLOR_WINDOW]); button->active = nk_style_item_color(table[NK_COLOR_WINDOW]); button->border_color = table[NK_COLOR_WINDOW]; button->text_background = table[NK_COLOR_WINDOW]; button->text_normal = table[NK_COLOR_TEXT]; button->text_hover = table[NK_COLOR_TEXT]; button->text_active = table[NK_COLOR_TEXT]; button->padding = nk_vec2(2.0f,2.0f); button->touch_padding = nk_vec2(0.0f,0.0f); button->userdata = nk_handle_ptr(0); button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 1.0f; button->draw_begin = 0; button->draw_end = 0; /* checkbox toggle */ toggle = &style->checkbox; nk_zero_struct(*toggle); toggle->normal = nk_style_item_color(table[NK_COLOR_TOGGLE]); toggle->hover = nk_style_item_color(table[NK_COLOR_TOGGLE_HOVER]); toggle->active = nk_style_item_color(table[NK_COLOR_TOGGLE_HOVER]); toggle->cursor_normal = nk_style_item_color(table[NK_COLOR_TOGGLE_CURSOR]); toggle->cursor_hover = nk_style_item_color(table[NK_COLOR_TOGGLE_CURSOR]); toggle->userdata = nk_handle_ptr(0); toggle->text_background = table[NK_COLOR_WINDOW]; toggle->text_normal = table[NK_COLOR_TEXT]; toggle->text_hover = table[NK_COLOR_TEXT]; toggle->text_active = table[NK_COLOR_TEXT]; toggle->padding = nk_vec2(2.0f, 2.0f); toggle->touch_padding = nk_vec2(0,0); toggle->border_color = nk_rgba(0,0,0,0); toggle->border = 0.0f; toggle->spacing = 4; /* option toggle */ toggle = &style->option; nk_zero_struct(*toggle); toggle->normal = nk_style_item_color(table[NK_COLOR_TOGGLE]); toggle->hover = nk_style_item_color(table[NK_COLOR_TOGGLE_HOVER]); toggle->active = nk_style_item_color(table[NK_COLOR_TOGGLE_HOVER]); toggle->cursor_normal = nk_style_item_color(table[NK_COLOR_TOGGLE_CURSOR]); toggle->cursor_hover = nk_style_item_color(table[NK_COLOR_TOGGLE_CURSOR]); toggle->userdata = nk_handle_ptr(0); toggle->text_background = table[NK_COLOR_WINDOW]; toggle->text_normal = table[NK_COLOR_TEXT]; toggle->text_hover = table[NK_COLOR_TEXT]; toggle->text_active = table[NK_COLOR_TEXT]; toggle->padding = nk_vec2(3.0f, 3.0f); toggle->touch_padding = nk_vec2(0,0); toggle->border_color = nk_rgba(0,0,0,0); toggle->border = 0.0f; toggle->spacing = 4; /* selectable */ select = &style->selectable; nk_zero_struct(*select); select->normal = nk_style_item_color(table[NK_COLOR_SELECT]); select->hover = nk_style_item_color(table[NK_COLOR_SELECT]); select->pressed = nk_style_item_color(table[NK_COLOR_SELECT]); select->normal_active = nk_style_item_color(table[NK_COLOR_SELECT_ACTIVE]); select->hover_active = nk_style_item_color(table[NK_COLOR_SELECT_ACTIVE]); select->pressed_active = nk_style_item_color(table[NK_COLOR_SELECT_ACTIVE]); select->text_normal = table[NK_COLOR_TEXT]; select->text_hover = table[NK_COLOR_TEXT]; select->text_pressed = table[NK_COLOR_TEXT]; select->text_normal_active = table[NK_COLOR_TEXT]; select->text_hover_active = table[NK_COLOR_TEXT]; select->text_pressed_active = table[NK_COLOR_TEXT]; select->padding = nk_vec2(2.0f,2.0f); select->touch_padding = nk_vec2(0,0); select->userdata = nk_handle_ptr(0); select->rounding = 0.0f; select->draw_begin = 0; select->draw_end = 0; /* slider */ slider = &style->slider; nk_zero_struct(*slider); slider->normal = nk_style_item_hide(); slider->hover = nk_style_item_hide(); slider->active = nk_style_item_hide(); slider->bar_normal = table[NK_COLOR_SLIDER]; slider->bar_hover = table[NK_COLOR_SLIDER]; slider->bar_active = table[NK_COLOR_SLIDER]; slider->bar_filled = table[NK_COLOR_SLIDER_CURSOR]; slider->cursor_normal = nk_style_item_color(table[NK_COLOR_SLIDER_CURSOR]); slider->cursor_hover = nk_style_item_color(table[NK_COLOR_SLIDER_CURSOR_HOVER]); slider->cursor_active = nk_style_item_color(table[NK_COLOR_SLIDER_CURSOR_ACTIVE]); slider->inc_symbol = NK_SYMBOL_TRIANGLE_RIGHT; slider->dec_symbol = NK_SYMBOL_TRIANGLE_LEFT; slider->cursor_size = nk_vec2(16,16); slider->padding = nk_vec2(2,2); slider->spacing = nk_vec2(2,2); slider->userdata = nk_handle_ptr(0); slider->show_buttons = nk_false; slider->bar_height = 8; slider->rounding = 0; slider->draw_begin = 0; slider->draw_end = 0; /* slider buttons */ button = &style->slider.inc_button; button->normal = nk_style_item_color(nk_rgb(40,40,40)); button->hover = nk_style_item_color(nk_rgb(42,42,42)); button->active = nk_style_item_color(nk_rgb(44,44,44)); button->border_color = nk_rgb(65,65,65); button->text_background = nk_rgb(40,40,40); button->text_normal = nk_rgb(175,175,175); button->text_hover = nk_rgb(175,175,175); button->text_active = nk_rgb(175,175,175); button->padding = nk_vec2(8.0f,8.0f); button->touch_padding = nk_vec2(0.0f,0.0f); button->userdata = nk_handle_ptr(0); button->text_alignment = NK_TEXT_CENTERED; button->border = 1.0f; button->rounding = 0.0f; button->draw_begin = 0; button->draw_end = 0; style->slider.dec_button = style->slider.inc_button; /* progressbar */ prog = &style->progress; nk_zero_struct(*prog); prog->normal = nk_style_item_color(table[NK_COLOR_SLIDER]); prog->hover = nk_style_item_color(table[NK_COLOR_SLIDER]); prog->active = nk_style_item_color(table[NK_COLOR_SLIDER]); prog->cursor_normal = nk_style_item_color(table[NK_COLOR_SLIDER_CURSOR]); prog->cursor_hover = nk_style_item_color(table[NK_COLOR_SLIDER_CURSOR_HOVER]); prog->cursor_active = nk_style_item_color(table[NK_COLOR_SLIDER_CURSOR_ACTIVE]); prog->border_color = nk_rgba(0,0,0,0); prog->cursor_border_color = nk_rgba(0,0,0,0); prog->userdata = nk_handle_ptr(0); prog->padding = nk_vec2(4,4); prog->rounding = 0; prog->border = 0; prog->cursor_rounding = 0; prog->cursor_border = 0; prog->draw_begin = 0; prog->draw_end = 0; /* scrollbars */ scroll = &style->scrollh; nk_zero_struct(*scroll); scroll->normal = nk_style_item_color(table[NK_COLOR_SCROLLBAR]); scroll->hover = nk_style_item_color(table[NK_COLOR_SCROLLBAR]); scroll->active = nk_style_item_color(table[NK_COLOR_SCROLLBAR]); scroll->cursor_normal = nk_style_item_color(table[NK_COLOR_SCROLLBAR_CURSOR]); scroll->cursor_hover = nk_style_item_color(table[NK_COLOR_SCROLLBAR_CURSOR_HOVER]); scroll->cursor_active = nk_style_item_color(table[NK_COLOR_SCROLLBAR_CURSOR_ACTIVE]); scroll->dec_symbol = NK_SYMBOL_CIRCLE_SOLID; scroll->inc_symbol = NK_SYMBOL_CIRCLE_SOLID; scroll->userdata = nk_handle_ptr(0); scroll->border_color = table[NK_COLOR_BORDER]; scroll->cursor_border_color = table[NK_COLOR_BORDER]; scroll->padding = nk_vec2(0,0); scroll->show_buttons = nk_false; scroll->border = 0; scroll->rounding = 0; scroll->border_cursor = 0; scroll->rounding_cursor = 0; scroll->draw_begin = 0; scroll->draw_end = 0; style->scrollv = style->scrollh; /* scrollbars buttons */ button = &style->scrollh.inc_button; button->normal = nk_style_item_color(nk_rgb(40,40,40)); button->hover = nk_style_item_color(nk_rgb(42,42,42)); button->active = nk_style_item_color(nk_rgb(44,44,44)); button->border_color = nk_rgb(65,65,65); button->text_background = nk_rgb(40,40,40); button->text_normal = nk_rgb(175,175,175); button->text_hover = nk_rgb(175,175,175); button->text_active = nk_rgb(175,175,175); button->padding = nk_vec2(4.0f,4.0f); button->touch_padding = nk_vec2(0.0f,0.0f); button->userdata = nk_handle_ptr(0); button->text_alignment = NK_TEXT_CENTERED; button->border = 1.0f; button->rounding = 0.0f; button->draw_begin = 0; button->draw_end = 0; style->scrollh.dec_button = style->scrollh.inc_button; style->scrollv.inc_button = style->scrollh.inc_button; style->scrollv.dec_button = style->scrollh.inc_button; /* edit */ edit = &style->edit; nk_zero_struct(*edit); edit->normal = nk_style_item_color(table[NK_COLOR_EDIT]); edit->hover = nk_style_item_color(table[NK_COLOR_EDIT]); edit->active = nk_style_item_color(table[NK_COLOR_EDIT]); edit->cursor_normal = table[NK_COLOR_TEXT]; edit->cursor_hover = table[NK_COLOR_TEXT]; edit->cursor_text_normal= table[NK_COLOR_EDIT]; edit->cursor_text_hover = table[NK_COLOR_EDIT]; edit->border_color = table[NK_COLOR_BORDER]; edit->text_normal = table[NK_COLOR_TEXT]; edit->text_hover = table[NK_COLOR_TEXT]; edit->text_active = table[NK_COLOR_TEXT]; edit->selected_normal = table[NK_COLOR_TEXT]; edit->selected_hover = table[NK_COLOR_TEXT]; edit->selected_text_normal = table[NK_COLOR_EDIT]; edit->selected_text_hover = table[NK_COLOR_EDIT]; edit->scrollbar_size = nk_vec2(10,10); edit->scrollbar = style->scrollv; edit->padding = nk_vec2(4,4); edit->row_padding = 2; edit->cursor_size = 4; edit->border = 1; edit->rounding = 0; /* property */ property = &style->property; nk_zero_struct(*property); property->normal = nk_style_item_color(table[NK_COLOR_PROPERTY]); property->hover = nk_style_item_color(table[NK_COLOR_PROPERTY]); property->active = nk_style_item_color(table[NK_COLOR_PROPERTY]); property->border_color = table[NK_COLOR_BORDER]; property->label_normal = table[NK_COLOR_TEXT]; property->label_hover = table[NK_COLOR_TEXT]; property->label_active = table[NK_COLOR_TEXT]; property->sym_left = NK_SYMBOL_TRIANGLE_LEFT; property->sym_right = NK_SYMBOL_TRIANGLE_RIGHT; property->userdata = nk_handle_ptr(0); property->padding = nk_vec2(4,4); property->border = 1; property->rounding = 10; property->draw_begin = 0; property->draw_end = 0; /* property buttons */ button = &style->property.dec_button; nk_zero_struct(*button); button->normal = nk_style_item_color(table[NK_COLOR_PROPERTY]); button->hover = nk_style_item_color(table[NK_COLOR_PROPERTY]); button->active = nk_style_item_color(table[NK_COLOR_PROPERTY]); button->border_color = nk_rgba(0,0,0,0); button->text_background = table[NK_COLOR_PROPERTY]; button->text_normal = table[NK_COLOR_TEXT]; button->text_hover = table[NK_COLOR_TEXT]; button->text_active = table[NK_COLOR_TEXT]; button->padding = nk_vec2(0.0f,0.0f); button->touch_padding = nk_vec2(0.0f,0.0f); button->userdata = nk_handle_ptr(0); button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; button->draw_begin = 0; button->draw_end = 0; style->property.inc_button = style->property.dec_button; /* property edit */ edit = &style->property.edit; nk_zero_struct(*edit); edit->normal = nk_style_item_color(table[NK_COLOR_PROPERTY]); edit->hover = nk_style_item_color(table[NK_COLOR_PROPERTY]); edit->active = nk_style_item_color(table[NK_COLOR_PROPERTY]); edit->border_color = nk_rgba(0,0,0,0); edit->cursor_normal = table[NK_COLOR_TEXT]; edit->cursor_hover = table[NK_COLOR_TEXT]; edit->cursor_text_normal= table[NK_COLOR_EDIT]; edit->cursor_text_hover = table[NK_COLOR_EDIT]; edit->text_normal = table[NK_COLOR_TEXT]; edit->text_hover = table[NK_COLOR_TEXT]; edit->text_active = table[NK_COLOR_TEXT]; edit->selected_normal = table[NK_COLOR_TEXT]; edit->selected_hover = table[NK_COLOR_TEXT]; edit->selected_text_normal = table[NK_COLOR_EDIT]; edit->selected_text_hover = table[NK_COLOR_EDIT]; edit->padding = nk_vec2(0,0); edit->cursor_size = 8; edit->border = 0; edit->rounding = 0; /* chart */ chart = &style->chart; nk_zero_struct(*chart); chart->background = nk_style_item_color(table[NK_COLOR_CHART]); chart->border_color = table[NK_COLOR_BORDER]; chart->selected_color = table[NK_COLOR_CHART_COLOR_HIGHLIGHT]; chart->color = table[NK_COLOR_CHART_COLOR]; chart->padding = nk_vec2(4,4); chart->border = 0; chart->rounding = 0; /* combo */ combo = &style->combo; combo->normal = nk_style_item_color(table[NK_COLOR_COMBO]); combo->hover = nk_style_item_color(table[NK_COLOR_COMBO]); combo->active = nk_style_item_color(table[NK_COLOR_COMBO]); combo->border_color = table[NK_COLOR_BORDER]; combo->label_normal = table[NK_COLOR_TEXT]; combo->label_hover = table[NK_COLOR_TEXT]; combo->label_active = table[NK_COLOR_TEXT]; combo->sym_normal = NK_SYMBOL_TRIANGLE_DOWN; combo->sym_hover = NK_SYMBOL_TRIANGLE_DOWN; combo->sym_active = NK_SYMBOL_TRIANGLE_DOWN; combo->content_padding = nk_vec2(4,4); combo->button_padding = nk_vec2(0,4); combo->spacing = nk_vec2(4,0); combo->border = 1; combo->rounding = 0; /* combo button */ button = &style->combo.button; nk_zero_struct(*button); button->normal = nk_style_item_color(table[NK_COLOR_COMBO]); button->hover = nk_style_item_color(table[NK_COLOR_COMBO]); button->active = nk_style_item_color(table[NK_COLOR_COMBO]); button->border_color = nk_rgba(0,0,0,0); button->text_background = table[NK_COLOR_COMBO]; button->text_normal = table[NK_COLOR_TEXT]; button->text_hover = table[NK_COLOR_TEXT]; button->text_active = table[NK_COLOR_TEXT]; button->padding = nk_vec2(2.0f,2.0f); button->touch_padding = nk_vec2(0.0f,0.0f); button->userdata = nk_handle_ptr(0); button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; button->draw_begin = 0; button->draw_end = 0; /* tab */ tab = &style->tab; tab->background = nk_style_item_color(table[NK_COLOR_TAB_HEADER]); tab->border_color = table[NK_COLOR_BORDER]; tab->text = table[NK_COLOR_TEXT]; tab->sym_minimize = NK_SYMBOL_TRIANGLE_RIGHT; tab->sym_maximize = NK_SYMBOL_TRIANGLE_DOWN; tab->padding = nk_vec2(4,4); tab->spacing = nk_vec2(4,4); tab->indent = 10.0f; tab->border = 1; tab->rounding = 0; /* tab button */ button = &style->tab.tab_minimize_button; nk_zero_struct(*button); button->normal = nk_style_item_color(table[NK_COLOR_TAB_HEADER]); button->hover = nk_style_item_color(table[NK_COLOR_TAB_HEADER]); button->active = nk_style_item_color(table[NK_COLOR_TAB_HEADER]); button->border_color = nk_rgba(0,0,0,0); button->text_background = table[NK_COLOR_TAB_HEADER]; button->text_normal = table[NK_COLOR_TEXT]; button->text_hover = table[NK_COLOR_TEXT]; button->text_active = table[NK_COLOR_TEXT]; button->padding = nk_vec2(2.0f,2.0f); button->touch_padding = nk_vec2(0.0f,0.0f); button->userdata = nk_handle_ptr(0); button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; button->draw_begin = 0; button->draw_end = 0; style->tab.tab_maximize_button =*button; /* node button */ button = &style->tab.node_minimize_button; nk_zero_struct(*button); button->normal = nk_style_item_color(table[NK_COLOR_WINDOW]); button->hover = nk_style_item_color(table[NK_COLOR_WINDOW]); button->active = nk_style_item_color(table[NK_COLOR_WINDOW]); button->border_color = nk_rgba(0,0,0,0); button->text_background = table[NK_COLOR_TAB_HEADER]; button->text_normal = table[NK_COLOR_TEXT]; button->text_hover = table[NK_COLOR_TEXT]; button->text_active = table[NK_COLOR_TEXT]; button->padding = nk_vec2(2.0f,2.0f); button->touch_padding = nk_vec2(0.0f,0.0f); button->userdata = nk_handle_ptr(0); button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; button->draw_begin = 0; button->draw_end = 0; style->tab.node_maximize_button =*button; /* window header */ win = &style->window; win->header.align = NK_HEADER_RIGHT; win->header.close_symbol = NK_SYMBOL_X; win->header.minimize_symbol = NK_SYMBOL_MINUS; win->header.maximize_symbol = NK_SYMBOL_PLUS; win->header.normal = nk_style_item_color(table[NK_COLOR_HEADER]); win->header.hover = nk_style_item_color(table[NK_COLOR_HEADER]); win->header.active = nk_style_item_color(table[NK_COLOR_HEADER]); win->header.label_normal = table[NK_COLOR_TEXT]; win->header.label_hover = table[NK_COLOR_TEXT]; win->header.label_active = table[NK_COLOR_TEXT]; win->header.label_padding = nk_vec2(4,4); win->header.padding = nk_vec2(4,4); win->header.spacing = nk_vec2(0,0); /* window header close button */ button = &style->window.header.close_button; nk_zero_struct(*button); button->normal = nk_style_item_color(table[NK_COLOR_HEADER]); button->hover = nk_style_item_color(table[NK_COLOR_HEADER]); button->active = nk_style_item_color(table[NK_COLOR_HEADER]); button->border_color = nk_rgba(0,0,0,0); button->text_background = table[NK_COLOR_HEADER]; button->text_normal = table[NK_COLOR_TEXT]; button->text_hover = table[NK_COLOR_TEXT]; button->text_active = table[NK_COLOR_TEXT]; button->padding = nk_vec2(0.0f,0.0f); button->touch_padding = nk_vec2(0.0f,0.0f); button->userdata = nk_handle_ptr(0); button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; button->draw_begin = 0; button->draw_end = 0; /* window header minimize button */ button = &style->window.header.minimize_button; nk_zero_struct(*button); button->normal = nk_style_item_color(table[NK_COLOR_HEADER]); button->hover = nk_style_item_color(table[NK_COLOR_HEADER]); button->active = nk_style_item_color(table[NK_COLOR_HEADER]); button->border_color = nk_rgba(0,0,0,0); button->text_background = table[NK_COLOR_HEADER]; button->text_normal = table[NK_COLOR_TEXT]; button->text_hover = table[NK_COLOR_TEXT]; button->text_active = table[NK_COLOR_TEXT]; button->padding = nk_vec2(0.0f,0.0f); button->touch_padding = nk_vec2(0.0f,0.0f); button->userdata = nk_handle_ptr(0); button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; button->draw_begin = 0; button->draw_end = 0; /* window */ win->background = table[NK_COLOR_WINDOW]; win->fixed_background = nk_style_item_color(table[NK_COLOR_WINDOW]); win->border_color = table[NK_COLOR_BORDER]; win->combo_border_color = table[NK_COLOR_BORDER]; win->contextual_border_color = table[NK_COLOR_BORDER]; win->menu_border_color = table[NK_COLOR_BORDER]; win->group_border_color = table[NK_COLOR_BORDER]; win->tooltip_border_color = table[NK_COLOR_BORDER]; win->scaler = nk_style_item_color(table[NK_COLOR_TEXT]); win->rounding = 0.0f; win->spacing = nk_vec2(4,4); win->scrollbar_size = nk_vec2(10,10); win->min_size = nk_vec2(64,64); win->combo_border = 1.0f; win->contextual_border = 1.0f; win->menu_border = 1.0f; win->group_border = 1.0f; win->tooltip_border = 1.0f; win->border = 2.0f; win->padding = nk_vec2(4,4); win->group_padding = nk_vec2(4,4); win->popup_padding = nk_vec2(4,4); win->combo_padding = nk_vec2(4,4); win->contextual_padding = nk_vec2(4,4); win->menu_padding = nk_vec2(4,4); win->tooltip_padding = nk_vec2(4,4); } NK_API void nk_style_set_font(struct nk_context *ctx, const struct nk_user_font *font) { struct nk_style *style; NK_ASSERT(ctx); if (!ctx) return; style = &ctx->style; style->font = font; ctx->stacks.fonts.head = 0; } NK_API int nk_style_push_font(struct nk_context *ctx, struct nk_user_font *font) { struct nk_config_stack_user_font *font_stack; struct nk_config_stack_user_font_element *element; NK_ASSERT(ctx); if (!ctx) return 0; font_stack = &ctx->stacks.fonts; NK_ASSERT(font_stack->head < (int)NK_LEN(font_stack->elements)); if (font_stack->head >= (int)NK_LEN(font_stack->elements)) return 0; element = &font_stack->elements[font_stack->head++]; element->address = &ctx->style.font; element->old_value = ctx->style.font; ctx->style.font = font; return 1; } NK_API int nk_style_pop_font(struct nk_context *ctx) { struct nk_config_stack_user_font *font_stack; struct nk_config_stack_user_font_element *element; NK_ASSERT(ctx); if (!ctx) return 0; font_stack = &ctx->stacks.fonts; NK_ASSERT(font_stack->head > 0); if (font_stack->head < 1) return 0; element = &font_stack->elements[--font_stack->head]; *element->address = element->old_value; return 1; } #define NK_STYLE_PUSH_IMPLEMENATION(prefix, type, stack) \ nk_style_push_##type(struct nk_context *ctx, prefix##_##type *address, prefix##_##type value)\ {\ struct nk_config_stack_##type * type_stack;\ struct nk_config_stack_##type##_element *element;\ NK_ASSERT(ctx);\ if (!ctx) return 0;\ type_stack = &ctx->stacks.stack;\ NK_ASSERT(type_stack->head < (int)NK_LEN(type_stack->elements));\ if (type_stack->head >= (int)NK_LEN(type_stack->elements))\ return 0;\ element = &type_stack->elements[type_stack->head++];\ element->address = address;\ element->old_value = *address;\ *address = value;\ return 1;\ } #define NK_STYLE_POP_IMPLEMENATION(type, stack) \ nk_style_pop_##type(struct nk_context *ctx)\ {\ struct nk_config_stack_##type *type_stack;\ struct nk_config_stack_##type##_element *element;\ NK_ASSERT(ctx);\ if (!ctx) return 0;\ type_stack = &ctx->stacks.stack;\ NK_ASSERT(type_stack->head > 0);\ if (type_stack->head < 1)\ return 0;\ element = &type_stack->elements[--type_stack->head];\ *element->address = element->old_value;\ return 1;\ } NK_API int NK_STYLE_PUSH_IMPLEMENATION(struct nk, style_item, style_items) NK_API int NK_STYLE_PUSH_IMPLEMENATION(nk,float, floats) NK_API int NK_STYLE_PUSH_IMPLEMENATION(struct nk, vec2, vectors) NK_API int NK_STYLE_PUSH_IMPLEMENATION(nk,flags, flags) NK_API int NK_STYLE_PUSH_IMPLEMENATION(struct nk,color, colors) NK_API int NK_STYLE_POP_IMPLEMENATION(style_item, style_items) NK_API int NK_STYLE_POP_IMPLEMENATION(float,floats) NK_API int NK_STYLE_POP_IMPLEMENATION(vec2, vectors) NK_API int NK_STYLE_POP_IMPLEMENATION(flags,flags) NK_API int NK_STYLE_POP_IMPLEMENATION(color,colors) NK_API int nk_style_set_cursor(struct nk_context *ctx, enum nk_style_cursor c) { struct nk_style *style; NK_ASSERT(ctx); if (!ctx) return 0; style = &ctx->style; if (style->cursors[c]) { style->cursor_active = style->cursors[c]; return 1; } return 0; } NK_API void nk_style_show_cursor(struct nk_context *ctx) { ctx->style.cursor_visible = nk_true; } NK_API void nk_style_hide_cursor(struct nk_context *ctx) { ctx->style.cursor_visible = nk_false; } NK_API void nk_style_load_cursor(struct nk_context *ctx, enum nk_style_cursor cursor, const struct nk_cursor *c) { struct nk_style *style; NK_ASSERT(ctx); if (!ctx) return; style = &ctx->style; style->cursors[cursor] = c; } NK_API void nk_style_load_all_cursors(struct nk_context *ctx, struct nk_cursor *cursors) { int i = 0; struct nk_style *style; NK_ASSERT(ctx); if (!ctx) return; style = &ctx->style; for (i = 0; i < NK_CURSOR_COUNT; ++i) style->cursors[i] = &cursors[i]; style->cursor_visible = nk_true; } /* =============================================================== * * POOL * * ===============================================================*/ NK_INTERN void nk_pool_init(struct nk_pool *pool, struct nk_allocator *alloc, unsigned int capacity) { nk_zero(pool, sizeof(*pool)); pool->alloc = *alloc; pool->capacity = capacity; pool->type = NK_BUFFER_DYNAMIC; pool->pages = 0; } NK_INTERN void nk_pool_free(struct nk_pool *pool) { struct nk_page *next; struct nk_page *iter = pool->pages; if (!pool) return; if (pool->type == NK_BUFFER_FIXED) return; while (iter) { next = iter->next; pool->alloc.free(pool->alloc.userdata, iter); iter = next; } } NK_INTERN void nk_pool_init_fixed(struct nk_pool *pool, void *memory, nk_size size) { nk_zero(pool, sizeof(*pool)); NK_ASSERT(size >= sizeof(struct nk_page)); if (size < sizeof(struct nk_page)) return; pool->capacity = (unsigned)(size - sizeof(struct nk_page)) / sizeof(struct nk_page_element); pool->pages = (struct nk_page*)memory; pool->type = NK_BUFFER_FIXED; pool->size = size; } NK_INTERN struct nk_page_element* nk_pool_alloc(struct nk_pool *pool) { if (!pool->pages || pool->pages->size >= pool->capacity) { /* allocate new page */ struct nk_page *page; if (pool->type == NK_BUFFER_FIXED) { if (!pool->pages) { NK_ASSERT(pool->pages); return 0; } NK_ASSERT(pool->pages->size < pool->capacity); return 0; } else { nk_size size = sizeof(struct nk_page); size += NK_POOL_DEFAULT_CAPACITY * sizeof(union nk_page_data); page = (struct nk_page*)pool->alloc.alloc(pool->alloc.userdata,0, size); page->next = pool->pages; pool->pages = page; page->size = 0; } } return &pool->pages->win[pool->pages->size++]; } /* =============================================================== * * CONTEXT * * ===============================================================*/ NK_INTERN void* nk_create_window(struct nk_context *ctx); NK_INTERN void nk_remove_window(struct nk_context*, struct nk_window*); NK_INTERN void nk_free_window(struct nk_context *ctx, struct nk_window *win); NK_INTERN void nk_free_table(struct nk_context *ctx, struct nk_table *tbl); NK_INTERN void nk_remove_table(struct nk_window *win, struct nk_table *tbl); NK_INTERN void nk_setup(struct nk_context *ctx, const struct nk_user_font *font) { NK_ASSERT(ctx); if (!ctx) return; nk_zero_struct(*ctx); nk_style_default(ctx); ctx->seq = 1; if (font) ctx->style.font = font; #ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT nk_draw_list_init(&ctx->draw_list); #endif } #ifdef NK_INCLUDE_DEFAULT_ALLOCATOR NK_API int nk_init_default(struct nk_context *ctx, const struct nk_user_font *font) { struct nk_allocator alloc; alloc.userdata.ptr = 0; alloc.alloc = nk_malloc; alloc.free = nk_mfree; return nk_init(ctx, &alloc, font); } #endif NK_API int nk_init_fixed(struct nk_context *ctx, void *memory, nk_size size, const struct nk_user_font *font) { NK_ASSERT(memory); if (!memory) return 0; nk_setup(ctx, font); nk_buffer_init_fixed(&ctx->memory, memory, size); ctx->use_pool = nk_false; return 1; } NK_API int nk_init_custom(struct nk_context *ctx, struct nk_buffer *cmds, struct nk_buffer *pool, const struct nk_user_font *font) { NK_ASSERT(cmds); NK_ASSERT(pool); if (!cmds || !pool) return 0; nk_setup(ctx, font); ctx->memory = *cmds; if (pool->type == NK_BUFFER_FIXED) { /* take memory from buffer and alloc fixed pool */ nk_pool_init_fixed(&ctx->pool, pool->memory.ptr, pool->memory.size); } else { /* create dynamic pool from buffer allocator */ struct nk_allocator *alloc = &pool->pool; nk_pool_init(&ctx->pool, alloc, NK_POOL_DEFAULT_CAPACITY); } ctx->use_pool = nk_true; return 1; } NK_API int nk_init(struct nk_context *ctx, struct nk_allocator *alloc, const struct nk_user_font *font) { NK_ASSERT(alloc); if (!alloc) return 0; nk_setup(ctx, font); nk_buffer_init(&ctx->memory, alloc, NK_DEFAULT_COMMAND_BUFFER_SIZE); nk_pool_init(&ctx->pool, alloc, NK_POOL_DEFAULT_CAPACITY); ctx->use_pool = nk_true; return 1; } #ifdef NK_INCLUDE_COMMAND_USERDATA NK_API void nk_set_user_data(struct nk_context *ctx, nk_handle handle) { if (!ctx) return; ctx->userdata = handle; if (ctx->current) ctx->current->buffer.userdata = handle; } #endif NK_API void nk_free(struct nk_context *ctx) { NK_ASSERT(ctx); if (!ctx) return; nk_buffer_free(&ctx->memory); if (ctx->use_pool) { nk_pool_free(&ctx->pool); } nk_zero(&ctx->input, sizeof(ctx->input)); nk_zero(&ctx->style, sizeof(ctx->style)); nk_zero(&ctx->memory, sizeof(ctx->memory)); ctx->seq = 0; ctx->build = 0; ctx->begin = 0; ctx->end = 0; ctx->active = 0; ctx->current = 0; ctx->freelist = 0; ctx->count = 0; } NK_API void nk_clear(struct nk_context *ctx) { struct nk_window *iter; struct nk_window *next; NK_ASSERT(ctx); if (!ctx) return; if (ctx->use_pool) nk_buffer_clear(&ctx->memory); else nk_buffer_reset(&ctx->memory, NK_BUFFER_FRONT); ctx->build = 0; ctx->memory.calls = 0; ctx->last_widget_state = 0; ctx->style.cursor_active = ctx->style.cursors[NK_CURSOR_ARROW]; NK_MEMSET(&ctx->overlay, 0, sizeof(ctx->overlay)); #ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT nk_draw_list_clear(&ctx->draw_list); #endif /* garbage collector */ iter = ctx->begin; while (iter) { /* make sure minimized windows do not get removed */ if (iter->flags & NK_WINDOW_MINIMIZED) { iter = iter->next; continue; } /* free unused popup windows */ if (iter->popup.win && iter->popup.win->seq != ctx->seq) { nk_free_window(ctx, iter->popup.win); iter->popup.win = 0; } /* remove unused window state tables */ {struct nk_table *n, *it = iter->tables; while (it) { n = it->next; if (it->seq != ctx->seq) { nk_remove_table(iter, it); nk_zero(it, sizeof(union nk_page_data)); nk_free_table(ctx, it); if (it == iter->tables) iter->tables = n; } it = n; }} /* window itself is not used anymore so free */ if (iter->seq != ctx->seq || iter->flags & NK_WINDOW_CLOSED) { next = iter->next; nk_remove_window(ctx, iter); nk_free_window(ctx, iter); iter = next; } else iter = iter->next; } ctx->seq++; } /* ---------------------------------------------------------------- * * BUFFERING * * ---------------------------------------------------------------*/ NK_INTERN void nk_start_buffer(struct nk_context *ctx, struct nk_command_buffer *buffer) { NK_ASSERT(ctx); NK_ASSERT(buffer); if (!ctx || !buffer) return; buffer->begin = ctx->memory.allocated; buffer->end = buffer->begin; buffer->last = buffer->begin; buffer->clip = nk_null_rect; } NK_INTERN void nk_start(struct nk_context *ctx, struct nk_window *win) { NK_ASSERT(ctx); NK_ASSERT(win); nk_start_buffer(ctx, &win->buffer); } NK_INTERN void nk_start_popup(struct nk_context *ctx, struct nk_window *win) { struct nk_popup_buffer *buf; struct nk_panel *iter; NK_ASSERT(ctx); NK_ASSERT(win); if (!ctx || !win) return; /* make sure to use the correct popup buffer*/ iter = win->layout; while (iter->parent) iter = iter->parent; /* save buffer fill state for popup */ buf = &iter->popup_buffer; buf->begin = win->buffer.end; buf->end = win->buffer.end; buf->parent = win->buffer.last; buf->last = buf->begin; buf->active = nk_true; } NK_INTERN void nk_finish_popup(struct nk_context *ctx, struct nk_window *win) { struct nk_popup_buffer *buf; struct nk_panel *iter; NK_ASSERT(ctx); NK_ASSERT(win); if (!ctx || !win) return; /* make sure to use the correct popup buffer*/ iter = win->layout; while (iter->parent) iter = iter->parent; buf = &iter->popup_buffer; buf->last = win->buffer.last; buf->end = win->buffer.end; } NK_INTERN void nk_finish_buffer(struct nk_context *ctx, struct nk_command_buffer *buffer) { NK_ASSERT(ctx); NK_ASSERT(buffer); if (!ctx || !buffer) return; buffer->end = ctx->memory.allocated; } NK_INTERN void nk_finish(struct nk_context *ctx, struct nk_window *win) { struct nk_popup_buffer *buf; struct nk_command *parent_last; struct nk_command *sublast; struct nk_command *last; void *memory; NK_ASSERT(ctx); NK_ASSERT(win); if (!ctx || !win) return; nk_finish_buffer(ctx, &win->buffer); if (!win->layout->popup_buffer.active) return; /* from here on is for popup window buffer handling */ buf = &win->layout->popup_buffer; memory = ctx->memory.memory.ptr; /* redirect the sub-window buffer to the end of the window command buffer */ parent_last = nk_ptr_add(struct nk_command, memory, buf->parent); sublast = nk_ptr_add(struct nk_command, memory, buf->last); last = nk_ptr_add(struct nk_command, memory, win->buffer.last); parent_last->next = buf->end; sublast->next = last->next; last->next = buf->begin; win->buffer.last = buf->last; win->buffer.end = buf->end; buf->active = nk_false; } NK_INTERN void nk_build(struct nk_context *ctx) { struct nk_window *iter; struct nk_window *next; struct nk_command *cmd; nk_byte *buffer; /* draw cursor overlay */ if (!ctx->style.cursor_active) ctx->style.cursor_active = ctx->style.cursors[NK_CURSOR_ARROW]; if (ctx->style.cursor_active && !ctx->input.mouse.grabbed && ctx->style.cursor_visible) { struct nk_rect mouse_bounds; const struct nk_cursor *cursor = ctx->style.cursor_active; nk_command_buffer_init(&ctx->overlay, &ctx->memory, NK_CLIPPING_OFF); nk_start_buffer(ctx, &ctx->overlay); mouse_bounds.x = ctx->input.mouse.pos.x - cursor->offset.x; mouse_bounds.y = ctx->input.mouse.pos.y - cursor->offset.y; mouse_bounds.w = cursor->size.x; mouse_bounds.h = cursor->size.y; nk_draw_image(&ctx->overlay, mouse_bounds, &cursor->img, nk_white); nk_finish_buffer(ctx, &ctx->overlay); } /* build one big draw command list out of all buffers */ iter = ctx->begin; buffer = (nk_byte*)ctx->memory.memory.ptr; while (iter != 0) { next = iter->next; if (iter->buffer.last == iter->buffer.begin || (iter->flags & NK_WINDOW_HIDDEN)) { iter = next; continue; } cmd = nk_ptr_add(struct nk_command, buffer, iter->buffer.last); while (next && ((next->buffer.last == next->buffer.begin) || (next->flags & NK_WINDOW_HIDDEN))) next = next->next; /* skip empty command buffers */ if (next) { cmd->next = next->buffer.begin; } else { if (ctx->overlay.end != ctx->overlay.begin) cmd->next = ctx->overlay.begin; else cmd->next = ctx->memory.allocated; } iter = next; } } NK_API const struct nk_command* nk__begin(struct nk_context *ctx) { struct nk_window *iter; nk_byte *buffer; NK_ASSERT(ctx); if (!ctx) return 0; if (!ctx->count) return 0; buffer = (nk_byte*)ctx->memory.memory.ptr; if (!ctx->build) { nk_build(ctx); ctx->build = nk_true; } iter = ctx->begin; while (iter && ((iter->buffer.begin == iter->buffer.end) || (iter->flags & NK_WINDOW_HIDDEN))) iter = iter->next; if (!iter) return 0; return nk_ptr_add_const(struct nk_command, buffer, iter->buffer.begin); } NK_API const struct nk_command* nk__next(struct nk_context *ctx, const struct nk_command *cmd) { nk_byte *buffer; const struct nk_command *next; NK_ASSERT(ctx); if (!ctx || !cmd || !ctx->count) return 0; if (cmd->next >= ctx->memory.allocated) return 0; buffer = (nk_byte*)ctx->memory.memory.ptr; next = nk_ptr_add_const(struct nk_command, buffer, cmd->next); return next; } /* ---------------------------------------------------------------- * * PANEL * * ---------------------------------------------------------------*/ static int nk_panel_has_header(nk_flags flags, const char *title) { /* window header state */ int active = 0; active = (flags & (NK_WINDOW_CLOSABLE|NK_WINDOW_MINIMIZABLE)); active = active || (flags & NK_WINDOW_TITLE); active = active && !(flags & NK_WINDOW_HIDDEN) && title; return active; } NK_INTERN struct nk_vec2 nk_panel_get_padding(const struct nk_style *style, enum nk_panel_type type) { switch (type) { default: case NK_PANEL_WINDOW: return style->window.padding; case NK_PANEL_GROUP: return style->window.group_padding; case NK_PANEL_POPUP: return style->window.popup_padding; case NK_PANEL_CONTEXTUAL: return style->window.contextual_padding; case NK_PANEL_COMBO: return style->window.combo_padding; case NK_PANEL_MENU: return style->window.menu_padding; case NK_PANEL_TOOLTIP: return style->window.menu_padding; } } NK_INTERN float nk_panel_get_border(const struct nk_style *style, nk_flags flags, enum nk_panel_type type) { if (flags & NK_WINDOW_BORDER) { switch (type) { default: case NK_PANEL_WINDOW: return style->window.border; case NK_PANEL_GROUP: return style->window.group_border; case NK_PANEL_POPUP: return style->window.popup_border; case NK_PANEL_CONTEXTUAL: return style->window.contextual_border; case NK_PANEL_COMBO: return style->window.combo_border; case NK_PANEL_MENU: return style->window.menu_border; case NK_PANEL_TOOLTIP: return style->window.menu_border; }} else return 0; } NK_INTERN struct nk_color nk_panel_get_border_color(const struct nk_style *style, enum nk_panel_type type) { switch (type) { default: case NK_PANEL_WINDOW: return style->window.border_color; case NK_PANEL_GROUP: return style->window.group_border_color; case NK_PANEL_POPUP: return style->window.popup_border_color; case NK_PANEL_CONTEXTUAL: return style->window.contextual_border_color; case NK_PANEL_COMBO: return style->window.combo_border_color; case NK_PANEL_MENU: return style->window.menu_border_color; case NK_PANEL_TOOLTIP: return style->window.menu_border_color; } } NK_INTERN int nk_panel_is_sub(enum nk_panel_type type) { return (type & NK_PANEL_SET_SUB)?1:0; } NK_INTERN int nk_panel_is_nonblock(enum nk_panel_type type) { return (type & NK_PANEL_SET_NONBLOCK)?1:0; } NK_INTERN int nk_panel_begin(struct nk_context *ctx, const char *title, enum nk_panel_type panel_type) { struct nk_input *in; struct nk_window *win; struct nk_panel *layout; struct nk_command_buffer *out; const struct nk_style *style; const struct nk_user_font *font; struct nk_vec2 scrollbar_size; struct nk_vec2 panel_padding; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; nk_zero(ctx->current->layout, sizeof(*ctx->current->layout)); if (ctx->current->flags & NK_WINDOW_HIDDEN) return 0; /* pull state into local stack */ style = &ctx->style; font = style->font; in = &ctx->input; win = ctx->current; layout = win->layout; out = &win->buffer; #ifdef NK_INCLUDE_COMMAND_USERDATA win->buffer.userdata = ctx->userdata; #endif /* pull style configuration into local stack */ scrollbar_size = style->window.scrollbar_size; panel_padding = nk_panel_get_padding(style, panel_type); /* window movement */ if ((win->flags & NK_WINDOW_MOVABLE) && !(win->flags & NK_WINDOW_ROM)) { int left_mouse_down; int left_mouse_click_in_cursor; /* calculate draggable window space */ struct nk_rect header; header.x = win->bounds.x; header.y = win->bounds.y; header.w = win->bounds.w; if (nk_panel_has_header(win->flags, title)) { header.h = font->height + 2.0f * style->window.header.padding.y; header.h += 2.0f * style->window.header.label_padding.y; } else header.h = panel_padding.y; /* window movement by dragging */ left_mouse_down = in->mouse.buttons[NK_BUTTON_LEFT].down; left_mouse_click_in_cursor = nk_input_has_mouse_click_down_in_rect(in, NK_BUTTON_LEFT, header, nk_true); if (left_mouse_down && left_mouse_click_in_cursor) { win->bounds.x = win->bounds.x + in->mouse.delta.x; win->bounds.y = win->bounds.y + in->mouse.delta.y; in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.x += in->mouse.delta.x; in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.y += in->mouse.delta.y; ctx->style.cursor_active = ctx->style.cursors[NK_CURSOR_MOVE]; } } /* setup panel */ layout->type = panel_type; layout->flags = win->flags; layout->bounds = win->bounds; layout->bounds.x += panel_padding.x; layout->bounds.w -= 2*panel_padding.x; if (win->flags & NK_WINDOW_BORDER) { layout->border = nk_panel_get_border(style, win->flags, panel_type); layout->bounds = nk_shrink_rect(layout->bounds, layout->border); } else layout->border = 0; layout->at_y = layout->bounds.y; layout->at_x = layout->bounds.x; layout->max_x = 0; layout->header_height = 0; layout->footer_height = 0; layout->row.index = 0; layout->row.columns = 0; layout->row.ratio = 0; layout->row.item_width = 0; layout->row.tree_depth = 0; layout->row.height = panel_padding.y; layout->has_scrolling = nk_true; if (!(win->flags & NK_WINDOW_NO_SCROLLBAR)) layout->bounds.w -= scrollbar_size.x; if (!nk_panel_is_nonblock(panel_type)) { layout->footer_height = 0; if (!(win->flags & NK_WINDOW_NO_SCROLLBAR) || win->flags & NK_WINDOW_SCALABLE) layout->footer_height = scrollbar_size.y; layout->bounds.h -= layout->footer_height; } /* panel header */ if (nk_panel_has_header(win->flags, title)) { struct nk_text text; struct nk_rect header; const struct nk_style_item *background = 0; /* calculate header bounds */ header.x = win->bounds.x; header.y = win->bounds.y; header.w = win->bounds.w; header.h = font->height + 2.0f * style->window.header.padding.y; header.h += (2.0f * style->window.header.label_padding.y); /* shrink panel by header */ layout->header_height = header.h; layout->bounds.y += header.h; layout->bounds.h -= header.h; layout->at_y += header.h; /* select correct header background and text color */ if (ctx->active == win) { background = &style->window.header.active; text.text = style->window.header.label_active; } else if (nk_input_is_mouse_hovering_rect(&ctx->input, header)) { background = &style->window.header.hover; text.text = style->window.header.label_hover; } else { background = &style->window.header.normal; text.text = style->window.header.label_normal; } /* draw header background */ header.h += 1.0f; if (background->type == NK_STYLE_ITEM_IMAGE) { text.background = nk_rgba(0,0,0,0); nk_draw_image(&win->buffer, header, &background->data.image, nk_white); } else { text.background = background->data.color; nk_fill_rect(out, header, 0, background->data.color); } /* window close button */ {struct nk_rect button; button.y = header.y + style->window.header.padding.y; button.h = header.h - 2 * style->window.header.padding.y; button.w = button.h; if (win->flags & NK_WINDOW_CLOSABLE) { nk_flags ws = 0; if (style->window.header.align == NK_HEADER_RIGHT) { button.x = (header.w + header.x) - (button.w + style->window.header.padding.x); header.w -= button.w + style->window.header.spacing.x + style->window.header.padding.x; } else { button.x = header.x + style->window.header.padding.x; header.x += button.w + style->window.header.spacing.x + style->window.header.padding.x; } if (nk_do_button_symbol(&ws, &win->buffer, button, style->window.header.close_symbol, NK_BUTTON_DEFAULT, &style->window.header.close_button, in, style->font) && !(win->flags & NK_WINDOW_ROM)) { layout->flags |= NK_WINDOW_HIDDEN; layout->flags |= NK_WINDOW_CLOSED; } } /* window minimize button */ if (win->flags & NK_WINDOW_MINIMIZABLE) { nk_flags ws = 0; if (style->window.header.align == NK_HEADER_RIGHT) { button.x = (header.w + header.x) - button.w; if (!(win->flags & NK_WINDOW_CLOSABLE)) { button.x -= style->window.header.padding.x; header.w -= style->window.header.padding.x; } header.w -= button.w + style->window.header.spacing.x; } else { button.x = header.x; header.x += button.w + style->window.header.spacing.x + style->window.header.padding.x; } if (nk_do_button_symbol(&ws, &win->buffer, button, (layout->flags & NK_WINDOW_MINIMIZED)? style->window.header.maximize_symbol: style->window.header.minimize_symbol, NK_BUTTON_DEFAULT, &style->window.header.minimize_button, in, style->font) && !(win->flags & NK_WINDOW_ROM)) layout->flags = (layout->flags & NK_WINDOW_MINIMIZED) ? layout->flags & (nk_flags)~NK_WINDOW_MINIMIZED: layout->flags | NK_WINDOW_MINIMIZED; }} {/* window header title */ int text_len = nk_strlen(title); struct nk_rect label = {0,0,0,0}; float t = font->width(font->userdata, font->height, title, text_len); text.padding = nk_vec2(0,0); label.x = header.x + style->window.header.padding.x; label.x += style->window.header.label_padding.x; label.y = header.y + style->window.header.label_padding.y; label.h = font->height + 2 * style->window.header.label_padding.y; label.w = t + 2 * style->window.header.spacing.x; nk_widget_text(out, label,(const char*)title, text_len, &text, NK_TEXT_LEFT, font);} } /* draw window background */ if (!(layout->flags & NK_WINDOW_MINIMIZED) && !(layout->flags & NK_WINDOW_DYNAMIC)) { struct nk_rect body; body.x = win->bounds.x; body.w = win->bounds.w; body.y = (win->bounds.y + layout->header_height); body.h = (win->bounds.h - layout->header_height); if (style->window.fixed_background.type == NK_STYLE_ITEM_IMAGE) nk_draw_image(out, body, &style->window.fixed_background.data.image, nk_white); else nk_fill_rect(out, body, 0, style->window.fixed_background.data.color); } /* set clipping rectangle */ {struct nk_rect clip; layout->clip = layout->bounds; nk_unify(&clip, &win->buffer.clip, layout->clip.x, layout->clip.y, layout->clip.x + layout->clip.w, layout->clip.y + layout->clip.h); nk_push_scissor(out, clip); layout->clip = clip;} return !(layout->flags & NK_WINDOW_HIDDEN) && !(layout->flags & NK_WINDOW_MINIMIZED); } NK_INTERN void nk_panel_end(struct nk_context *ctx) { struct nk_input *in; struct nk_window *window; struct nk_panel *layout; const struct nk_style *style; struct nk_command_buffer *out; struct nk_vec2 scrollbar_size; struct nk_vec2 panel_padding; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; window = ctx->current; layout = window->layout; style = &ctx->style; out = &window->buffer; in = (layout->flags & NK_WINDOW_ROM) ? 0 :&ctx->input; if (!nk_panel_is_sub(layout->type)) nk_push_scissor(out, nk_null_rect); /* cache configuration data */ scrollbar_size = style->window.scrollbar_size; panel_padding = nk_panel_get_padding(style, layout->type); /* update the current cursor Y-position to point over the last added widget */ layout->at_y += layout->row.height; /* dynamic panels */ if (layout->flags & NK_WINDOW_DYNAMIC && !(layout->flags & NK_WINDOW_MINIMIZED)) { /* update panel height to fit dynamic growth */ struct nk_rect empty_space; if (layout->at_y < (layout->bounds.y + layout->bounds.h)) layout->bounds.h = layout->at_y - layout->bounds.y; /* fill top empty space */ empty_space.x = window->bounds.x; empty_space.y = layout->bounds.y; empty_space.h = panel_padding.y; empty_space.w = window->bounds.w; nk_fill_rect(out, empty_space, 0, style->window.background); /* fill left empty space */ empty_space.x = window->bounds.x; empty_space.y = layout->bounds.y; empty_space.w = panel_padding.x + layout->border; empty_space.h = layout->bounds.h; nk_fill_rect(out, empty_space, 0, style->window.background); /* fill right empty space */ empty_space.x = layout->bounds.x + layout->bounds.w - layout->border; empty_space.y = layout->bounds.y; empty_space.w = panel_padding.x + layout->border; empty_space.h = layout->bounds.h; if (layout->offset->y == 0 && !(layout->flags & NK_WINDOW_NO_SCROLLBAR)) empty_space.w += scrollbar_size.x; nk_fill_rect(out, empty_space, 0, style->window.background); /* fill bottom empty space */ if (layout->offset->x != 0 && !(layout->flags & NK_WINDOW_NO_SCROLLBAR)) { empty_space.x = window->bounds.x; empty_space.y = layout->bounds.y + layout->bounds.h; empty_space.w = window->bounds.w; empty_space.h = scrollbar_size.y; nk_fill_rect(out, empty_space, 0, style->window.background); } } /* scrollbars */ if (!(layout->flags & NK_WINDOW_NO_SCROLLBAR) && !(layout->flags & NK_WINDOW_MINIMIZED) && window->scrollbar_hiding_timer < NK_SCROLLBAR_HIDING_TIMEOUT) { struct nk_rect scroll; int scroll_has_scrolling; float scroll_target; float scroll_offset; float scroll_step; float scroll_inc; { /* vertical scrollbar */ nk_flags state = 0; scroll.x = layout->bounds.x + layout->bounds.w + panel_padding.x; scroll.y = layout->bounds.y; scroll.w = scrollbar_size.x; scroll.h = layout->bounds.h; scroll_offset = layout->offset->y; scroll_step = scroll.h * 0.10f; scroll_inc = scroll.h * 0.01f; scroll_target = (float)(int)(layout->at_y - scroll.y); /* scrolling by mouse wheel */ if (nk_panel_is_sub(layout->type)) { /* sub-window scrollbar wheel scrolling */ struct nk_window *root_window = window; struct nk_panel *root_panel = window->layout; while (root_panel->parent) root_panel = root_panel->parent; while (root_window->parent) root_window = root_window->parent; /* only allow scrolling if parent window is active */ scroll_has_scrolling = 0; if ((root_window == ctx->active) && layout->has_scrolling) { /* and panel is being hovered and inside clip rect*/ if (nk_input_is_mouse_hovering_rect(in, layout->bounds) && NK_INTERSECT(layout->bounds.x, layout->bounds.y, layout->bounds.w, layout->bounds.h, root_panel->clip.x, root_panel->clip.y, root_panel->clip.w, root_panel->clip.h)) { /* deactivate all parent scrolling */ root_panel = window->layout; while (root_panel->parent) { root_panel->has_scrolling = nk_false; root_panel = root_panel->parent; } root_panel->has_scrolling = nk_false; scroll_has_scrolling = nk_true; } } } else if (!nk_panel_is_sub(layout->type)) { /* window scrollbar wheel scrolling */ scroll_has_scrolling = (window == ctx->active) && layout->has_scrolling; if (in && in->mouse.scroll_delta > 0 && scroll_has_scrolling) window->scrolled = nk_true; else window->scrolled = nk_false; } else scroll_has_scrolling = nk_false; /* execute scrollbar */ scroll_offset = nk_do_scrollbarv(&state, out, scroll, scroll_has_scrolling, scroll_offset, scroll_target, scroll_step, scroll_inc, &ctx->style.scrollv, in, style->font); layout->offset->y = (unsigned short)scroll_offset; if (in && scroll_has_scrolling) in->mouse.scroll_delta = 0; } { /* horizontal scrollbar */ nk_flags state = 0; scroll.x = layout->bounds.x; scroll.y = layout->bounds.y + layout->bounds.h; scroll.w = layout->bounds.w; scroll.h = scrollbar_size.y; scroll_offset = layout->offset->x; scroll_target = (float)(int)(layout->max_x - scroll.x); scroll_step = layout->max_x * 0.05f; scroll_inc = layout->max_x * 0.005f; scroll_has_scrolling = nk_false; scroll_offset = nk_do_scrollbarh(&state, out, scroll, scroll_has_scrolling, scroll_offset, scroll_target, scroll_step, scroll_inc, &ctx->style.scrollh, in, style->font); layout->offset->x = (unsigned short)scroll_offset; } } /* hide scroll if no user input */ if (window->flags & NK_WINDOW_SCROLL_AUTO_HIDE) { int has_input = ctx->input.mouse.delta.x != 0 || ctx->input.mouse.delta.y != 0 || ctx->input.mouse.scroll_delta != 0; int is_window_hovered = nk_window_is_hovered(ctx); int any_item_active = (ctx->last_widget_state & NK_WIDGET_STATE_MODIFIED); if ((!has_input && is_window_hovered) || (!is_window_hovered && !any_item_active)) window->scrollbar_hiding_timer += ctx->delta_time_seconds; else window->scrollbar_hiding_timer = 0; } else window->scrollbar_hiding_timer = 0; /* window border */ if (layout->flags & NK_WINDOW_BORDER) { struct nk_color border_color = nk_panel_get_border_color(style, layout->type); const float padding_y = (layout->flags & NK_WINDOW_MINIMIZED) ? style->window.border + window->bounds.y + layout->header_height: (layout->flags & NK_WINDOW_DYNAMIC)? layout->bounds.y + layout->bounds.h + layout->footer_height: window->bounds.y + window->bounds.h; /* draw border top */ nk_stroke_line(out,window->bounds.x,window->bounds.y, window->bounds.x + window->bounds.w, window->bounds.y, layout->border, border_color); /* draw bottom border */ nk_stroke_line(out, window->bounds.x, padding_y, window->bounds.x + window->bounds.w, padding_y, layout->border, border_color); /* draw left border */ nk_stroke_line(out, window->bounds.x + layout->border*0.5f, window->bounds.y, window->bounds.x + layout->border*0.5f, padding_y, layout->border, border_color); /* draw right border */ nk_stroke_line(out, window->bounds.x + window->bounds.w, window->bounds.y, window->bounds.x + window->bounds.w, padding_y, layout->border, border_color); } /* scaler */ if ((layout->flags & NK_WINDOW_SCALABLE) && in && !(layout->flags & NK_WINDOW_MINIMIZED)) { /* calculate scaler bounds */ struct nk_rect scaler; scaler.w = scrollbar_size.x; scaler.h = scrollbar_size.y; scaler.y = layout->bounds.y + layout->bounds.h; scaler.x = layout->bounds.x + layout->bounds.w + panel_padding.x; if (layout->flags & NK_WINDOW_NO_SCROLLBAR) scaler.x -= scaler.w; /* draw scaler */ {const struct nk_style_item *item = &style->window.scaler; if (item->type == NK_STYLE_ITEM_IMAGE) nk_draw_image(out, scaler, &item->data.image, nk_white); else nk_fill_triangle(out, scaler.x + scaler.w, scaler.y, scaler.x + scaler.w, scaler.y + scaler.h, scaler.x, scaler.y + scaler.h, item->data.color); } /* do window scaling */ if (!(window->flags & NK_WINDOW_ROM)) { struct nk_vec2 window_size = style->window.min_size; int left_mouse_down = in->mouse.buttons[NK_BUTTON_LEFT].down; int left_mouse_click_in_scaler = nk_input_has_mouse_click_down_in_rect(in, NK_BUTTON_LEFT, scaler, nk_true); if (nk_input_is_mouse_down(in, NK_BUTTON_LEFT) && left_mouse_down && left_mouse_click_in_scaler) { window->bounds.w = NK_MAX(window_size.x, window->bounds.w + in->mouse.delta.x); /* dragging in y-direction is only possible if static window */ if (!(layout->flags & NK_WINDOW_DYNAMIC)) window->bounds.h = NK_MAX(window_size.y, window->bounds.h + in->mouse.delta.y); ctx->style.cursor_active = ctx->style.cursors[NK_CURSOR_RESIZE_TOP_RIGHT_DOWN_LEFT]; in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.x = scaler.x + in->mouse.delta.x + scaler.w/2.0f; in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.y = scaler.y + in->mouse.delta.y + scaler.h/2.0f; } } } if (!nk_panel_is_sub(layout->type)) { /* window is hidden so clear command buffer */ if (layout->flags & NK_WINDOW_HIDDEN) nk_command_buffer_reset(&window->buffer); /* window is visible and not tab */ else nk_finish(ctx, window); } /* NK_WINDOW_REMOVE_ROM flag was set so remove NK_WINDOW_ROM */ if (layout->flags & NK_WINDOW_REMOVE_ROM) { layout->flags &= ~(nk_flags)NK_WINDOW_ROM; layout->flags &= ~(nk_flags)NK_WINDOW_REMOVE_ROM; } window->flags = layout->flags; /* property garbage collector */ if (window->property.active && window->property.old != window->property.seq && window->property.active == window->property.prev) { nk_zero(&window->property, sizeof(window->property)); } else { window->property.old = window->property.seq; window->property.prev = window->property.active; window->property.seq = 0; } /* edit garbage collector */ if (window->edit.active && window->edit.old != window->edit.seq && window->edit.active == window->edit.prev) { nk_zero(&window->edit, sizeof(window->edit)); } else { window->edit.old = window->edit.seq; window->edit.prev = window->edit.active; window->edit.seq = 0; } /* contextual garbage collector */ if (window->popup.active_con && window->popup.con_old != window->popup.con_count) { window->popup.con_count = 0; window->popup.con_old = 0; window->popup.active_con = 0; } else { window->popup.con_old = window->popup.con_count; window->popup.con_count = 0; } window->popup.combo_count = 0; /* helper to make sure you have a 'nk_tree_push' * for every 'nk_tree_pop' */ NK_ASSERT(!layout->row.tree_depth); } /* ---------------------------------------------------------------- * * PAGE ELEMENT * * ---------------------------------------------------------------*/ NK_INTERN struct nk_page_element* nk_create_page_element(struct nk_context *ctx) { struct nk_page_element *elem; if (ctx->freelist) { /* unlink page element from free list */ elem = ctx->freelist; ctx->freelist = elem->next; } else if (ctx->use_pool) { /* allocate page element from memory pool */ elem = nk_pool_alloc(&ctx->pool); NK_ASSERT(elem); if (!elem) return 0; } else { /* allocate new page element from the back of the fixed size memory buffer */ NK_STORAGE const nk_size size = sizeof(struct nk_page_element); NK_STORAGE const nk_size align = NK_ALIGNOF(struct nk_page_element); elem = (struct nk_page_element*)nk_buffer_alloc(&ctx->memory, NK_BUFFER_BACK, size, align); NK_ASSERT(elem); if (!elem) return 0; } nk_zero_struct(*elem); elem->next = 0; elem->prev = 0; return elem; } NK_INTERN void nk_free_page_element(struct nk_context *ctx, struct nk_page_element *elem) { /* link table into freelist */ if (!ctx->freelist) { ctx->freelist = elem; } else { elem->next = ctx->freelist; ctx->freelist = elem; } } /* ---------------------------------------------------------------- * * TABLES * * ---------------------------------------------------------------*/ NK_INTERN struct nk_table* nk_create_table(struct nk_context *ctx) { struct nk_page_element *elem = nk_create_page_element(ctx); if (!elem) return 0; nk_zero_struct(*elem); return &elem->data.tbl; } NK_INTERN void nk_free_table(struct nk_context *ctx, struct nk_table *tbl) { union nk_page_data *pd = NK_CONTAINER_OF(tbl, union nk_page_data, tbl); struct nk_page_element *pe = NK_CONTAINER_OF(pd, struct nk_page_element, data); nk_free_page_element(ctx, pe); } NK_INTERN void nk_push_table(struct nk_window *win, struct nk_table *tbl) { if (!win->tables) { win->tables = tbl; tbl->next = 0; tbl->prev = 0; win->table_count = 1; win->table_size = 0; return; } win->tables->prev = tbl; tbl->next = win->tables; tbl->prev = 0; win->tables = tbl; win->table_count++; win->table_size = 0; } NK_INTERN void nk_remove_table(struct nk_window *win, struct nk_table *tbl) { if (win->tables == tbl) win->tables = tbl->next; if (tbl->next) tbl->next->prev = tbl->prev; if (tbl->prev) tbl->prev->next = tbl->next; tbl->next = 0; tbl->prev = 0; } NK_INTERN nk_uint* nk_add_value(struct nk_context *ctx, struct nk_window *win, nk_hash name, nk_uint value) { NK_ASSERT(ctx); NK_ASSERT(win); if (!win || !ctx) return 0; if (!win->tables || win->table_size >= NK_VALUE_PAGE_CAPACITY) { struct nk_table *tbl = nk_create_table(ctx); NK_ASSERT(tbl); if (!tbl) return 0; nk_push_table(win, tbl); } win->tables->seq = win->seq; win->tables->keys[win->table_size] = name; win->tables->values[win->table_size] = value; return &win->tables->values[win->table_size++]; } NK_INTERN nk_uint* nk_find_value(struct nk_window *win, nk_hash name) { unsigned short size = win->table_size; struct nk_table *iter = win->tables; while (iter) { unsigned short i = 0; for (i = 0; i < size; ++i) { if (iter->keys[i] == name) { iter->seq = win->seq; return &iter->values[i]; } } size = NK_VALUE_PAGE_CAPACITY; iter = iter->next; } return 0; } /* ---------------------------------------------------------------- * * WINDOW * * ---------------------------------------------------------------*/ NK_INTERN void* nk_create_window(struct nk_context *ctx) { struct nk_page_element *elem = nk_create_page_element(ctx); if (!elem) return 0; elem->data.win.seq = ctx->seq; return &elem->data.win; } NK_INTERN void nk_free_window(struct nk_context *ctx, struct nk_window *win) { /* unlink windows from list */ struct nk_table *n, *it = win->tables; if (win->popup.win) { nk_free_window(ctx, win->popup.win); win->popup.win = 0; } win->next = 0; win->prev = 0; while (it) { /*free window state tables */ n = it->next; nk_remove_table(win, it); nk_free_table(ctx, it); if (it == win->tables) win->tables = n; it = n; } /* link windows into freelist */ {union nk_page_data *pd = NK_CONTAINER_OF(win, union nk_page_data, win); struct nk_page_element *pe = NK_CONTAINER_OF(pd, struct nk_page_element, data); nk_free_page_element(ctx, pe);} } NK_INTERN struct nk_window* nk_find_window(struct nk_context *ctx, nk_hash hash, const char *name) { struct nk_window *iter; iter = ctx->begin; while (iter) { NK_ASSERT(iter != iter->next); if (iter->name == hash) { int max_len = nk_strlen(iter->name_string); if (!nk_stricmpn(iter->name_string, name, max_len)) return iter; } iter = iter->next; } return 0; } enum nk_window_insert_location { NK_INSERT_BACK, /* inserts window into the back of list (front of screen) */ NK_INSERT_FRONT /* inserts window into the front of list (back of screen) */ }; NK_INTERN void nk_insert_window(struct nk_context *ctx, struct nk_window *win, enum nk_window_insert_location loc) { const struct nk_window *iter; NK_ASSERT(ctx); NK_ASSERT(win); if (!win || !ctx) return; iter = ctx->begin; while (iter) { NK_ASSERT(iter != iter->next); NK_ASSERT(iter != win); if (iter == win) return; iter = iter->next; } if (!ctx->begin) { win->next = 0; win->prev = 0; ctx->begin = win; ctx->end = win; ctx->count = 1; return; } if (loc == NK_INSERT_BACK) { struct nk_window *end; end = ctx->end; end->flags |= NK_WINDOW_ROM; end->next = win; win->prev = ctx->end; win->next = 0; ctx->end = win; ctx->active = ctx->end; ctx->end->flags &= ~(nk_flags)NK_WINDOW_ROM; } else { ctx->end->flags |= NK_WINDOW_ROM; ctx->begin->prev = win; win->next = ctx->begin; win->prev = 0; ctx->begin = win; ctx->begin->flags &= ~(nk_flags)NK_WINDOW_ROM; } ctx->count++; } NK_INTERN void nk_remove_window(struct nk_context *ctx, struct nk_window *win) { if (win == ctx->begin || win == ctx->end) { if (win == ctx->begin) { ctx->begin = win->next; if (win->next) win->next->prev = 0; } if (win == ctx->end) { ctx->end = win->prev; if (win->prev) win->prev->next = 0; } } else { if (win->next) win->next->prev = win->prev; if (win->prev) win->prev->next = win->next; } if (win == ctx->active || !ctx->active) { ctx->active = ctx->end; if (ctx->end) ctx->end->flags &= ~(nk_flags)NK_WINDOW_ROM; } win->next = 0; win->prev = 0; ctx->count--; } NK_API int nk_begin(struct nk_context *ctx, struct nk_panel *layout, const char *title, struct nk_rect bounds, nk_flags flags) { return nk_begin_titled(ctx, layout, title, title, bounds, flags); } NK_API int nk_begin_titled(struct nk_context *ctx, struct nk_panel *layout, const char *name, const char *title, struct nk_rect bounds, nk_flags flags) { struct nk_window *win; struct nk_style *style; nk_hash title_hash; int title_len; int ret = 0; NK_ASSERT(ctx); NK_ASSERT(name); NK_ASSERT(title); NK_ASSERT(ctx->style.font && ctx->style.font->width && "if this triggers you forgot to add a font"); NK_ASSERT(!ctx->current && "if this triggers you missed a `nk_end` call"); if (!ctx || ctx->current || !title || !name) return 0; /* find or create window */ style = &ctx->style; title_len = (int)nk_strlen(name); title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE); win = nk_find_window(ctx, title_hash, name); if (!win) { /* create new window */ nk_size name_length = (nk_size)nk_strlen(name); win = (struct nk_window*)nk_create_window(ctx); NK_ASSERT(win); if (!win) return 0; if (flags & NK_WINDOW_BACKGROUND) nk_insert_window(ctx, win, NK_INSERT_FRONT); else nk_insert_window(ctx, win, NK_INSERT_BACK); nk_command_buffer_init(&win->buffer, &ctx->memory, NK_CLIPPING_ON); win->flags = flags; win->bounds = bounds; win->name = title_hash; name_length = NK_MIN(name_length, NK_WINDOW_MAX_NAME-1); NK_MEMCPY(win->name_string, name, name_length); win->name_string[name_length] = 0; win->popup.win = 0; if (!ctx->active) ctx->active = win; } else { /* update window */ win->flags &= ~(nk_flags)(NK_WINDOW_PRIVATE-1); win->flags |= flags; NK_ASSERT(win->seq != ctx->seq && "if this triggers you probably have two windows with same name!"); win->seq = ctx->seq; if (!ctx->active) ctx->active = win; } if (win->flags & NK_WINDOW_HIDDEN) { ctx->current = win; return 0; } /* window overlapping */ if (!(win->flags & NK_WINDOW_HIDDEN)) { int inpanel, ishovered; const struct nk_window *iter = win; float h = ctx->style.font->height + 2.0f * style->window.header.padding.y + (2.0f * style->window.header.label_padding.y); struct nk_rect win_bounds = (!(win->flags & NK_WINDOW_MINIMIZED))? win->bounds: nk_rect(win->bounds.x, win->bounds.y, win->bounds.w, h); /* activate window if hovered and no other window is overlapping this window */ nk_start(ctx, win); inpanel = nk_input_has_mouse_click_down_in_rect(&ctx->input, NK_BUTTON_LEFT, win_bounds, nk_true); inpanel = inpanel && ctx->input.mouse.buttons[NK_BUTTON_LEFT].clicked; ishovered = nk_input_is_mouse_hovering_rect(&ctx->input, win_bounds); if ((win != ctx->active) && ishovered && !ctx->input.mouse.buttons[NK_BUTTON_LEFT].down) { iter = win->next; while (iter) { struct nk_rect iter_bounds = (!(iter->flags & NK_WINDOW_MINIMIZED))? iter->bounds: nk_rect(iter->bounds.x, iter->bounds.y, iter->bounds.w, h); if (NK_INTERSECT(win_bounds.x, win_bounds.y, win_bounds.w, win_bounds.h, iter_bounds.x, iter_bounds.y, iter_bounds.w, iter_bounds.h) && (!(iter->flags & NK_WINDOW_HIDDEN) || !(iter->flags & NK_WINDOW_BACKGROUND))) break; if (iter->popup.win && iter->popup.active && !(iter->flags & NK_WINDOW_HIDDEN) && NK_INTERSECT(win->bounds.x, win_bounds.y, win_bounds.w, win_bounds.h, iter->popup.win->bounds.x, iter->popup.win->bounds.y, iter->popup.win->bounds.w, iter->popup.win->bounds.h)) break; iter = iter->next; } } /* activate window if clicked */ if (iter && inpanel && (win != ctx->end) && !(iter->flags & NK_WINDOW_BACKGROUND)) { iter = win->next; while (iter) { /* try to find a panel with higher priority in the same position */ struct nk_rect iter_bounds = (!(iter->flags & NK_WINDOW_MINIMIZED))? iter->bounds: nk_rect(iter->bounds.x, iter->bounds.y, iter->bounds.w, h); if (NK_INBOX(ctx->input.mouse.pos.x, ctx->input.mouse.pos.y, iter_bounds.x, iter_bounds.y, iter_bounds.w, iter_bounds.h) && !(iter->flags & NK_WINDOW_HIDDEN)) break; if (iter->popup.win && iter->popup.active && !(iter->flags & NK_WINDOW_HIDDEN) && NK_INTERSECT(win_bounds.x, win_bounds.y, win_bounds.w, win_bounds.h, iter->popup.win->bounds.x, iter->popup.win->bounds.y, iter->popup.win->bounds.w, iter->popup.win->bounds.h)) break; iter = iter->next; } } if (!iter && ctx->end != win) { if (!(win->flags & NK_WINDOW_BACKGROUND)) { /* current window is active in that position so transfer to top * at the highest priority in stack */ nk_remove_window(ctx, win); nk_insert_window(ctx, win, NK_INSERT_BACK); } win->flags &= ~(nk_flags)NK_WINDOW_ROM; ctx->active = win; } if (ctx->end != win && !(win->flags & NK_WINDOW_BACKGROUND)) win->flags |= NK_WINDOW_ROM; } win->layout = layout; ctx->current = win; ret = nk_panel_begin(ctx, title, NK_PANEL_WINDOW); layout->offset = &win->scrollbar; return ret; } NK_API void nk_end(struct nk_context *ctx) { NK_ASSERT(ctx); NK_ASSERT(ctx->current && "if this triggers you forgot to call `nk_begin`"); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current) return; if (ctx->current->flags & NK_WINDOW_HIDDEN) { ctx->current = 0; return; } nk_panel_end(ctx); ctx->current = 0; } NK_API struct nk_rect nk_window_get_bounds(const struct nk_context *ctx) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return nk_rect(0,0,0,0); return ctx->current->bounds; } NK_API struct nk_vec2 nk_window_get_position(const struct nk_context *ctx) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return nk_vec2(0,0); return nk_vec2(ctx->current->bounds.x, ctx->current->bounds.y); } NK_API struct nk_vec2 nk_window_get_size(const struct nk_context *ctx) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return nk_vec2(0,0); return nk_vec2(ctx->current->bounds.w, ctx->current->bounds.h); } NK_API float nk_window_get_width(const struct nk_context *ctx) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return 0; return ctx->current->bounds.w; } NK_API float nk_window_get_height(const struct nk_context *ctx) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return 0; return ctx->current->bounds.h; } NK_API struct nk_rect nk_window_get_content_region(struct nk_context *ctx) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return nk_rect(0,0,0,0); return ctx->current->layout->clip; } NK_API struct nk_vec2 nk_window_get_content_region_min(struct nk_context *ctx) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current) return nk_vec2(0,0); return nk_vec2(ctx->current->layout->clip.x, ctx->current->layout->clip.y); } NK_API struct nk_vec2 nk_window_get_content_region_max(struct nk_context *ctx) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current) return nk_vec2(0,0); return nk_vec2(ctx->current->layout->clip.x + ctx->current->layout->clip.w, ctx->current->layout->clip.y + ctx->current->layout->clip.h); } NK_API struct nk_vec2 nk_window_get_content_region_size(struct nk_context *ctx) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current) return nk_vec2(0,0); return nk_vec2(ctx->current->layout->clip.w, ctx->current->layout->clip.h); } NK_API struct nk_command_buffer* nk_window_get_canvas(struct nk_context *ctx) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current) return 0; return &ctx->current->buffer; } NK_API struct nk_panel* nk_window_get_panel(struct nk_context *ctx) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return 0; return ctx->current->layout; } NK_API int nk_window_has_focus(const struct nk_context *ctx) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current) return 0; return ctx->current == ctx->active; } NK_API int nk_window_is_hovered(struct nk_context *ctx) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return 0; return nk_input_is_mouse_hovering_rect(&ctx->input, ctx->current->bounds); } NK_API int nk_window_is_any_hovered(struct nk_context *ctx) { struct nk_window *iter; NK_ASSERT(ctx); if (!ctx) return 0; iter = ctx->begin; while (iter) { /* check if window is being hovered */ if (iter->flags & NK_WINDOW_MINIMIZED) { struct nk_rect header = iter->bounds; header.h = ctx->style.font->height + 2 * ctx->style.window.header.padding.y; if (nk_input_is_mouse_hovering_rect(&ctx->input, header)) return 1; } else if (nk_input_is_mouse_hovering_rect(&ctx->input, iter->bounds)) { return 1; } /* check if window popup is being hovered */ if (iter->popup.active && iter->popup.win && nk_input_is_mouse_hovering_rect(&ctx->input, iter->popup.win->bounds)) return 1; iter = iter->next; } return 0; } NK_API int nk_item_is_any_active(struct nk_context *ctx) { int any_hovered = nk_window_is_any_hovered(ctx); int any_active = (ctx->last_widget_state & NK_WIDGET_STATE_MODIFIED); return any_hovered || any_active; } NK_API int nk_window_is_collapsed(struct nk_context *ctx, const char *name) { int title_len; nk_hash title_hash; struct nk_window *win; NK_ASSERT(ctx); if (!ctx) return 0; title_len = (int)nk_strlen(name); title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE); win = nk_find_window(ctx, title_hash, name); if (!win) return 0; return win->flags & NK_WINDOW_MINIMIZED; } NK_API int nk_window_is_closed(struct nk_context *ctx, const char *name) { int title_len; nk_hash title_hash; struct nk_window *win; NK_ASSERT(ctx); if (!ctx) return 1; title_len = (int)nk_strlen(name); title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE); win = nk_find_window(ctx, title_hash, name); if (!win) return 1; return (win->flags & NK_WINDOW_CLOSED); } NK_API int nk_window_is_hidden(struct nk_context *ctx, const char *name) { int title_len; nk_hash title_hash; struct nk_window *win; NK_ASSERT(ctx); if (!ctx) return 1; title_len = (int)nk_strlen(name); title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE); win = nk_find_window(ctx, title_hash, name); if (!win) return 1; return (win->flags & NK_WINDOW_HIDDEN); } NK_API int nk_window_is_active(struct nk_context *ctx, const char *name) { int title_len; nk_hash title_hash; struct nk_window *win; NK_ASSERT(ctx); if (!ctx) return 0; title_len = (int)nk_strlen(name); title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE); win = nk_find_window(ctx, title_hash, name); if (!win) return 0; return win == ctx->active; } NK_API struct nk_window* nk_window_find(struct nk_context *ctx, const char *name) { int title_len; nk_hash title_hash; title_len = (int)nk_strlen(name); title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE); return nk_find_window(ctx, title_hash, name); } NK_API void nk_window_close(struct nk_context *ctx, const char *name) { struct nk_window *win; NK_ASSERT(ctx); if (!ctx) return; win = nk_window_find(ctx, name); if (!win) return; NK_ASSERT(ctx->current != win && "You cannot close a currently active window"); if (ctx->current == win) return; win->flags |= NK_WINDOW_HIDDEN; win->flags |= NK_WINDOW_CLOSED; } NK_API void nk_window_set_bounds(struct nk_context *ctx, struct nk_rect bounds) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return; ctx->current->bounds = bounds; } NK_API void nk_window_set_position(struct nk_context *ctx, struct nk_vec2 pos) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return; ctx->current->bounds.x = pos.x; ctx->current->bounds.y = pos.y; } NK_API void nk_window_set_size(struct nk_context *ctx, struct nk_vec2 size) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return; ctx->current->bounds.w = size.x; ctx->current->bounds.h = size.y; } NK_API void nk_window_collapse(struct nk_context *ctx, const char *name, enum nk_collapse_states c) { int title_len; nk_hash title_hash; struct nk_window *win; NK_ASSERT(ctx); if (!ctx) return; title_len = (int)nk_strlen(name); title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE); win = nk_find_window(ctx, title_hash, name); if (!win) return; if (c == NK_MINIMIZED) win->flags |= NK_WINDOW_MINIMIZED; else win->flags &= ~(nk_flags)NK_WINDOW_MINIMIZED; } NK_API void nk_window_collapse_if(struct nk_context *ctx, const char *name, enum nk_collapse_states c, int cond) { NK_ASSERT(ctx); if (!ctx || !cond) return; nk_window_collapse(ctx, name, c); } NK_API void nk_window_show(struct nk_context *ctx, const char *name, enum nk_show_states s) { int title_len; nk_hash title_hash; struct nk_window *win; NK_ASSERT(ctx); if (!ctx) return; title_len = (int)nk_strlen(name); title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE); win = nk_find_window(ctx, title_hash, name); if (!win) return; if (s == NK_HIDDEN) win->flags |= NK_WINDOW_HIDDEN; else win->flags &= ~(nk_flags)NK_WINDOW_HIDDEN; } NK_API void nk_window_show_if(struct nk_context *ctx, const char *name, enum nk_show_states s, int cond) { NK_ASSERT(ctx); if (!ctx || !cond) return; nk_window_show(ctx, name, s); } NK_API void nk_window_set_focus(struct nk_context *ctx, const char *name) { int title_len; nk_hash title_hash; struct nk_window *win; NK_ASSERT(ctx); if (!ctx) return; title_len = (int)nk_strlen(name); title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE); win = nk_find_window(ctx, title_hash, name); if (win && ctx->end != win) { nk_remove_window(ctx, win); nk_insert_window(ctx, win, NK_INSERT_BACK); } ctx->active = win; } /*---------------------------------------------------------------- * * PANEL * * --------------------------------------------------------------*/ NK_API void nk_menubar_begin(struct nk_context *ctx) { struct nk_panel *layout; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; layout = ctx->current->layout; NK_ASSERT(layout->at_y == layout->bounds.y); /* if this assert triggers you allocated space between nk_begin and nk_menubar_begin. If you want a menubar the first nuklear function after `nk_begin` has to be a `nk_menubar_begin` call. Inside the menubar you then have to allocate space for widgets (also supports multiple rows). Example: if (nk_begin(...)) { nk_menubar_begin(...); nk_layout_xxxx(...); nk_button(...); nk_layout_xxxx(...); nk_button(...); nk_menubar_end(...); } nk_end(...); */ if (layout->flags & NK_WINDOW_HIDDEN || layout->flags & NK_WINDOW_MINIMIZED) return; layout->menu.x = layout->at_x; layout->menu.y = layout->at_y + layout->row.height; layout->menu.w = layout->bounds.w; layout->menu.offset = *layout->offset; layout->offset->y = 0; } NK_API void nk_menubar_end(struct nk_context *ctx) { struct nk_window *win; struct nk_panel *layout; struct nk_command_buffer *out; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; win = ctx->current; out = &win->buffer; layout = win->layout; if (layout->flags & NK_WINDOW_HIDDEN || layout->flags & NK_WINDOW_MINIMIZED) return; layout->menu.h = layout->at_y - layout->menu.y; layout->bounds.y += layout->menu.h + ctx->style.window.spacing.y + layout->row.height; layout->bounds.h -= layout->menu.h + ctx->style.window.spacing.y + layout->row.height; *layout->offset = layout->menu.offset; layout->at_y = layout->bounds.y - layout->row.height; layout->clip.y = layout->bounds.y; layout->clip.h = layout->bounds.h; nk_push_scissor(out, layout->clip); } /* ------------------------------------------------------------- * * LAYOUT * * --------------------------------------------------------------*/ #define NK_LAYOUT_DYNAMIC_FIXED 0 #define NK_LAYOUT_DYNAMIC_ROW 1 #define NK_LAYOUT_DYNAMIC_FREE 2 #define NK_LAYOUT_DYNAMIC 3 #define NK_LAYOUT_STATIC_FIXED 4 #define NK_LAYOUT_STATIC_ROW 5 #define NK_LAYOUT_STATIC_FREE 6 #define NK_LAYOUT_STATIC 7 NK_INTERN void nk_panel_layout(const struct nk_context *ctx, struct nk_window *win, float height, int cols) { struct nk_panel *layout; const struct nk_style *style; struct nk_command_buffer *out; struct nk_vec2 item_spacing; struct nk_color color; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; /* prefetch some configuration data */ layout = win->layout; style = &ctx->style; out = &win->buffer; color = style->window.background; item_spacing = style->window.spacing; /* if one of these triggers you forgot to add an `if` condition around either a window, group, popup, combobox or contextual menu `begin` and `end` block. Example: if (nk_begin(...) {...} nk_end(...); or if (nk_group_begin(...) { nk_group_end(...);} */ NK_ASSERT(!(layout->flags & NK_WINDOW_MINIMIZED)); NK_ASSERT(!(layout->flags & NK_WINDOW_HIDDEN)); NK_ASSERT(!(layout->flags & NK_WINDOW_CLOSED)); /* update the current row and set the current row layout */ layout->row.index = 0; layout->at_y += layout->row.height; layout->row.columns = cols; layout->row.height = height + item_spacing.y; layout->row.item_offset = 0; if (layout->flags & NK_WINDOW_DYNAMIC) { /* draw background for dynamic panels */ struct nk_rect background; background.x = win->bounds.x; background.w = win->bounds.w; background.y = layout->at_y - 1.0f; background.h = layout->row.height + 1.0f; nk_fill_rect(out, background, 0, color); } } NK_INTERN void nk_row_layout(struct nk_context *ctx, enum nk_layout_format fmt, float height, int cols, int width) { /* update the current row and set the current row layout */ struct nk_window *win; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; win = ctx->current; nk_panel_layout(ctx, win, height, cols); if (fmt == NK_DYNAMIC) win->layout->row.type = NK_LAYOUT_DYNAMIC_FIXED; else win->layout->row.type = NK_LAYOUT_STATIC_FIXED; win->layout->row.ratio = 0; win->layout->row.filled = 0; win->layout->row.item_offset = 0; win->layout->row.item_width = (float)width; } NK_API float nk_layout_ratio_from_pixel(struct nk_context *ctx, float pixel_width) { struct nk_window *win; NK_ASSERT(ctx); NK_ASSERT(pixel_width); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; return NK_CLAMP(0.0f, pixel_width/win->bounds.x, 1.0f); } NK_API void nk_layout_row_dynamic(struct nk_context *ctx, float height, int cols) { nk_row_layout(ctx, NK_DYNAMIC, height, cols, 0); } NK_API void nk_layout_row_static(struct nk_context *ctx, float height, int item_width, int cols) { nk_row_layout(ctx, NK_STATIC, height, cols, item_width); } NK_API void nk_layout_row_begin(struct nk_context *ctx, enum nk_layout_format fmt, float row_height, int cols) { struct nk_window *win; struct nk_panel *layout; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; win = ctx->current; layout = win->layout; nk_panel_layout(ctx, win, row_height, cols); if (fmt == NK_DYNAMIC) layout->row.type = NK_LAYOUT_DYNAMIC_ROW; else layout->row.type = NK_LAYOUT_STATIC_ROW; layout->row.ratio = 0; layout->row.filled = 0; layout->row.item_width = 0; layout->row.item_offset = 0; layout->row.columns = cols; } NK_API void nk_layout_row_push(struct nk_context *ctx, float ratio_or_width) { struct nk_window *win; struct nk_panel *layout; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; win = ctx->current; layout = win->layout; if (layout->row.type == NK_LAYOUT_DYNAMIC_ROW) { float ratio = ratio_or_width; if ((ratio + layout->row.filled) > 1.0f) return; if (ratio > 0.0f) layout->row.item_width = NK_SATURATE(ratio); else layout->row.item_width = 1.0f - layout->row.filled; } else layout->row.item_width = ratio_or_width; } NK_API void nk_layout_row_end(struct nk_context *ctx) { struct nk_window *win; struct nk_panel *layout; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; win = ctx->current; layout = win->layout; layout->row.item_width = 0; layout->row.item_offset = 0; } NK_API void nk_layout_row(struct nk_context *ctx, enum nk_layout_format fmt, float height, int cols, const float *ratio) { int i; int n_undef = 0; struct nk_window *win; struct nk_panel *layout; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; win = ctx->current; layout = win->layout; nk_panel_layout(ctx, win, height, cols); if (fmt == NK_DYNAMIC) { /* calculate width of undefined widget ratios */ float r = 0; layout->row.ratio = ratio; for (i = 0; i < cols; ++i) { if (ratio[i] < 0.0f) n_undef++; else r += ratio[i]; } r = NK_SATURATE(1.0f - r); layout->row.type = NK_LAYOUT_DYNAMIC; layout->row.item_width = (r > 0 && n_undef > 0) ? (r / (float)n_undef):0; } else { layout->row.ratio = ratio; layout->row.type = NK_LAYOUT_STATIC; layout->row.item_width = 0; layout->row.item_offset = 0; } layout->row.item_offset = 0; layout->row.filled = 0; } NK_API void nk_layout_space_begin(struct nk_context *ctx, enum nk_layout_format fmt, float height, int widget_count) { struct nk_window *win; struct nk_panel *layout; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; win = ctx->current; layout = win->layout; nk_panel_layout(ctx, win, height, widget_count); if (fmt == NK_STATIC) layout->row.type = NK_LAYOUT_STATIC_FREE; else layout->row.type = NK_LAYOUT_DYNAMIC_FREE; layout->row.ratio = 0; layout->row.filled = 0; layout->row.item_width = 0; layout->row.item_offset = 0; } NK_API void nk_layout_space_end(struct nk_context *ctx) { struct nk_window *win; struct nk_panel *layout; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; win = ctx->current; layout = win->layout; layout->row.item_width = 0; layout->row.item_height = 0; layout->row.item_offset = 0; nk_zero(&layout->row.item, sizeof(layout->row.item)); } NK_API void nk_layout_space_push(struct nk_context *ctx, struct nk_rect rect) { struct nk_window *win; struct nk_panel *layout; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; win = ctx->current; layout = win->layout; layout->row.item = rect; } NK_API struct nk_rect nk_layout_space_bounds(struct nk_context *ctx) { struct nk_rect ret; struct nk_window *win; struct nk_panel *layout; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); win = ctx->current; layout = win->layout; ret.x = layout->clip.x; ret.y = layout->clip.y; ret.w = layout->clip.w; ret.h = layout->row.height; return ret; } NK_API struct nk_vec2 nk_layout_space_to_screen(struct nk_context *ctx, struct nk_vec2 ret) { struct nk_window *win; struct nk_panel *layout; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); win = ctx->current; layout = win->layout; ret.x += layout->at_x - layout->offset->x; ret.y += layout->at_y - layout->offset->y; return ret; } NK_API struct nk_vec2 nk_layout_space_to_local(struct nk_context *ctx, struct nk_vec2 ret) { struct nk_window *win; struct nk_panel *layout; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); win = ctx->current; layout = win->layout; ret.x += -layout->at_x + layout->offset->x; ret.y += -layout->at_y + layout->offset->y; return ret; } NK_API struct nk_rect nk_layout_space_rect_to_screen(struct nk_context *ctx, struct nk_rect ret) { struct nk_window *win; struct nk_panel *layout; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); win = ctx->current; layout = win->layout; ret.x += layout->at_x - layout->offset->x; ret.y += layout->at_y - layout->offset->y; return ret; } NK_API struct nk_rect nk_layout_space_rect_to_local(struct nk_context *ctx, struct nk_rect ret) { struct nk_window *win; struct nk_panel *layout; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); win = ctx->current; layout = win->layout; ret.x += -layout->at_x + layout->offset->x; ret.y += -layout->at_y + layout->offset->y; return ret; } NK_INTERN void nk_panel_alloc_row(const struct nk_context *ctx, struct nk_window *win) { struct nk_panel *layout = win->layout; struct nk_vec2 spacing = ctx->style.window.spacing; const float row_height = layout->row.height - spacing.y; nk_panel_layout(ctx, win, row_height, layout->row.columns); } NK_INTERN void nk_layout_widget_space(struct nk_rect *bounds, const struct nk_context *ctx, struct nk_window *win, int modify) { struct nk_panel *layout; const struct nk_style *style; float item_offset = 0; float item_width = 0; float item_spacing = 0; float panel_padding; float panel_spacing; float panel_space; struct nk_vec2 spacing; struct nk_vec2 padding; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; win = ctx->current; style = &ctx->style; layout = win->layout; NK_ASSERT(bounds); /* cache some configuration data */ spacing = ctx->style.window.spacing; padding = nk_panel_get_padding(style, layout->type); /* calculate the usable panel space */ panel_padding = 2 * padding.x; panel_spacing = (float)(layout->row.columns - 1) * spacing.x; panel_space = layout->bounds.w - panel_padding - panel_spacing; /* calculate the width of one item inside the current layout space */ switch (layout->row.type) { case NK_LAYOUT_DYNAMIC_FIXED: { /* scaling fixed size widgets item width */ item_width = panel_space / (float)layout->row.columns; item_offset = (float)layout->row.index * item_width; item_spacing = (float)layout->row.index * spacing.x; } break; case NK_LAYOUT_DYNAMIC_ROW: { /* scaling single ratio widget width */ item_width = layout->row.item_width * panel_space; item_offset = layout->row.item_offset; item_spacing = 0; if (modify) { layout->row.item_offset += item_width + spacing.x; layout->row.filled += layout->row.item_width; layout->row.index = 0; } } break; case NK_LAYOUT_DYNAMIC_FREE: { /* panel width depended free widget placing */ bounds->x = layout->at_x + (layout->bounds.w * layout->row.item.x); bounds->x -= layout->offset->x; bounds->y = layout->at_y + (layout->row.height * layout->row.item.y); bounds->y -= layout->offset->y; bounds->w = layout->bounds.w * layout->row.item.w; bounds->h = layout->row.height * layout->row.item.h; return; }; case NK_LAYOUT_DYNAMIC: { /* scaling arrays of panel width ratios for every widget */ float ratio; NK_ASSERT(layout->row.ratio); ratio = (layout->row.ratio[layout->row.index] < 0) ? layout->row.item_width : layout->row.ratio[layout->row.index]; item_spacing = (float)layout->row.index * spacing.x; item_width = (ratio * panel_space); item_offset = layout->row.item_offset; if (modify) { layout->row.item_offset += item_width; layout->row.filled += ratio; } } break; case NK_LAYOUT_STATIC_FIXED: { /* non-scaling fixed widgets item width */ item_width = layout->row.item_width; item_offset = (float)layout->row.index * item_width; item_spacing = (float)layout->row.index * spacing.x; } break; case NK_LAYOUT_STATIC_ROW: { /* scaling single ratio widget width */ item_width = layout->row.item_width; item_offset = layout->row.item_offset; item_spacing = (float)layout->row.index * spacing.x; if (modify) { layout->row.item_offset += item_width; layout->row.index = 0; } } break; case NK_LAYOUT_STATIC_FREE: { /* free widget placing */ bounds->x = layout->at_x + layout->row.item.x; bounds->w = layout->row.item.w; if (((bounds->x + bounds->w) > layout->max_x) && modify) layout->max_x = (bounds->x + bounds->w); bounds->x -= layout->offset->x; bounds->y = layout->at_y + layout->row.item.y; bounds->y -= layout->offset->y; bounds->h = layout->row.item.h; return; }; case NK_LAYOUT_STATIC: { /* non-scaling array of panel pixel width for every widget */ item_spacing = (float)layout->row.index * spacing.x; item_width = layout->row.ratio[layout->row.index]; item_offset = layout->row.item_offset; if (modify) layout->row.item_offset += item_width; } break; default: NK_ASSERT(0); break; }; /* set the bounds of the newly allocated widget */ bounds->w = item_width; bounds->h = layout->row.height - spacing.y; bounds->y = layout->at_y - layout->offset->y; bounds->x = layout->at_x + item_offset + item_spacing + padding.x; if (((bounds->x + bounds->w) > layout->max_x) && modify) layout->max_x = bounds->x + bounds->w; bounds->x -= layout->offset->x; } NK_INTERN void nk_panel_alloc_space(struct nk_rect *bounds, const struct nk_context *ctx) { struct nk_window *win; struct nk_panel *layout; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; /* check if the end of the row has been hit and begin new row if so */ win = ctx->current; layout = win->layout; if (layout->row.index >= layout->row.columns) nk_panel_alloc_row(ctx, win); /* calculate widget position and size */ nk_layout_widget_space(bounds, ctx, win, nk_true); layout->row.index++; } NK_INTERN void nk_layout_peek(struct nk_rect *bounds, struct nk_context *ctx) { float y; int index; struct nk_window *win; struct nk_panel *layout; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; win = ctx->current; layout = win->layout; y = layout->at_y; index = layout->row.index; if (layout->row.index >= layout->row.columns) { layout->at_y += layout->row.height; layout->row.index = 0; } nk_layout_widget_space(bounds, ctx, win, nk_false); layout->at_y = y; layout->row.index = index; } NK_INTERN int nk_tree_base(struct nk_context *ctx, enum nk_tree_type type, struct nk_image *img, const char *title, enum nk_collapse_states initial_state, const char *hash, int len, int line) { struct nk_window *win; struct nk_panel *layout; const struct nk_style *style; struct nk_command_buffer *out; const struct nk_input *in; const struct nk_style_button *button; enum nk_symbol_type symbol; struct nk_vec2 item_spacing; struct nk_rect header = {0,0,0,0}; struct nk_rect sym = {0,0,0,0}; struct nk_text text; nk_flags ws = 0; int title_len = 0; nk_hash tree_hash = 0; nk_uint *state = 0; enum nk_widget_layout_states widget_state; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; /* cache some data */ win = ctx->current; layout = win->layout; out = &win->buffer; style = &ctx->style; item_spacing = style->window.spacing; /* calculate header bounds and draw background */ nk_layout_row_dynamic(ctx, style->font->height + 2 * style->tab.padding.y, 1); widget_state = nk_widget(&header, ctx); if (type == NK_TREE_TAB) { const struct nk_style_item *background = &style->tab.background; if (background->type == NK_STYLE_ITEM_IMAGE) { nk_draw_image(out, header, &background->data.image, nk_white); text.background = nk_rgba(0,0,0,0); } else { text.background = background->data.color; nk_fill_rect(out, header, 0, style->tab.border_color); nk_fill_rect(out, nk_shrink_rect(header, style->tab.border), style->tab.rounding, background->data.color); } } else text.background = style->window.background; /* find, create or set tab persistent state (open/closed) */ if (hash) { tree_hash = nk_murmur_hash(hash, len, (nk_hash)line); } else { title_len = (int)nk_strlen(title); tree_hash = nk_murmur_hash(title, (int)title_len, (nk_hash)line); } state = nk_find_value(win, tree_hash); if (!state) { state = nk_add_value(ctx, win, tree_hash, 0); *state = initial_state; } /* update node state */ in = (!(layout->flags & NK_WINDOW_ROM)) ? &ctx->input: 0; in = (in && widget_state == NK_WIDGET_VALID) ? &ctx->input : 0; if (nk_button_behavior(&ws, header, in, NK_BUTTON_DEFAULT)) *state = (*state == NK_MAXIMIZED) ? NK_MINIMIZED : NK_MAXIMIZED; /* select correct button style */ if (*state == NK_MAXIMIZED) { symbol = style->tab.sym_maximize; if (type == NK_TREE_TAB) button = &style->tab.tab_maximize_button; else button = &style->tab.node_maximize_button; } else { symbol = style->tab.sym_minimize; if (type == NK_TREE_TAB) button = &style->tab.tab_minimize_button; else button = &style->tab.node_minimize_button; } {/* draw triangle button */ sym.w = sym.h = style->font->height; sym.y = header.y + style->tab.padding.y; sym.x = header.x + style->tab.padding.x; nk_do_button_symbol(&ws, &win->buffer, sym, symbol, NK_BUTTON_DEFAULT, button, 0, style->font); if (img) { /* draw optional image icon */ sym.x = sym.x + sym.w + 4 * item_spacing.x; nk_draw_image(&win->buffer, sym, img, nk_white); sym.w = style->font->height + style->tab.spacing.x;} } {/* draw label */ struct nk_rect label; header.w = NK_MAX(header.w, sym.w + item_spacing.x); label.x = sym.x + sym.w + item_spacing.x; label.y = sym.y; label.w = header.w - (sym.w + item_spacing.y + style->tab.indent); label.h = style->font->height; text.text = style->tab.text; text.padding = nk_vec2(0,0); nk_widget_text(out, label, title, nk_strlen(title), &text, NK_TEXT_LEFT, style->font);} /* increase x-axis cursor widget position pointer */ if (*state == NK_MAXIMIZED) { layout->at_x = header.x + layout->offset->x + style->tab.indent; layout->bounds.w = NK_MAX(layout->bounds.w, style->tab.indent); layout->bounds.w -= (style->tab.indent + style->window.padding.x); layout->row.tree_depth++; return nk_true; } else return nk_false; } NK_API int nk_tree_push_hashed(struct nk_context *ctx, enum nk_tree_type type, const char *title, enum nk_collapse_states initial_state, const char *hash, int len, int line) {return nk_tree_base(ctx, type, 0, title, initial_state, hash, len, line);} NK_API int nk_tree_image_push_hashed(struct nk_context *ctx, enum nk_tree_type type, struct nk_image img, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed) {return nk_tree_base(ctx, type, &img, title, initial_state, hash, len, seed);} NK_API void nk_tree_pop(struct nk_context *ctx) { struct nk_window *win = 0; struct nk_panel *layout = 0; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; win = ctx->current; layout = win->layout; layout->at_x -= ctx->style.tab.indent + ctx->style.window.padding.x; layout->bounds.w += ctx->style.tab.indent + ctx->style.window.padding.x; NK_ASSERT(layout->row.tree_depth); layout->row.tree_depth--; } /*---------------------------------------------------------------- * * WIDGETS * * --------------------------------------------------------------*/ NK_API struct nk_rect nk_widget_bounds(struct nk_context *ctx) { struct nk_rect bounds; NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return nk_rect(0,0,0,0); nk_layout_peek(&bounds, ctx); return bounds; } NK_API struct nk_vec2 nk_widget_position(struct nk_context *ctx) { struct nk_rect bounds; NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return nk_vec2(0,0); nk_layout_peek(&bounds, ctx); return nk_vec2(bounds.x, bounds.y); } NK_API struct nk_vec2 nk_widget_size(struct nk_context *ctx) { struct nk_rect bounds; NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return nk_vec2(0,0); nk_layout_peek(&bounds, ctx); return nk_vec2(bounds.w, bounds.h); } NK_API float nk_widget_width(struct nk_context *ctx) { struct nk_rect bounds; NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return 0; nk_layout_peek(&bounds, ctx); return bounds.w; } NK_API float nk_widget_height(struct nk_context *ctx) { struct nk_rect bounds; NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return 0; nk_layout_peek(&bounds, ctx); return bounds.h; } NK_API int nk_widget_is_hovered(struct nk_context *ctx) { int ret; struct nk_rect bounds; NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return 0; nk_layout_peek(&bounds, ctx); ret = (ctx->active == ctx->current); ret = ret && nk_input_is_mouse_hovering_rect(&ctx->input, bounds); return ret; } NK_API int nk_widget_is_mouse_clicked(struct nk_context *ctx, enum nk_buttons btn) { int ret; struct nk_rect bounds; NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return 0; nk_layout_peek(&bounds, ctx); ret = (ctx->active == ctx->current); ret = ret && nk_input_mouse_clicked(&ctx->input, btn, bounds); return ret; } NK_API int nk_widget_has_mouse_click_down(struct nk_context *ctx, enum nk_buttons btn, int down) { int ret; struct nk_rect bounds; NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return 0; nk_layout_peek(&bounds, ctx); ret = (ctx->active == ctx->current); ret = ret && nk_input_has_mouse_click_down_in_rect(&ctx->input, btn, bounds, down); return ret; } NK_API enum nk_widget_layout_states nk_widget(struct nk_rect *bounds, const struct nk_context *ctx) { struct nk_rect *c = 0; struct nk_window *win; struct nk_panel *layout; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return NK_WIDGET_INVALID; /* allocate space and check if the widget needs to be updated and drawn */ nk_panel_alloc_space(bounds, ctx); win = ctx->current; layout = win->layout; c = &layout->clip; /* if one of these triggers you forgot to add an `if` condition around either a window, group, popup, combobox or contextual menu `begin` and `end` block. Example: if (nk_begin(...) {...} nk_end(...); or if (nk_group_begin(...) { nk_group_end(...);} */ NK_ASSERT(!(layout->flags & NK_WINDOW_MINIMIZED)); NK_ASSERT(!(layout->flags & NK_WINDOW_HIDDEN)); NK_ASSERT(!(layout->flags & NK_WINDOW_CLOSED)); /* need to convert to int here to remove floating point error */ bounds->x = (float)((int)bounds->x); bounds->y = (float)((int)bounds->y); bounds->w = (float)((int)bounds->w); bounds->h = (float)((int)bounds->h); if (!NK_INTERSECT(c->x, c->y, c->w, c->h, bounds->x, bounds->y, bounds->w, bounds->h)) return NK_WIDGET_INVALID; if (!NK_CONTAINS(bounds->x, bounds->y, bounds->w, bounds->h, c->x, c->y, c->w, c->h)) return NK_WIDGET_ROM; return NK_WIDGET_VALID; } NK_API enum nk_widget_layout_states nk_widget_fitting(struct nk_rect *bounds, struct nk_context *ctx, struct nk_vec2 item_padding) { /* update the bounds to stand without padding */ struct nk_window *win; struct nk_style *style; struct nk_panel *layout; enum nk_widget_layout_states state; struct nk_vec2 panel_padding; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return NK_WIDGET_INVALID; win = ctx->current; style = &ctx->style; layout = win->layout; state = nk_widget(bounds, ctx); panel_padding = nk_panel_get_padding(style, layout->type); if (layout->row.index == 1) { bounds->w += panel_padding.x; bounds->x -= panel_padding.x; } else bounds->x -= item_padding.x; if (layout->row.index == layout->row.columns) bounds->w += panel_padding.x; else bounds->w += item_padding.x; return state; } /*---------------------------------------------------------------- * * MISC * * --------------------------------------------------------------*/ NK_API void nk_spacing(struct nk_context *ctx, int cols) { struct nk_window *win; struct nk_panel *layout; struct nk_rect nil; int i, index, rows; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; /* spacing over row boundaries */ win = ctx->current; layout = win->layout; index = (layout->row.index + cols) % layout->row.columns; rows = (layout->row.index + cols) / layout->row.columns; if (rows) { for (i = 0; i < rows; ++i) nk_panel_alloc_row(ctx, win); cols = index; } /* non table layout need to allocate space */ if (layout->row.type != NK_LAYOUT_DYNAMIC_FIXED && layout->row.type != NK_LAYOUT_STATIC_FIXED) { for (i = 0; i < cols; ++i) nk_panel_alloc_space(&nil, ctx); } layout->row.index = index; } /*---------------------------------------------------------------- * * TEXT * * --------------------------------------------------------------*/ NK_API void nk_text_colored(struct nk_context *ctx, const char *str, int len, nk_flags alignment, struct nk_color color) { struct nk_window *win; const struct nk_style *style; struct nk_vec2 item_padding; struct nk_rect bounds; struct nk_text text; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; win = ctx->current; style = &ctx->style; nk_panel_alloc_space(&bounds, ctx); item_padding = style->text.padding; text.padding.x = item_padding.x; text.padding.y = item_padding.y; text.background = style->window.background; text.text = color; nk_widget_text(&win->buffer, bounds, str, len, &text, alignment, style->font); } NK_API void nk_text_wrap_colored(struct nk_context *ctx, const char *str, int len, struct nk_color color) { struct nk_window *win; const struct nk_style *style; struct nk_vec2 item_padding; struct nk_rect bounds; struct nk_text text; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; win = ctx->current; style = &ctx->style; nk_panel_alloc_space(&bounds, ctx); item_padding = style->text.padding; text.padding.x = item_padding.x; text.padding.y = item_padding.y; text.background = style->window.background; text.text = color; nk_widget_text_wrap(&win->buffer, bounds, str, len, &text, style->font); } #ifdef NK_INCLUDE_STANDARD_VARARGS NK_API void nk_labelf_colored(struct nk_context *ctx, nk_flags flags, struct nk_color color, const char *fmt, ...) { char buf[256]; va_list args; va_start(args, fmt); nk_strfmt(buf, NK_LEN(buf), fmt, args); nk_label_colored(ctx, buf, flags, color); va_end(args); } NK_API void nk_labelf_colored_wrap(struct nk_context *ctx, struct nk_color color, const char *fmt, ...) { char buf[256]; va_list args; va_start(args, fmt); nk_strfmt(buf, NK_LEN(buf), fmt, args); nk_label_colored_wrap(ctx, buf, color); va_end(args); } NK_API void nk_labelf(struct nk_context *ctx, nk_flags flags, const char *fmt, ...) { char buf[256]; va_list args; va_start(args, fmt); nk_strfmt(buf, NK_LEN(buf), fmt, args); nk_label(ctx, buf, flags); va_end(args); } NK_API void nk_labelf_wrap(struct nk_context *ctx, const char *fmt,...) { char buf[256]; va_list args; va_start(args, fmt); nk_strfmt(buf, NK_LEN(buf), fmt, args); nk_label_wrap(ctx, buf); va_end(args); } NK_API void nk_value_bool(struct nk_context *ctx, const char *prefix, int value) {nk_labelf(ctx, NK_TEXT_LEFT, "%s: %s", prefix, ((value) ? "true": "false"));} NK_API void nk_value_int(struct nk_context *ctx, const char *prefix, int value) {nk_labelf(ctx, NK_TEXT_LEFT, "%s: %d", prefix, value);} NK_API void nk_value_uint(struct nk_context *ctx, const char *prefix, unsigned int value) {nk_labelf(ctx, NK_TEXT_LEFT, "%s: %u", prefix, value);} NK_API void nk_value_float(struct nk_context *ctx, const char *prefix, float value) { double double_value = (double)value; nk_labelf(ctx, NK_TEXT_LEFT, "%s: %.3f", prefix, double_value); } NK_API void nk_value_color_byte(struct nk_context *ctx, const char *p, struct nk_color c) {nk_labelf(ctx, NK_TEXT_LEFT, "%s: (%c, %c, %c, %c)", p, c.r, c.g, c.b, c.a);} NK_API void nk_value_color_float(struct nk_context *ctx, const char *p, struct nk_color color) { double c[4]; nk_color_dv(c, color); nk_labelf(ctx, NK_TEXT_LEFT, "%s: (%.2f, %.2f, %.2f, %.2f)", p, c[0], c[1], c[2], c[3]); } NK_API void nk_value_color_hex(struct nk_context *ctx, const char *prefix, struct nk_color color) { char hex[16]; nk_color_hex_rgba(hex, color); nk_labelf(ctx, NK_TEXT_LEFT, "%s: %s", prefix, hex); } #endif NK_API void nk_text(struct nk_context *ctx, const char *str, int len, nk_flags alignment) { NK_ASSERT(ctx); if (!ctx) return; nk_text_colored(ctx, str, len, alignment, ctx->style.text.color); } NK_API void nk_text_wrap(struct nk_context *ctx, const char *str, int len) { NK_ASSERT(ctx); if (!ctx) return; nk_text_wrap_colored(ctx, str, len, ctx->style.text.color); } NK_API void nk_label(struct nk_context *ctx, const char *str, nk_flags alignment) {nk_text(ctx, str, nk_strlen(str), alignment);} NK_API void nk_label_colored(struct nk_context *ctx, const char *str, nk_flags align, struct nk_color color) {nk_text_colored(ctx, str, nk_strlen(str), align, color);} NK_API void nk_label_wrap(struct nk_context *ctx, const char *str) {nk_text_wrap(ctx, str, nk_strlen(str));} NK_API void nk_label_colored_wrap(struct nk_context *ctx, const char *str, struct nk_color color) {nk_text_wrap_colored(ctx, str, nk_strlen(str), color);} NK_API void nk_image(struct nk_context *ctx, struct nk_image img) { struct nk_window *win; struct nk_rect bounds; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; win = ctx->current; if (!nk_widget(&bounds, ctx)) return; nk_draw_image(&win->buffer, bounds, &img, nk_white); } /*---------------------------------------------------------------- * * BUTTON * * --------------------------------------------------------------*/ NK_API void nk_button_set_behavior(struct nk_context *ctx, enum nk_button_behavior behavior) { NK_ASSERT(ctx); if (!ctx) return; ctx->button_behavior = behavior; } NK_API int nk_button_push_behavior(struct nk_context *ctx, enum nk_button_behavior behavior) { struct nk_config_stack_button_behavior *button_stack; struct nk_config_stack_button_behavior_element *element; NK_ASSERT(ctx); if (!ctx) return 0; button_stack = &ctx->stacks.button_behaviors; NK_ASSERT(button_stack->head < (int)NK_LEN(button_stack->elements)); if (button_stack->head >= (int)NK_LEN(button_stack->elements)) return 0; element = &button_stack->elements[button_stack->head++]; element->address = &ctx->button_behavior; element->old_value = ctx->button_behavior; ctx->button_behavior = behavior; return 1; } NK_API int nk_button_pop_behavior(struct nk_context *ctx) { struct nk_config_stack_button_behavior *button_stack; struct nk_config_stack_button_behavior_element *element; NK_ASSERT(ctx); if (!ctx) return 0; button_stack = &ctx->stacks.button_behaviors; NK_ASSERT(button_stack->head > 0); if (button_stack->head < 1) return 0; element = &button_stack->elements[--button_stack->head]; *element->address = element->old_value; return 1; } NK_API int nk_button_text(struct nk_context *ctx, const char *title, int len) { struct nk_window *win; struct nk_panel *layout; const struct nk_input *in; const struct nk_style *style; struct nk_rect bounds; enum nk_widget_layout_states state; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; style = &ctx->style; layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return 0; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_text(&ctx->last_widget_state, &win->buffer, bounds, title, len, style->button.text_alignment, ctx->button_behavior, &style->button, in, style->font); } NK_API int nk_button_label(struct nk_context *ctx, const char *title) {return nk_button_text(ctx, title, nk_strlen(title));} NK_API int nk_button_color(struct nk_context *ctx, struct nk_color color) { struct nk_window *win; struct nk_panel *layout; const struct nk_input *in; struct nk_style_button button; int ret = 0; struct nk_rect bounds; struct nk_rect content; enum nk_widget_layout_states state; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return 0; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; button = ctx->style.button; button.normal = nk_style_item_color(color); button.hover = nk_style_item_color(color); button.active = nk_style_item_color(color); ret = nk_do_button(&ctx->last_widget_state, &win->buffer, bounds, &button, in, ctx->button_behavior, &content); nk_draw_button(&win->buffer, &bounds, ctx->last_widget_state, &button); return ret; } NK_API int nk_button_symbol(struct nk_context *ctx, enum nk_symbol_type symbol) { struct nk_window *win; struct nk_panel *layout; const struct nk_input *in; const struct nk_style *style; struct nk_rect bounds; enum nk_widget_layout_states state; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; style = &ctx->style; layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return 0; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_symbol(&ctx->last_widget_state, &win->buffer, bounds, symbol, ctx->button_behavior, &style->button, in, style->font); } NK_API int nk_button_image(struct nk_context *ctx, struct nk_image img) { struct nk_window *win; struct nk_panel *layout; const struct nk_input *in; const struct nk_style *style; struct nk_rect bounds; enum nk_widget_layout_states state; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; style = &ctx->style; layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return 0; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_image(&ctx->last_widget_state, &win->buffer, bounds, img, ctx->button_behavior, &style->button, in); } NK_API int nk_button_symbol_text(struct nk_context *ctx, enum nk_symbol_type symbol, const char* text, int len, nk_flags align) { struct nk_window *win; struct nk_panel *layout; const struct nk_input *in; const struct nk_style *style; struct nk_rect bounds; enum nk_widget_layout_states state; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; style = &ctx->style; layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return 0; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_text_symbol(&ctx->last_widget_state, &win->buffer, bounds, symbol, text, len, align, ctx->button_behavior, &style->button, style->font, in); } NK_API int nk_button_symbol_label(struct nk_context *ctx, enum nk_symbol_type symbol, const char *label, nk_flags align) {return nk_button_symbol_text(ctx, symbol, label, nk_strlen(label), align);} NK_API int nk_button_image_text(struct nk_context *ctx, struct nk_image img, const char *text, int len, nk_flags align) { struct nk_window *win; struct nk_panel *layout; const struct nk_input *in; const struct nk_style *style; struct nk_rect bounds; enum nk_widget_layout_states state; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; style = &ctx->style; layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return 0; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_text_image(&ctx->last_widget_state, &win->buffer, bounds, img, text, len, align, ctx->button_behavior, &style->button, style->font, in); } NK_API int nk_button_image_label(struct nk_context *ctx, struct nk_image img, const char *label, nk_flags align) {return nk_button_image_text(ctx, img, label, nk_strlen(label), align);} /*---------------------------------------------------------------- * * SELECTABLE * * --------------------------------------------------------------*/ NK_API int nk_selectable_text(struct nk_context *ctx, const char *str, int len, nk_flags align, int *value) { struct nk_window *win; struct nk_panel *layout; const struct nk_input *in; const struct nk_style *style; enum nk_widget_layout_states state; struct nk_rect bounds; NK_ASSERT(ctx); NK_ASSERT(value); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout || !value) return 0; win = ctx->current; layout = win->layout; style = &ctx->style; state = nk_widget(&bounds, ctx); if (!state) return 0; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_selectable(&ctx->last_widget_state, &win->buffer, bounds, str, len, align, value, &style->selectable, in, style->font); } NK_API int nk_selectable_image_text(struct nk_context *ctx, struct nk_image img, const char *str, int len, nk_flags align, int *value) { struct nk_window *win; struct nk_panel *layout; const struct nk_input *in; const struct nk_style *style; enum nk_widget_layout_states state; struct nk_rect bounds; NK_ASSERT(ctx); NK_ASSERT(value); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout || !value) return 0; win = ctx->current; layout = win->layout; style = &ctx->style; state = nk_widget(&bounds, ctx); if (!state) return 0; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_selectable_image(&ctx->last_widget_state, &win->buffer, bounds, str, len, align, value, &img, &style->selectable, in, style->font); } NK_API int nk_select_text(struct nk_context *ctx, const char *str, int len, nk_flags align, int value) {nk_selectable_text(ctx, str, len, align, &value);return value;} NK_API int nk_selectable_label(struct nk_context *ctx, const char *str, nk_flags align, int *value) {return nk_selectable_text(ctx, str, nk_strlen(str), align, value);} NK_API int nk_selectable_image_label(struct nk_context *ctx,struct nk_image img, const char *str, nk_flags align, int *value) {return nk_selectable_image_text(ctx, img, str, nk_strlen(str), align, value);} NK_API int nk_select_label(struct nk_context *ctx, const char *str, nk_flags align, int value) {nk_selectable_text(ctx, str, nk_strlen(str), align, &value);return value;} NK_API int nk_select_image_label(struct nk_context *ctx, struct nk_image img, const char *str, nk_flags align, int value) {nk_selectable_image_text(ctx, img, str, nk_strlen(str), align, &value);return value;} NK_API int nk_select_image_text(struct nk_context *ctx, struct nk_image img, const char *str, int len, nk_flags align, int value) {nk_selectable_image_text(ctx, img, str, len, align, &value);return value;} /*---------------------------------------------------------------- * * CHECKBOX * * --------------------------------------------------------------*/ NK_API int nk_check_text(struct nk_context *ctx, const char *text, int len, int active) { struct nk_window *win; struct nk_panel *layout; const struct nk_input *in; const struct nk_style *style; struct nk_rect bounds; enum nk_widget_layout_states state; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return active; win = ctx->current; style = &ctx->style; layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return active; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &active, text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font); return active; } NK_API unsigned int nk_check_flags_text(struct nk_context *ctx, const char *text, int len, unsigned int flags, unsigned int value) { int old_active; NK_ASSERT(ctx); NK_ASSERT(text); if (!ctx || !text) return flags; old_active = (int)((flags & value) & value); if (nk_check_text(ctx, text, len, old_active)) flags |= value; else flags &= ~value; return flags; } NK_API int nk_checkbox_text(struct nk_context *ctx, const char *text, int len, int *active) { int old_val; NK_ASSERT(ctx); NK_ASSERT(text); NK_ASSERT(active); if (!ctx || !text || !active) return 0; old_val = *active; *active = nk_check_text(ctx, text, len, *active); return old_val != *active; } NK_API int nk_checkbox_flags_text(struct nk_context *ctx, const char *text, int len, unsigned int *flags, unsigned int value) { int active; NK_ASSERT(ctx); NK_ASSERT(text); NK_ASSERT(flags); if (!ctx || !text || !flags) return 0; active = (int)((*flags & value) & value); if (nk_checkbox_text(ctx, text, len, &active)) { if (active) *flags |= value; else *flags &= ~value; return 1; } return 0; } NK_API int nk_check_label(struct nk_context *ctx, const char *label, int active) {return nk_check_text(ctx, label, nk_strlen(label), active);} NK_API unsigned int nk_check_flags_label(struct nk_context *ctx, const char *label, unsigned int flags, unsigned int value) {return nk_check_flags_text(ctx, label, nk_strlen(label), flags, value);} NK_API int nk_checkbox_label(struct nk_context *ctx, const char *label, int *active) {return nk_checkbox_text(ctx, label, nk_strlen(label), active);} NK_API int nk_checkbox_flags_label(struct nk_context *ctx, const char *label, unsigned int *flags, unsigned int value) {return nk_checkbox_flags_text(ctx, label, nk_strlen(label), flags, value);} /*---------------------------------------------------------------- * * OPTION * * --------------------------------------------------------------*/ NK_API int nk_option_text(struct nk_context *ctx, const char *text, int len, int is_active) { struct nk_window *win; struct nk_panel *layout; const struct nk_input *in; const struct nk_style *style; struct nk_rect bounds; enum nk_widget_layout_states state; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return is_active; win = ctx->current; style = &ctx->style; layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return state; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &is_active, text, len, NK_TOGGLE_OPTION, &style->option, in, style->font); return is_active; } NK_API int nk_radio_text(struct nk_context *ctx, const char *text, int len, int *active) { int old_value; NK_ASSERT(ctx); NK_ASSERT(text); NK_ASSERT(active); if (!ctx || !text || !active) return 0; old_value = *active; *active = nk_option_text(ctx, text, len, old_value); return old_value != *active; } NK_API int nk_option_label(struct nk_context *ctx, const char *label, int active) {return nk_option_text(ctx, label, nk_strlen(label), active);} NK_API int nk_radio_label(struct nk_context *ctx, const char *label, int *active) {return nk_radio_text(ctx, label, nk_strlen(label), active);} /*---------------------------------------------------------------- * * SLIDER * * --------------------------------------------------------------*/ NK_API int nk_slider_float(struct nk_context *ctx, float min_value, float *value, float max_value, float value_step) { struct nk_window *win; struct nk_panel *layout; struct nk_input *in; const struct nk_style *style; int ret = 0; float old_value; struct nk_rect bounds; enum nk_widget_layout_states state; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); NK_ASSERT(value); if (!ctx || !ctx->current || !ctx->current->layout || !value) return ret; win = ctx->current; style = &ctx->style; layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return ret; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; old_value = *value; *value = nk_do_slider(&ctx->last_widget_state, &win->buffer, bounds, min_value, old_value, max_value, value_step, &style->slider, in, style->font); return (old_value > *value || old_value < *value); } NK_API float nk_slide_float(struct nk_context *ctx, float min, float val, float max, float step) { nk_slider_float(ctx, min, &val, max, step); return val; } NK_API int nk_slide_int(struct nk_context *ctx, int min, int val, int max, int step) { float value = (float)val; nk_slider_float(ctx, (float)min, &value, (float)max, (float)step); return (int)value; } NK_API int nk_slider_int(struct nk_context *ctx, int min, int *val, int max, int step) { int ret; float value = (float)*val; ret = nk_slider_float(ctx, (float)min, &value, (float)max, (float)step); *val = (int)value; return ret; } /*---------------------------------------------------------------- * * PROGRESSBAR * * --------------------------------------------------------------*/ NK_API int nk_progress(struct nk_context *ctx, nk_size *cur, nk_size max, int is_modifyable) { struct nk_window *win; struct nk_panel *layout; const struct nk_style *style; const struct nk_input *in; struct nk_rect bounds; enum nk_widget_layout_states state; nk_size old_value; NK_ASSERT(ctx); NK_ASSERT(cur); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout || !cur) return 0; win = ctx->current; style = &ctx->style; layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return 0; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; old_value = *cur; *cur = nk_do_progress(&ctx->last_widget_state, &win->buffer, bounds, *cur, max, is_modifyable, &style->progress, in); return (*cur != old_value); } NK_API nk_size nk_prog(struct nk_context *ctx, nk_size cur, nk_size max, int modifyable) {nk_progress(ctx, &cur, max, modifyable);return cur;} /*---------------------------------------------------------------- * * EDIT * * --------------------------------------------------------------*/ NK_API nk_flags nk_edit_string(struct nk_context *ctx, nk_flags flags, char *memory, int *len, int max, nk_plugin_filter filter) { nk_hash hash; nk_flags state; struct nk_text_edit *edit; struct nk_window *win; NK_ASSERT(ctx); NK_ASSERT(memory); NK_ASSERT(len); if (!ctx || !memory || !len) return 0; filter = (!filter) ? nk_filter_default: filter; win = ctx->current; hash = win->edit.seq; edit = &ctx->text_edit; nk_textedit_clear_state(&ctx->text_edit, (flags & NK_EDIT_MULTILINE)? NK_TEXT_EDIT_MULTI_LINE: NK_TEXT_EDIT_SINGLE_LINE, filter); if (win->edit.active && hash == win->edit.name) { if (flags & NK_EDIT_NO_CURSOR) edit->cursor = nk_utf_len(memory, *len); else edit->cursor = win->edit.cursor; if (!(flags & NK_EDIT_SELECTABLE)) { edit->select_start = win->edit.cursor; edit->select_end = win->edit.cursor; } else { edit->select_start = win->edit.sel_start; edit->select_end = win->edit.sel_end; } edit->mode = win->edit.mode; edit->scrollbar.x = (float)win->edit.scrollbar.x; edit->scrollbar.y = (float)win->edit.scrollbar.y; edit->active = nk_true; } else edit->active = nk_false; max = NK_MAX(1, max); *len = NK_MIN(*len, max-1); nk_str_init_fixed(&edit->string, memory, (nk_size)max); edit->string.buffer.allocated = (nk_size)*len; edit->string.len = nk_utf_len(memory, *len); state = nk_edit_buffer(ctx, flags, edit, filter); *len = (int)edit->string.buffer.allocated; if (edit->active) { win->edit.cursor = edit->cursor; win->edit.sel_start = edit->select_start; win->edit.sel_end = edit->select_end; win->edit.mode = edit->mode; win->edit.scrollbar.x = (unsigned short)edit->scrollbar.x; win->edit.scrollbar.y = (unsigned short)edit->scrollbar.y; } return state; } NK_API nk_flags nk_edit_buffer(struct nk_context *ctx, nk_flags flags, struct nk_text_edit *edit, nk_plugin_filter filter) { struct nk_window *win; struct nk_style *style; struct nk_input *in; enum nk_widget_layout_states state; struct nk_rect bounds; nk_flags ret_flags = 0; unsigned char prev_state; nk_hash hash; /* make sure correct values */ NK_ASSERT(ctx); NK_ASSERT(edit); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; style = &ctx->style; state = nk_widget(&bounds, ctx); if (!state) return state; in = (win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; /* check if edit is currently hot item */ hash = win->edit.seq++; if (win->edit.active && hash == win->edit.name) { if (flags & NK_EDIT_NO_CURSOR) edit->cursor = edit->string.len; if (!(flags & NK_EDIT_SELECTABLE)) { edit->select_start = edit->cursor; edit->select_end = edit->cursor; } if (flags & NK_EDIT_CLIPBOARD) edit->clip = ctx->clip; } filter = (!filter) ? nk_filter_default: filter; prev_state = (unsigned char)edit->active; in = (flags & NK_EDIT_READ_ONLY) ? 0: in; ret_flags = nk_do_edit(&ctx->last_widget_state, &win->buffer, bounds, flags, filter, edit, &style->edit, in, style->font); if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) ctx->style.cursor_active = ctx->style.cursors[NK_CURSOR_TEXT]; if (edit->active && prev_state != edit->active) { /* current edit is now hot */ win->edit.active = nk_true; win->edit.name = hash; } else if (prev_state && !edit->active) { /* current edit is now cold */ win->edit.active = nk_false; } return ret_flags; } NK_API nk_flags nk_edit_string_zero_terminated(struct nk_context *ctx, nk_flags flags, char *buffer, int max, nk_plugin_filter filter) { nk_flags result; int len = nk_strlen(buffer); result = nk_edit_string(ctx, flags, buffer, &len, max, filter); buffer[NK_MIN(NK_MAX(max-1,0), len)] = '\0'; return result; } /*---------------------------------------------------------------- * * PROPERTY * * --------------------------------------------------------------*/ NK_INTERN struct nk_property_variant nk_property_variant_int(int value, int min_value, int max_value, int step) { struct nk_property_variant result; result.kind = NK_PROPERTY_INT; result.value.i = value; result.min_value.i = min_value; result.max_value.i = max_value; result.step.i = step; return result; } NK_INTERN struct nk_property_variant nk_property_variant_float(float value, float min_value, float max_value, float step) { struct nk_property_variant result; result.kind = NK_PROPERTY_FLOAT; result.value.f = value; result.min_value.f = min_value; result.max_value.f = max_value; result.step.f = step; return result; } NK_INTERN struct nk_property_variant nk_property_variant_double(double value, double min_value, double max_value, double step) { struct nk_property_variant result; result.kind = NK_PROPERTY_DOUBLE; result.value.d = value; result.min_value.d = min_value; result.max_value.d = max_value; result.step.d = step; return result; } NK_INTERN void nk_property(struct nk_context *ctx, const char *name, struct nk_property_variant *variant, float inc_per_pixel, const enum nk_property_filter filter) { struct nk_window *win; struct nk_panel *layout; struct nk_input *in; const struct nk_style *style; struct nk_rect bounds; enum nk_widget_layout_states s; int *state = 0; nk_hash hash = 0; char *buffer = 0; int *len = 0; int *cursor = 0; int old_state; char dummy_buffer[NK_MAX_NUMBER_BUFFER]; int dummy_state = NK_PROPERTY_DEFAULT; int dummy_length = 0; int dummy_cursor = 0; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; win = ctx->current; layout = win->layout; style = &ctx->style; s = nk_widget(&bounds, ctx); if (!s) return; in = (s == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; /* calculate hash from name */ if (name[0] == '#') { hash = nk_murmur_hash(name, (int)nk_strlen(name), win->property.seq++); name++; /* special number hash */ } else hash = nk_murmur_hash(name, (int)nk_strlen(name), 42); /* check if property is currently hot item */ if (win->property.active && hash == win->property.name) { buffer = win->property.buffer; len = &win->property.length; cursor = &win->property.cursor; state = &win->property.state; } else { buffer = dummy_buffer; len = &dummy_length; cursor = &dummy_cursor; state = &dummy_state; } /* execute property widget */ old_state = *state; nk_do_property(&ctx->last_widget_state, &win->buffer, bounds, name, variant, inc_per_pixel, buffer, len, state, cursor, &style->property, filter, in, style->font, &ctx->text_edit); if (in && *state != NK_PROPERTY_DEFAULT && !win->property.active) { /* current property is now hot */ win->property.active = 1; NK_MEMCPY(win->property.buffer, buffer, (nk_size)*len); win->property.length = *len; win->property.cursor = *cursor; win->property.state = *state; win->property.name = hash; if (*state == NK_PROPERTY_DRAG) { ctx->input.mouse.grab = nk_true; ctx->input.mouse.grabbed = nk_true; } } /* check if previously active property is now inactive */ if (*state == NK_PROPERTY_DEFAULT && old_state != NK_PROPERTY_DEFAULT) { if (old_state == NK_PROPERTY_DRAG) { ctx->input.mouse.grab = nk_false; ctx->input.mouse.grabbed = nk_false; ctx->input.mouse.ungrab = nk_true; } win->property.active = 0; } } NK_API void nk_property_int(struct nk_context *ctx, const char *name, int min, int *val, int max, int step, float inc_per_pixel) { struct nk_property_variant variant; NK_ASSERT(ctx); NK_ASSERT(name); NK_ASSERT(val); if (!ctx || !ctx->current || !name || !val) return; variant = nk_property_variant_int(*val, min, max, step); nk_property(ctx, name, &variant, inc_per_pixel, NK_FILTER_INT); *val = variant.value.i; } NK_API void nk_property_float(struct nk_context *ctx, const char *name, float min, float *val, float max, float step, float inc_per_pixel) { struct nk_property_variant variant; NK_ASSERT(ctx); NK_ASSERT(name); NK_ASSERT(val); if (!ctx || !ctx->current || !name || !val) return; variant = nk_property_variant_float(*val, min, max, step); nk_property(ctx, name, &variant, inc_per_pixel, NK_FILTER_FLOAT); *val = variant.value.f; } NK_API void nk_property_double(struct nk_context *ctx, const char *name, double min, double *val, double max, double step, float inc_per_pixel) { struct nk_property_variant variant; NK_ASSERT(ctx); NK_ASSERT(name); NK_ASSERT(val); if (!ctx || !ctx->current || !name || !val) return; variant = nk_property_variant_double(*val, min, max, step); nk_property(ctx, name, &variant, inc_per_pixel, NK_FILTER_FLOAT); *val = variant.value.d; } NK_API int nk_propertyi(struct nk_context *ctx, const char *name, int min, int val, int max, int step, float inc_per_pixel) { struct nk_property_variant variant; NK_ASSERT(ctx); NK_ASSERT(name); if (!ctx || !ctx->current || !name) return val; variant = nk_property_variant_int(val, min, max, step); nk_property(ctx, name, &variant, inc_per_pixel, NK_FILTER_INT); val = variant.value.i; return val; } NK_API float nk_propertyf(struct nk_context *ctx, const char *name, float min, float val, float max, float step, float inc_per_pixel) { struct nk_property_variant variant; NK_ASSERT(ctx); NK_ASSERT(name); if (!ctx || !ctx->current || !name) return val; variant = nk_property_variant_float(val, min, max, step); nk_property(ctx, name, &variant, inc_per_pixel, NK_FILTER_FLOAT); val = variant.value.f; return val; } NK_API double nk_propertyd(struct nk_context *ctx, const char *name, double min, double val, double max, double step, float inc_per_pixel) { struct nk_property_variant variant; NK_ASSERT(ctx); NK_ASSERT(name); if (!ctx || !ctx->current || !name) return val; variant = nk_property_variant_double(val, min, max, step); nk_property(ctx, name, &variant, inc_per_pixel, NK_FILTER_FLOAT); val = variant.value.d; return val; } /*---------------------------------------------------------------- * * COLOR PICKER * * --------------------------------------------------------------*/ NK_API int nk_color_pick(struct nk_context * ctx, struct nk_color *color, enum nk_color_format fmt) { struct nk_window *win; struct nk_panel *layout; const struct nk_style *config; const struct nk_input *in; enum nk_widget_layout_states state; struct nk_rect bounds; NK_ASSERT(ctx); NK_ASSERT(color); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout || !color) return 0; win = ctx->current; config = &ctx->style; layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return 0; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_color_picker(&ctx->last_widget_state, &win->buffer, color, fmt, bounds, nk_vec2(0,0), in, config->font); } NK_API struct nk_color nk_color_picker(struct nk_context *ctx, struct nk_color color, enum nk_color_format fmt) { nk_color_pick(ctx, &color, fmt); return color; } /* ------------------------------------------------------------- * * CHART * * --------------------------------------------------------------*/ NK_API int nk_chart_begin_colored(struct nk_context *ctx, enum nk_chart_type type, struct nk_color color, struct nk_color highlight, int count, float min_value, float max_value) { struct nk_window *win; struct nk_chart *chart; const struct nk_style *config; const struct nk_style_chart *style; const struct nk_style_item *background; struct nk_rect bounds = {0, 0, 0, 0}; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; if (!nk_widget(&bounds, ctx)) { chart = &ctx->current->layout->chart; nk_zero(chart, sizeof(*chart)); return 0; } win = ctx->current; config = &ctx->style; chart = &win->layout->chart; style = &config->chart; /* setup basic generic chart */ nk_zero(chart, sizeof(*chart)); chart->x = bounds.x + style->padding.x; chart->y = bounds.y + style->padding.y; chart->w = bounds.w - 2 * style->padding.x; chart->h = bounds.h - 2 * style->padding.y; chart->w = NK_MAX(chart->w, 2 * style->padding.x); chart->h = NK_MAX(chart->h, 2 * style->padding.y); /* add first slot into chart */ {struct nk_chart_slot *slot = &chart->slots[chart->slot++]; slot->type = type; slot->count = count; slot->color = color; slot->highlight = highlight; slot->min = NK_MIN(min_value, max_value); slot->max = NK_MAX(min_value, max_value); slot->range = slot->max - slot->min;} /* draw chart background */ background = &style->background; if (background->type == NK_STYLE_ITEM_IMAGE) { nk_draw_image(&win->buffer, bounds, &background->data.image, nk_white); } else { nk_fill_rect(&win->buffer, bounds, style->rounding, style->border_color); nk_fill_rect(&win->buffer, nk_shrink_rect(bounds, style->border), style->rounding, style->background.data.color); } return 1; } NK_API int nk_chart_begin(struct nk_context *ctx, const enum nk_chart_type type, int count, float min_value, float max_value) {return nk_chart_begin_colored(ctx, type, ctx->style.chart.color, ctx->style.chart.selected_color, count, min_value, max_value);} NK_API void nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type type, struct nk_color color, struct nk_color highlight, int count, float min_value, float max_value) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); NK_ASSERT(ctx->current->layout->chart.slot < NK_CHART_MAX_SLOT); if (!ctx || !ctx->current || !ctx->current->layout) return; if (ctx->current->layout->chart.slot >= NK_CHART_MAX_SLOT) return; /* add another slot into the graph */ {struct nk_chart *chart = &ctx->current->layout->chart; struct nk_chart_slot *slot = &chart->slots[chart->slot++]; slot->type = type; slot->count = count; slot->color = color; slot->highlight = highlight; slot->min = NK_MIN(min_value, max_value); slot->max = NK_MAX(min_value, max_value); slot->range = slot->max - slot->min;} } NK_API void nk_chart_add_slot(struct nk_context *ctx, const enum nk_chart_type type, int count, float min_value, float max_value) {nk_chart_add_slot_colored(ctx, type, ctx->style.chart.color, ctx->style.chart.selected_color, count, min_value, max_value);} NK_INTERN nk_flags nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, struct nk_chart *g, float value, int slot) { struct nk_panel *layout = win->layout; const struct nk_input *i = &ctx->input; struct nk_command_buffer *out = &win->buffer; nk_flags ret = 0; struct nk_vec2 cur; struct nk_rect bounds; struct nk_color color; float step; float range; float ratio; NK_ASSERT(slot >= 0 && slot < NK_CHART_MAX_SLOT); step = g->w / (float)g->slots[slot].count; range = g->slots[slot].max - g->slots[slot].min; ratio = (value - g->slots[slot].min) / range; if (g->slots[slot].index == 0) { /* first data point does not have a connection */ g->slots[slot].last.x = g->x; g->slots[slot].last.y = (g->y + g->h) - ratio * (float)g->h; bounds.x = g->slots[slot].last.x - 2; bounds.y = g->slots[slot].last.y - 2; bounds.w = 4; bounds.h = 4; color = g->slots[slot].color; if (!(layout->flags & NK_WINDOW_ROM) && NK_INBOX(i->mouse.pos.x,i->mouse.pos.y, g->slots[slot].last.x-3, g->slots[slot].last.y-3, 6, 6)){ ret = nk_input_is_mouse_hovering_rect(i, bounds) ? NK_CHART_HOVERING : 0; ret |= (i->mouse.buttons[NK_BUTTON_LEFT].down && i->mouse.buttons[NK_BUTTON_LEFT].clicked) ? NK_CHART_CLICKED: 0; color = g->slots[slot].highlight; } nk_fill_rect(out, bounds, 0, color); g->slots[slot].index += 1; return ret; } /* draw a line between the last data point and the new one */ color = g->slots[slot].color; cur.x = g->x + (float)(step * (float)g->slots[slot].index); cur.y = (g->y + g->h) - (ratio * (float)g->h); nk_stroke_line(out, g->slots[slot].last.x, g->slots[slot].last.y, cur.x, cur.y, 1.0f, color); bounds.x = cur.x - 3; bounds.y = cur.y - 3; bounds.w = 6; bounds.h = 6; /* user selection of current data point */ if (!(layout->flags & NK_WINDOW_ROM)) { if (nk_input_is_mouse_hovering_rect(i, bounds)) { ret = NK_CHART_HOVERING; ret |= (!i->mouse.buttons[NK_BUTTON_LEFT].down && i->mouse.buttons[NK_BUTTON_LEFT].clicked) ? NK_CHART_CLICKED: 0; color = g->slots[slot].highlight; } } nk_fill_rect(out, nk_rect(cur.x - 2, cur.y - 2, 4, 4), 0, color); /* save current data point position */ g->slots[slot].last.x = cur.x; g->slots[slot].last.y = cur.y; g->slots[slot].index += 1; return ret; } NK_INTERN nk_flags nk_chart_push_column(const struct nk_context *ctx, struct nk_window *win, struct nk_chart *chart, float value, int slot) { struct nk_command_buffer *out = &win->buffer; const struct nk_input *in = &ctx->input; struct nk_panel *layout = win->layout; float ratio; nk_flags ret = 0; struct nk_color color; struct nk_rect item = {0,0,0,0}; NK_ASSERT(slot >= 0 && slot < NK_CHART_MAX_SLOT); if (chart->slots[slot].index >= chart->slots[slot].count) return nk_false; if (chart->slots[slot].count) { float padding = (float)(chart->slots[slot].count-1); item.w = (chart->w - padding) / (float)(chart->slots[slot].count); } /* calculate bounds of current bar chart entry */ color = chart->slots[slot].color;; item.h = chart->h * NK_ABS((value/chart->slots[slot].range)); if (value >= 0) { ratio = (value + NK_ABS(chart->slots[slot].min)) / NK_ABS(chart->slots[slot].range); item.y = (chart->y + chart->h) - chart->h * ratio; } else { ratio = (value - chart->slots[slot].max) / chart->slots[slot].range; item.y = chart->y + (chart->h * NK_ABS(ratio)) - item.h; } item.x = chart->x + ((float)chart->slots[slot].index * item.w); item.x = item.x + ((float)chart->slots[slot].index); /* user chart bar selection */ if (!(layout->flags & NK_WINDOW_ROM) && NK_INBOX(in->mouse.pos.x,in->mouse.pos.y,item.x,item.y,item.w,item.h)) { ret = NK_CHART_HOVERING; ret |= (!in->mouse.buttons[NK_BUTTON_LEFT].down && in->mouse.buttons[NK_BUTTON_LEFT].clicked) ? NK_CHART_CLICKED: 0; color = chart->slots[slot].highlight; } nk_fill_rect(out, item, 0, color); chart->slots[slot].index += 1; return ret; } NK_API nk_flags nk_chart_push_slot(struct nk_context *ctx, float value, int slot) { nk_flags flags; struct nk_window *win; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(slot >= 0 && slot < NK_CHART_MAX_SLOT); NK_ASSERT(slot < ctx->current->layout->chart.slot); if (!ctx || !ctx->current || slot >= NK_CHART_MAX_SLOT) return nk_false; if (slot >= ctx->current->layout->chart.slot) return nk_false; win = ctx->current; if (win->layout->chart.slot < slot) return nk_false; switch (win->layout->chart.slots[slot].type) { case NK_CHART_LINES: flags = nk_chart_push_line(ctx, win, &win->layout->chart, value, slot); break; case NK_CHART_COLUMN: flags = nk_chart_push_column(ctx, win, &win->layout->chart, value, slot); break; default: case NK_CHART_MAX: flags = 0; } return flags; } NK_API nk_flags nk_chart_push(struct nk_context *ctx, float value) {return nk_chart_push_slot(ctx, value, 0);} NK_API void nk_chart_end(struct nk_context *ctx) { struct nk_window *win; struct nk_chart *chart; NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return; win = ctx->current; chart = &win->layout->chart; NK_MEMSET(chart, 0, sizeof(*chart)); return; } NK_API void nk_plot(struct nk_context *ctx, enum nk_chart_type type, const float *values, int count, int offset) { int i = 0; float min_value; float max_value; NK_ASSERT(ctx); NK_ASSERT(values); if (!ctx || !values || !count) return; min_value = values[offset]; max_value = values[offset]; for (i = 0; i < count; ++i) { min_value = NK_MIN(values[i + offset], min_value); max_value = NK_MAX(values[i + offset], max_value); } nk_chart_begin(ctx, type, count, min_value, max_value); for (i = 0; i < count; ++i) nk_chart_push(ctx, values[i + offset]); nk_chart_end(ctx); } NK_API void nk_plot_function(struct nk_context *ctx, enum nk_chart_type type, void *userdata, float(*value_getter)(void* user, int index), int count, int offset) { int i = 0; float min_value; float max_value; NK_ASSERT(ctx); NK_ASSERT(value_getter); if (!ctx || !value_getter || !count) return; max_value = min_value = value_getter(userdata, offset); for (i = 0; i < count; ++i) { float value = value_getter(userdata, i + offset); min_value = NK_MIN(value, min_value); max_value = NK_MAX(value, max_value); } nk_chart_begin(ctx, type, count, min_value, max_value); for (i = 0; i < count; ++i) nk_chart_push(ctx, value_getter(userdata, i + offset)); nk_chart_end(ctx); } /* ------------------------------------------------------------- * * GROUP * * --------------------------------------------------------------*/ NK_API int nk_group_begin(struct nk_context *ctx, struct nk_panel *layout, const char *title, nk_flags flags) { struct nk_window *win; const struct nk_rect *c; union {struct nk_scroll *s; nk_uint *i;} value; struct nk_window panel; struct nk_rect bounds; nk_hash title_hash; int title_len; NK_ASSERT(ctx); NK_ASSERT(title); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout || !title) return 0; /* allocate space for the group panel inside the panel */ win = ctx->current; c = &win->layout->clip; nk_panel_alloc_space(&bounds, ctx); nk_zero(layout, sizeof(*layout)); /* This triggers either if you pass the same panel to parent window or parent and child group * or forgot to add a `nk_group_end` to a `nk_group_begin`. */ NK_ASSERT(win->layout != layout && "Parent and group are not allowed to use the same panel"); /* find persistent group scrollbar value */ title_len = (int)nk_strlen(title); title_hash = nk_murmur_hash(title, (int)title_len, NK_PANEL_GROUP); value.i = nk_find_value(win, title_hash); if (!value.i) { value.i = nk_add_value(ctx, win, title_hash, 0); *value.i = 0; } if (!NK_INTERSECT(c->x, c->y, c->w, c->h, bounds.x, bounds.y, bounds.w, bounds.h) && !(flags & NK_WINDOW_MOVABLE)) { return 0; } if (win->flags & NK_WINDOW_ROM) flags |= NK_WINDOW_ROM; /* initialize a fake window to create the layout from */ nk_zero(&panel, sizeof(panel)); panel.bounds = bounds; panel.flags = flags; panel.scrollbar.x = (unsigned short)value.s->x; panel.scrollbar.y = (unsigned short)value.s->y; panel.buffer = win->buffer; panel.layout = layout; ctx->current = &panel; nk_panel_begin(ctx, (flags & NK_WINDOW_TITLE) ? title: 0, NK_PANEL_GROUP); win->buffer = panel.buffer; win->buffer.clip = layout->clip; layout->offset = value.s; layout->parent = win->layout; win->layout = layout; ctx->current = win; return 1; } NK_API void nk_group_end(struct nk_context *ctx) { struct nk_window *win; struct nk_panel *parent; struct nk_panel *g; struct nk_rect clip; struct nk_window pan; struct nk_vec2 panel_padding; NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return; /* make sure nk_group_begin was called correctly */ NK_ASSERT(ctx->current); win = ctx->current; NK_ASSERT(win->layout); g = win->layout; NK_ASSERT(g->parent); parent = g->parent; /* dummy window */ nk_zero_struct(pan); panel_padding = nk_panel_get_padding(&ctx->style, NK_PANEL_GROUP); pan.bounds.y = g->bounds.y - (g->header_height + g->menu.h); pan.bounds.x = g->bounds.x - panel_padding.x; pan.bounds.w = g->bounds.w + 2 * panel_padding.x; pan.bounds.h = g->bounds.h + g->header_height + g->menu.h; if (g->flags & NK_WINDOW_BORDER) { pan.bounds.x -= g->border; pan.bounds.y -= g->border; pan.bounds.w += 2*g->border; pan.bounds.h += 2*g->border; } if (!(g->flags & NK_WINDOW_NO_SCROLLBAR)) { pan.bounds.w += ctx->style.window.scrollbar_size.x; pan.bounds.h += ctx->style.window.scrollbar_size.y; } pan.scrollbar.x = (unsigned short)g->offset->x; pan.scrollbar.y = (unsigned short)g->offset->y; pan.flags = g->flags; pan.buffer = win->buffer; pan.layout = g; pan.parent = win; ctx->current = &pan; /* make sure group has correct clipping rectangle */ nk_unify(&clip, &parent->clip, pan.bounds.x, pan.bounds.y, pan.bounds.x + pan.bounds.w, pan.bounds.y + pan.bounds.h + panel_padding.x); nk_push_scissor(&pan.buffer, clip); nk_end(ctx); win->buffer = pan.buffer; nk_push_scissor(&win->buffer, parent->clip); ctx->current = win; win->layout = parent; g->bounds = pan.bounds; return; } /* -------------------------------------------------------------- * * POPUP * * --------------------------------------------------------------*/ NK_API int nk_popup_begin(struct nk_context *ctx, struct nk_panel *layout, enum nk_popup_type type, const char *title, nk_flags flags, struct nk_rect rect) { struct nk_window *popup; struct nk_window *win; struct nk_panel *panel; int title_len; nk_hash title_hash; nk_size allocated; NK_ASSERT(ctx); NK_ASSERT(title); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; panel = win->layout; NK_ASSERT(!(panel->type & NK_PANEL_SET_POPUP) && "popups are not allowed to have popups"); title_len = (int)nk_strlen(title); title_hash = nk_murmur_hash(title, (int)title_len, NK_PANEL_POPUP); popup = win->popup.win; if (!popup) { popup = (struct nk_window*)nk_create_window(ctx); popup->parent = win; win->popup.win = popup; win->popup.active = 0; win->popup.type = NK_PANEL_POPUP; } /* make sure we have to correct popup */ if (win->popup.name != title_hash) { if (!win->popup.active) { nk_zero(popup, sizeof(*popup)); win->popup.name = title_hash; win->popup.active = 1; win->popup.type = NK_PANEL_POPUP; } else return 0; } /* popup position is local to window */ ctx->current = popup; rect.x += win->layout->clip.x; rect.y += win->layout->clip.y; /* setup popup data */ popup->parent = win; popup->bounds = rect; popup->seq = ctx->seq; popup->layout = layout; popup->flags = flags; popup->flags |= NK_WINDOW_BORDER; if (type == NK_POPUP_DYNAMIC) popup->flags |= NK_WINDOW_DYNAMIC; popup->buffer = win->buffer; nk_start_popup(ctx, win); allocated = ctx->memory.allocated; nk_push_scissor(&popup->buffer, nk_null_rect); if (nk_panel_begin(ctx, title, NK_PANEL_POPUP)) { /* popup is running therefore invalidate parent panels */ struct nk_panel *root; root = win->layout; while (root) { root->flags |= NK_WINDOW_ROM; root->flags &= ~(nk_flags)NK_WINDOW_REMOVE_ROM; root = root->parent; } win->popup.active = 1; layout->offset = &popup->scrollbar; layout->parent = win->layout; return 1; } else { /* popup was closed/is invalid so cleanup */ struct nk_panel *root; root = win->layout; while (root) { root->flags |= NK_WINDOW_REMOVE_ROM; root = root->parent; } win->layout->popup_buffer.active = 0; win->popup.active = 0; ctx->memory.allocated = allocated; ctx->current = win; return 0; } } NK_INTERN int nk_nonblock_begin(struct nk_panel *layout, struct nk_context *ctx, nk_flags flags, struct nk_rect body, struct nk_rect header, enum nk_panel_type panel_type) { struct nk_window *popup; struct nk_window *win; struct nk_panel *panel; int is_active = nk_true; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; /* popups cannot have popups */ win = ctx->current; panel = win->layout; NK_ASSERT(!(panel->type & NK_PANEL_SET_POPUP)); popup = win->popup.win; if (!popup) { /* create window for nonblocking popup */ popup = (struct nk_window*)nk_create_window(ctx); popup->parent = win; win->popup.win = popup; win->popup.type = panel_type; nk_command_buffer_init(&popup->buffer, &ctx->memory, NK_CLIPPING_ON); } else { /* close the popup if user pressed outside or in the header */ int pressed, in_body, in_header; pressed = nk_input_is_mouse_pressed(&ctx->input, NK_BUTTON_LEFT); in_body = nk_input_is_mouse_hovering_rect(&ctx->input, body); in_header = nk_input_is_mouse_hovering_rect(&ctx->input, header); if (pressed && (!in_body || in_header)) is_active = nk_false; } win->popup.header = header; if (!is_active) { /* remove read only mode from all parent panels */ struct nk_panel *root; root = win->layout; while (root) { root->flags |= NK_WINDOW_REMOVE_ROM; root = root->parent; } return is_active; } popup->bounds = body; popup->parent = win; popup->layout = layout; popup->flags = flags; popup->flags |= NK_WINDOW_BORDER; popup->flags |= NK_WINDOW_DYNAMIC; popup->seq = ctx->seq; win->popup.active = 1; nk_start_popup(ctx, win); popup->buffer = win->buffer; nk_push_scissor(&popup->buffer, nk_null_rect); ctx->current = popup; nk_panel_begin(ctx, 0, panel_type); win->buffer = popup->buffer; layout->parent = win->layout; layout->offset = &popup->scrollbar; /* set read only mode to all parent panels */ {struct nk_panel *root; root = win->layout; while (root) { root->flags |= NK_WINDOW_ROM; root = root->parent; }} return is_active; } NK_API void nk_popup_close(struct nk_context *ctx) { struct nk_window *popup; NK_ASSERT(ctx); if (!ctx || !ctx->current) return; popup = ctx->current; NK_ASSERT(popup->parent); NK_ASSERT(popup->layout->type & NK_PANEL_SET_POPUP); popup->flags |= NK_WINDOW_HIDDEN; } NK_API void nk_popup_end(struct nk_context *ctx) { struct nk_window *win; struct nk_window *popup; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; popup = ctx->current; if (!popup->parent) return; win = popup->parent; if (popup->flags & NK_WINDOW_HIDDEN) { struct nk_panel *root; root = win->layout; while (root) { root->flags |= NK_WINDOW_REMOVE_ROM; root = root->parent; } win->popup.active = 0; } nk_push_scissor(&popup->buffer, nk_null_rect); nk_end(ctx); win->buffer = popup->buffer; nk_finish_popup(ctx, win); ctx->current = win; nk_push_scissor(&win->buffer, win->layout->clip); } /* ------------------------------------------------------------- * * TOOLTIP * * -------------------------------------------------------------- */ NK_API int nk_tooltip_begin(struct nk_context *ctx, struct nk_panel *layout, float width) { struct nk_window *win; const struct nk_input *in; struct nk_rect bounds; int ret; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; /* make sure that no nonblocking popup is currently active */ win = ctx->current; in = &ctx->input; if (win->popup.win && (win->popup.type & NK_PANEL_SET_NONBLOCK)) return 0; bounds.w = width; bounds.h = nk_null_rect.h; bounds.x = (in->mouse.pos.x + 1) - win->layout->clip.x; bounds.y = (in->mouse.pos.y + 1) - win->layout->clip.y; ret = nk_popup_begin(ctx, layout, NK_POPUP_DYNAMIC, "__##Tooltip##__", NK_WINDOW_NO_SCROLLBAR|NK_WINDOW_BORDER, bounds); if (ret) win->layout->flags &= ~(nk_flags)NK_WINDOW_ROM; win->popup.type = NK_PANEL_TOOLTIP; layout->type = NK_PANEL_TOOLTIP; return ret; } NK_API void nk_tooltip_end(struct nk_context *ctx) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return; nk_popup_close(ctx); nk_popup_end(ctx); } NK_API void nk_tooltip(struct nk_context *ctx, const char *text) { const struct nk_style *style; struct nk_vec2 padding; struct nk_panel layout; int text_len; float text_width; float text_height; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); NK_ASSERT(text); if (!ctx || !ctx->current || !ctx->current->layout || !text) return; /* fetch configuration data */ style = &ctx->style; padding = style->window.padding; /* calculate size of the text and tooltip */ text_len = nk_strlen(text); text_width = style->font->width(style->font->userdata, style->font->height, text, text_len); text_width += (4 * padding.x); text_height = (style->font->height + 2 * padding.y); /* execute tooltip and fill with text */ if (nk_tooltip_begin(ctx, &layout, (float)text_width)) { nk_layout_row_dynamic(ctx, (float)text_height, 1); nk_text(ctx, text, text_len, NK_TEXT_LEFT); nk_tooltip_end(ctx); } } /* ------------------------------------------------------------- * * CONTEXTUAL * * -------------------------------------------------------------- */ NK_API int nk_contextual_begin(struct nk_context *ctx, struct nk_panel *layout, nk_flags flags, struct nk_vec2 size, struct nk_rect trigger_bounds) { struct nk_window *win; struct nk_window *popup; struct nk_rect body; NK_STORAGE const struct nk_rect null_rect = {0,0,0,0}; int is_clicked = 0; int is_active = 0; int is_open = 0; int ret = 0; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; ++win->popup.con_count; /* check if currently active contextual is active */ popup = win->popup.win; is_open = (popup && win->popup.type == NK_PANEL_CONTEXTUAL); is_clicked = nk_input_mouse_clicked(&ctx->input, NK_BUTTON_RIGHT, trigger_bounds); if (win->popup.active_con && win->popup.con_count != win->popup.active_con) return 0; if ((is_clicked && is_open && !is_active) || (!is_open && !is_active && !is_clicked)) return 0; /* calculate contextual position on click */ win->popup.active_con = win->popup.con_count; if (is_clicked) { body.x = ctx->input.mouse.pos.x; body.y = ctx->input.mouse.pos.y; } else { body.x = popup->bounds.x; body.y = popup->bounds.y; } body.w = size.x; body.h = size.y; /* start nonblocking contextual popup */ ret = nk_nonblock_begin(layout, ctx, flags|NK_WINDOW_NO_SCROLLBAR, body, null_rect, NK_PANEL_CONTEXTUAL); if (ret) win->popup.type = NK_PANEL_CONTEXTUAL; else { win->popup.active_con = 0; if (win->popup.win) win->popup.win->flags = 0; } return ret; } NK_API int nk_contextual_item_text(struct nk_context *ctx, const char *text, int len, nk_flags alignment) { struct nk_window *win; const struct nk_input *in; const struct nk_style *style; struct nk_rect bounds; enum nk_widget_layout_states state; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; style = &ctx->style; state = nk_widget_fitting(&bounds, ctx, style->contextual_button.padding); if (!state) return nk_false; in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_text(&ctx->last_widget_state, &win->buffer, bounds, text, len, alignment, NK_BUTTON_DEFAULT, &style->contextual_button, in, style->font)) { nk_contextual_close(ctx); return nk_true; } return nk_false; } NK_API int nk_contextual_item_label(struct nk_context *ctx, const char *label, nk_flags align) {return nk_contextual_item_text(ctx, label, nk_strlen(label), align);} NK_API int nk_contextual_item_image_text(struct nk_context *ctx, struct nk_image img, const char *text, int len, nk_flags align) { struct nk_window *win; const struct nk_input *in; const struct nk_style *style; struct nk_rect bounds; enum nk_widget_layout_states state; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; style = &ctx->style; state = nk_widget_fitting(&bounds, ctx, style->contextual_button.padding); if (!state) return nk_false; in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_text_image(&ctx->last_widget_state, &win->buffer, bounds, img, text, len, align, NK_BUTTON_DEFAULT, &style->contextual_button, style->font, in)){ nk_contextual_close(ctx); return nk_true; } return nk_false; } NK_API int nk_contextual_item_image_label(struct nk_context *ctx, struct nk_image img, const char *label, nk_flags align) {return nk_contextual_item_image_text(ctx, img, label, nk_strlen(label), align);} NK_API int nk_contextual_item_symbol_text(struct nk_context *ctx, enum nk_symbol_type symbol, const char *text, int len, nk_flags align) { struct nk_window *win; const struct nk_input *in; const struct nk_style *style; struct nk_rect bounds; enum nk_widget_layout_states state; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; style = &ctx->style; state = nk_widget_fitting(&bounds, ctx, style->contextual_button.padding); if (!state) return nk_false; in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_text_symbol(&ctx->last_widget_state, &win->buffer, bounds, symbol, text, len, align, NK_BUTTON_DEFAULT, &style->contextual_button, style->font, in)) { nk_contextual_close(ctx); return nk_true; } return nk_false; } NK_API int nk_contextual_item_symbol_label(struct nk_context *ctx, enum nk_symbol_type symbol, const char *text, nk_flags align) {return nk_contextual_item_symbol_text(ctx, symbol, text, nk_strlen(text), align);} NK_API void nk_contextual_close(struct nk_context *ctx) { NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; if (!ctx->current) return; nk_popup_close(ctx); } NK_API void nk_contextual_end(struct nk_context *ctx) { struct nk_window *popup; struct nk_panel *panel; NK_ASSERT(ctx); NK_ASSERT(ctx->current); if (!ctx || !ctx->current) return; popup = ctx->current; panel = popup->layout; NK_ASSERT(popup->parent); NK_ASSERT(panel->type & NK_PANEL_SET_POPUP); if (panel->flags & NK_WINDOW_DYNAMIC) { /* Close behavior This is a bit hack solution since we do not now before we end our popup how big it will be. We therefore do not directly now when a click outside the non-blocking popup must close it at that direct frame. Instead it will be closed in the next frame.*/ struct nk_rect body = {0,0,0,0}; if (panel->at_y < (panel->bounds.y + panel->bounds.h)) { struct nk_vec2 padding = nk_panel_get_padding(&ctx->style, panel->type); body = panel->bounds; body.y = (panel->at_y + panel->footer_height + panel->border + padding.y); body.h = (panel->bounds.y + panel->bounds.h) - body.y; } {int pressed = nk_input_is_mouse_pressed(&ctx->input, NK_BUTTON_LEFT); int in_body = nk_input_is_mouse_hovering_rect(&ctx->input, body); if (pressed && in_body) popup->flags |= NK_WINDOW_HIDDEN; } } if (popup->flags & NK_WINDOW_HIDDEN) popup->seq = 0; nk_popup_end(ctx); return; } /* ------------------------------------------------------------- * * COMBO * * --------------------------------------------------------------*/ NK_INTERN int nk_combo_begin(struct nk_panel *layout, struct nk_context *ctx, struct nk_window *win, struct nk_vec2 size, int is_clicked, struct nk_rect header) { struct nk_window *popup; int is_open = 0; int is_active = 0; struct nk_rect body; nk_hash hash; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; popup = win->popup.win; body.x = header.x; body.w = size.x; body.y = header.y + header.h-ctx->style.window.combo_border; body.h = size.y; hash = win->popup.combo_count++; is_open = (popup) ? nk_true:nk_false; is_active = (popup && (win->popup.name == hash) && win->popup.type == NK_PANEL_COMBO); if ((is_clicked && is_open && !is_active) || (is_open && !is_active) || (!is_open && !is_active && !is_clicked)) return 0; if (!nk_nonblock_begin(layout, ctx, 0, body, (is_clicked && is_open)?nk_rect(0,0,0,0):header, NK_PANEL_COMBO)) return 0; win->popup.type = NK_PANEL_COMBO; win->popup.name = hash; return 1; } NK_API int nk_combo_begin_text(struct nk_context *ctx, struct nk_panel *layout, const char *selected, int len, struct nk_vec2 size) { const struct nk_input *in; struct nk_window *win; struct nk_style *style; enum nk_widget_layout_states s; int is_clicked = nk_false; struct nk_rect header; const struct nk_style_item *background; struct nk_text text; NK_ASSERT(ctx); NK_ASSERT(selected); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout || !selected) return 0; win = ctx->current; style = &ctx->style; s = nk_widget(&header, ctx); if (s == NK_WIDGET_INVALID) return 0; in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; /* draw combo box header background and border */ if (ctx->last_widget_state & NK_WIDGET_STATE_ACTIVED) { background = &style->combo.active; text.text = style->combo.label_active; } else if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) { background = &style->combo.hover; text.text = style->combo.label_hover; } else { background = &style->combo.normal; text.text = style->combo.label_normal; } if (background->type == NK_STYLE_ITEM_IMAGE) { text.background = nk_rgba(0,0,0,0); nk_draw_image(&win->buffer, header, &background->data.image, nk_white); } else { text.background = background->data.color; nk_fill_rect(&win->buffer, header, style->combo.rounding, style->combo.border_color); nk_fill_rect(&win->buffer, nk_shrink_rect(header, 1), style->combo.rounding, background->data.color); } { /* print currently selected text item */ struct nk_rect label; struct nk_rect button; struct nk_rect content; enum nk_symbol_type sym; if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) sym = style->combo.sym_hover; else if (is_clicked) sym = style->combo.sym_active; else sym = style->combo.sym_normal; /* calculate button */ button.w = header.h - 2 * style->combo.button_padding.y; button.x = (header.x + header.w - header.h) - style->combo.button_padding.x; button.y = header.y + style->combo.button_padding.y; button.h = button.w; content.x = button.x + style->combo.button.padding.x; content.y = button.y + style->combo.button.padding.y; content.w = button.w - 2 * style->combo.button.padding.x; content.h = button.h - 2 * style->combo.button.padding.y; /* draw selected label */ text.padding = nk_vec2(0,0); label.x = header.x + style->combo.content_padding.x; label.y = header.y + style->combo.content_padding.y; label.w = button.x - (style->combo.content_padding.x + style->combo.spacing.x) - label.x;; label.h = header.h - 2 * style->combo.content_padding.y; nk_widget_text(&win->buffer, label, selected, len, &text, NK_TEXT_LEFT, ctx->style.font); /* draw open/close button */ nk_draw_button_symbol(&win->buffer, &button, &content, ctx->last_widget_state, &ctx->style.combo.button, sym, style->font); } return nk_combo_begin(layout, ctx, win, size, is_clicked, header); } NK_API int nk_combo_begin_label(struct nk_context *ctx, struct nk_panel *layout, const char *selected, struct nk_vec2 size) {return nk_combo_begin_text(ctx, layout, selected, nk_strlen(selected), size);} NK_API int nk_combo_begin_color(struct nk_context *ctx, struct nk_panel *layout, struct nk_color color, struct nk_vec2 size) { struct nk_window *win; struct nk_style *style; const struct nk_input *in; struct nk_rect header; int is_clicked = nk_false; enum nk_widget_layout_states s; const struct nk_style_item *background; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; style = &ctx->style; s = nk_widget(&header, ctx); if (s == NK_WIDGET_INVALID) return 0; in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; /* draw combo box header background and border */ if (ctx->last_widget_state & NK_WIDGET_STATE_ACTIVED) background = &style->combo.active; else if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) background = &style->combo.hover; else background = &style->combo.normal; if (background->type == NK_STYLE_ITEM_IMAGE) { nk_draw_image(&win->buffer, header, &background->data.image,nk_white); } else { nk_fill_rect(&win->buffer, header, 0, style->combo.border_color); nk_fill_rect(&win->buffer, nk_shrink_rect(header, 1), 0, background->data.color); } { struct nk_rect content; struct nk_rect button; struct nk_rect bounds; enum nk_symbol_type sym; if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) sym = style->combo.sym_hover; else if (is_clicked) sym = style->combo.sym_active; else sym = style->combo.sym_normal; /* calculate button */ button.w = header.h - 2 * style->combo.button_padding.y; button.x = (header.x + header.w - header.h) - style->combo.button_padding.x; button.y = header.y + style->combo.button_padding.y; button.h = button.w; content.x = button.x + style->combo.button.padding.x; content.y = button.y + style->combo.button.padding.y; content.w = button.w - 2 * style->combo.button.padding.x; content.h = button.h - 2 * style->combo.button.padding.y; /* draw color */ bounds.h = header.h - 4 * style->combo.content_padding.y; bounds.y = header.y + 2 * style->combo.content_padding.y; bounds.x = header.x + 2 * style->combo.content_padding.x; bounds.w = (button.x - (style->combo.content_padding.x + style->combo.spacing.x)) - bounds.x; nk_fill_rect(&win->buffer, bounds, 0, color); /* draw open/close button */ nk_draw_button_symbol(&win->buffer, &button, &content, ctx->last_widget_state, &ctx->style.combo.button, sym, style->font); } return nk_combo_begin(layout, ctx, win, size, is_clicked, header); } NK_API int nk_combo_begin_symbol(struct nk_context *ctx, struct nk_panel *layout, enum nk_symbol_type symbol, struct nk_vec2 size) { struct nk_window *win; struct nk_style *style; const struct nk_input *in; struct nk_rect header; int is_clicked = nk_false; enum nk_widget_layout_states s; const struct nk_style_item *background; struct nk_color sym_background; struct nk_color symbol_color; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; style = &ctx->style; s = nk_widget(&header, ctx); if (s == NK_WIDGET_INVALID) return 0; in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; /* draw combo box header background and border */ if (ctx->last_widget_state & NK_WIDGET_STATE_ACTIVED) { background = &style->combo.active; symbol_color = style->combo.symbol_active; } else if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) { background = &style->combo.hover; symbol_color = style->combo.symbol_hover; } else { background = &style->combo.normal; symbol_color = style->combo.symbol_hover; } if (background->type == NK_STYLE_ITEM_IMAGE) { sym_background = nk_rgba(0,0,0,0); nk_draw_image(&win->buffer, header, &background->data.image, nk_white); } else { sym_background = background->data.color; nk_fill_rect(&win->buffer, header, 0, style->combo.border_color); nk_fill_rect(&win->buffer, nk_shrink_rect(header, 1), 0, background->data.color); } { struct nk_rect bounds = {0,0,0,0}; struct nk_rect content; struct nk_rect button; enum nk_symbol_type sym; if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) sym = style->combo.sym_hover; else if (is_clicked) sym = style->combo.sym_active; else sym = style->combo.sym_normal; /* calculate button */ button.w = header.h - 2 * style->combo.button_padding.y; button.x = (header.x + header.w - header.h) - style->combo.button_padding.y; button.y = header.y + style->combo.button_padding.y; button.h = button.w; content.x = button.x + style->combo.button.padding.x; content.y = button.y + style->combo.button.padding.y; content.w = button.w - 2 * style->combo.button.padding.x; content.h = button.h - 2 * style->combo.button.padding.y; /* draw symbol */ bounds.h = header.h - 2 * style->combo.content_padding.y; bounds.y = header.y + style->combo.content_padding.y; bounds.x = header.x + style->combo.content_padding.x; bounds.w = (button.x - style->combo.content_padding.y) - bounds.x; nk_draw_symbol(&win->buffer, symbol, bounds, sym_background, symbol_color, 1.0f, style->font); /* draw open/close button */ nk_draw_button_symbol(&win->buffer, &bounds, &content, ctx->last_widget_state, &ctx->style.combo.button, sym, style->font); } return nk_combo_begin(layout, ctx, win, size, is_clicked, header); } NK_API int nk_combo_begin_symbol_text(struct nk_context *ctx, struct nk_panel *layout, const char *selected, int len, enum nk_symbol_type symbol, struct nk_vec2 size) { struct nk_window *win; struct nk_style *style; struct nk_input *in; struct nk_rect header; int is_clicked = nk_false; enum nk_widget_layout_states s; const struct nk_style_item *background; struct nk_color symbol_color; struct nk_text text; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; style = &ctx->style; s = nk_widget(&header, ctx); if (!s) return 0; in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; /* draw combo box header background and border */ if (ctx->last_widget_state & NK_WIDGET_STATE_ACTIVED) { background = &style->combo.active; symbol_color = style->combo.symbol_active; text.text = style->combo.label_active; } else if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) { background = &style->combo.hover; symbol_color = style->combo.symbol_hover; text.text = style->combo.label_hover; } else { background = &style->combo.normal; symbol_color = style->combo.symbol_normal; text.text = style->combo.label_normal; } if (background->type == NK_STYLE_ITEM_IMAGE) { text.background = nk_rgba(0,0,0,0); nk_draw_image(&win->buffer, header, &background->data.image, nk_white); } else { text.background = background->data.color; nk_fill_rect(&win->buffer, header, 0, style->combo.border_color); nk_fill_rect(&win->buffer, nk_shrink_rect(header, 1), 0, background->data.color); } { struct nk_rect content; struct nk_rect button; struct nk_rect label; struct nk_rect image; enum nk_symbol_type sym; if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) sym = style->combo.sym_hover; else if (is_clicked) sym = style->combo.sym_active; else sym = style->combo.sym_normal; /* calculate button */ button.w = header.h - 2 * style->combo.button_padding.y; button.x = (header.x + header.w - header.h) - style->combo.button_padding.x; button.y = header.y + style->combo.button_padding.y; button.h = button.w; content.x = button.x + style->combo.button.padding.x; content.y = button.y + style->combo.button.padding.y; content.w = button.w - 2 * style->combo.button.padding.x; content.h = button.h - 2 * style->combo.button.padding.y; nk_draw_button_symbol(&win->buffer, &button, &content, ctx->last_widget_state, &ctx->style.combo.button, sym, style->font); /* draw symbol */ image.x = header.x + style->combo.content_padding.x; image.y = header.y + style->combo.content_padding.y; image.h = header.h - 2 * style->combo.content_padding.y; image.w = image.h; nk_draw_symbol(&win->buffer, symbol, image, text.background, symbol_color, 1.0f, style->font); /* draw label */ text.padding = nk_vec2(0,0); label.x = image.x + image.w + style->combo.spacing.x + style->combo.content_padding.x; label.y = header.y + style->combo.content_padding.y; label.w = (button.x - style->combo.content_padding.x) - label.x; label.h = header.h - 2 * style->combo.content_padding.y; nk_widget_text(&win->buffer, label, selected, len, &text, NK_TEXT_LEFT, style->font); } return nk_combo_begin(layout, ctx, win, size, is_clicked, header); } NK_API int nk_combo_begin_image(struct nk_context *ctx, struct nk_panel *layout, struct nk_image img, struct nk_vec2 size) { struct nk_window *win; struct nk_style *style; const struct nk_input *in; struct nk_rect header; int is_clicked = nk_false; enum nk_widget_layout_states s; const struct nk_style_item *background; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; style = &ctx->style; s = nk_widget(&header, ctx); if (s == NK_WIDGET_INVALID) return 0; in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; /* draw combo box header background and border */ if (ctx->last_widget_state & NK_WIDGET_STATE_ACTIVED) background = &style->combo.active; else if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) background = &style->combo.hover; else background = &style->combo.normal; if (background->type == NK_STYLE_ITEM_IMAGE) { nk_draw_image(&win->buffer, header, &background->data.image, nk_white); } else { nk_fill_rect(&win->buffer, header, 0, style->combo.border_color); nk_fill_rect(&win->buffer, nk_shrink_rect(header, 1), 0, background->data.color); } { struct nk_rect bounds = {0,0,0,0}; struct nk_rect content; struct nk_rect button; enum nk_symbol_type sym; if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) sym = style->combo.sym_hover; else if (is_clicked) sym = style->combo.sym_active; else sym = style->combo.sym_normal; /* calculate button */ button.w = header.h - 2 * style->combo.button_padding.y; button.x = (header.x + header.w - header.h) - style->combo.button_padding.y; button.y = header.y + style->combo.button_padding.y; button.h = button.w; content.x = button.x + style->combo.button.padding.x; content.y = button.y + style->combo.button.padding.y; content.w = button.w - 2 * style->combo.button.padding.x; content.h = button.h - 2 * style->combo.button.padding.y; /* draw image */ bounds.h = header.h - 2 * style->combo.content_padding.y; bounds.y = header.y + style->combo.content_padding.y; bounds.x = header.x + style->combo.content_padding.x; bounds.w = (button.x - style->combo.content_padding.y) - bounds.x; nk_draw_image(&win->buffer, bounds, &img, nk_white); /* draw open/close button */ nk_draw_button_symbol(&win->buffer, &bounds, &content, ctx->last_widget_state, &ctx->style.combo.button, sym, style->font); } return nk_combo_begin(layout, ctx, win, size, is_clicked, header); } NK_API int nk_combo_begin_image_text(struct nk_context *ctx, struct nk_panel *layout, const char *selected, int len, struct nk_image img, struct nk_vec2 size) { struct nk_window *win; struct nk_style *style; struct nk_input *in; struct nk_rect header; int is_clicked = nk_false; enum nk_widget_layout_states s; const struct nk_style_item *background; struct nk_text text; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; style = &ctx->style; s = nk_widget(&header, ctx); if (!s) return 0; in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; /* draw combo box header background and border */ if (ctx->last_widget_state & NK_WIDGET_STATE_ACTIVED) { background = &style->combo.active; text.text = style->combo.label_active; } else if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) { background = &style->combo.hover; text.text = style->combo.label_hover; } else { background = &style->combo.normal; text.text = style->combo.label_normal; } if (background->type == NK_STYLE_ITEM_IMAGE) { text.background = nk_rgba(0,0,0,0); nk_draw_image(&win->buffer, header, &background->data.image, nk_white); } else { text.background = background->data.color; nk_fill_rect(&win->buffer, header, 0, style->combo.border_color); nk_fill_rect(&win->buffer, nk_shrink_rect(header, 1), 0, background->data.color); } { struct nk_rect content; struct nk_rect button; struct nk_rect label; struct nk_rect image; enum nk_symbol_type sym; if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) sym = style->combo.sym_hover; else if (is_clicked) sym = style->combo.sym_active; else sym = style->combo.sym_normal; /* calculate button */ button.w = header.h - 2 * style->combo.button_padding.y; button.x = (header.x + header.w - header.h) - style->combo.button_padding.x; button.y = header.y + style->combo.button_padding.y; button.h = button.w; content.x = button.x + style->combo.button.padding.x; content.y = button.y + style->combo.button.padding.y; content.w = button.w - 2 * style->combo.button.padding.x; content.h = button.h - 2 * style->combo.button.padding.y; nk_draw_button_symbol(&win->buffer, &button, &content, ctx->last_widget_state, &ctx->style.combo.button, sym, style->font); /* draw image */ image.x = header.x + style->combo.content_padding.x; image.y = header.y + style->combo.content_padding.y; image.h = header.h - 2 * style->combo.content_padding.y; image.w = image.h; nk_draw_image(&win->buffer, image, &img, nk_white); /* draw label */ text.padding = nk_vec2(0,0); label.x = image.x + image.w + style->combo.spacing.x + style->combo.content_padding.x; label.y = header.y + style->combo.content_padding.y; label.w = (button.x - style->combo.content_padding.x) - label.x; label.h = header.h - 2 * style->combo.content_padding.y; nk_widget_text(&win->buffer, label, selected, len, &text, NK_TEXT_LEFT, style->font); } return nk_combo_begin(layout, ctx, win, size, is_clicked, header); } NK_API int nk_combo_begin_symbol_label(struct nk_context *ctx, struct nk_panel *layout, const char *selected, enum nk_symbol_type type, struct nk_vec2 size) {return nk_combo_begin_symbol_text(ctx, layout, selected, nk_strlen(selected), type, size);} NK_API int nk_combo_begin_image_label(struct nk_context *ctx, struct nk_panel *layout, const char *selected, struct nk_image img, struct nk_vec2 size) {return nk_combo_begin_image_text(ctx, layout, selected, nk_strlen(selected), img, size);} NK_API int nk_combo_item_text(struct nk_context *ctx, const char *text, int len,nk_flags align) {return nk_contextual_item_text(ctx, text, len, align);} NK_API int nk_combo_item_label(struct nk_context *ctx, const char *label, nk_flags align) {return nk_contextual_item_label(ctx, label, align);} NK_API int nk_combo_item_image_text(struct nk_context *ctx, struct nk_image img, const char *text, int len, nk_flags alignment) {return nk_contextual_item_image_text(ctx, img, text, len, alignment);} NK_API int nk_combo_item_image_label(struct nk_context *ctx, struct nk_image img, const char *text, nk_flags alignment) {return nk_contextual_item_image_label(ctx, img, text, alignment);} NK_API int nk_combo_item_symbol_text(struct nk_context *ctx, enum nk_symbol_type sym, const char *text, int len, nk_flags alignment) {return nk_contextual_item_symbol_text(ctx, sym, text, len, alignment);} NK_API int nk_combo_item_symbol_label(struct nk_context *ctx, enum nk_symbol_type sym, const char *label, nk_flags alignment) {return nk_contextual_item_symbol_label(ctx, sym, label, alignment);} NK_API void nk_combo_end(struct nk_context *ctx) {nk_contextual_end(ctx);} NK_API void nk_combo_close(struct nk_context *ctx) {nk_contextual_close(ctx);} NK_API int nk_combo(struct nk_context *ctx, const char **items, int count, int selected, int item_height, struct nk_vec2 size) { int i = 0; int max_height; struct nk_panel combo; struct nk_vec2 item_spacing; struct nk_vec2 window_padding; NK_ASSERT(ctx); NK_ASSERT(items); NK_ASSERT(ctx->current); if (!ctx || !items ||!count) return selected; item_spacing = ctx->style.window.spacing; window_padding = nk_panel_get_padding(&ctx->style, ctx->current->layout->type); max_height = count * item_height + count * (int)item_spacing.y; max_height += (int)item_spacing.y * 2 + (int)window_padding.y * 2; size.y = NK_MIN(size.y, (float)max_height); if (nk_combo_begin_label(ctx, &combo, items[selected], size)) { nk_layout_row_dynamic(ctx, (float)item_height, 1); for (i = 0; i < count; ++i) { if (nk_combo_item_label(ctx, items[i], NK_TEXT_LEFT)) selected = i; } nk_combo_end(ctx); } return selected; } NK_API int nk_combo_separator(struct nk_context *ctx, const char *items_separated_by_separator, int separator, int selected, int count, int item_height, struct nk_vec2 size) { int i; int max_height; struct nk_panel combo; struct nk_vec2 item_spacing; struct nk_vec2 window_padding; const char *current_item; const char *iter; int length = 0; NK_ASSERT(ctx); NK_ASSERT(items_separated_by_separator); if (!ctx || !items_separated_by_separator) return selected; /* calculate popup window */ item_spacing = ctx->style.window.spacing; window_padding = nk_panel_get_padding(&ctx->style, ctx->current->layout->type); max_height = count * item_height + count * (int)item_spacing.y; max_height += (int)item_spacing.y * 2 + (int)window_padding.y * 2; size.y = NK_MIN(size.y, (float)max_height); /* find selected item */ current_item = items_separated_by_separator; for (i = 0; i < selected; ++i) { iter = current_item; while (*iter != separator) iter++; length = (int)(iter - current_item); current_item = iter + 1; } if (nk_combo_begin_text(ctx, &combo, current_item, length, size)) { current_item = items_separated_by_separator; nk_layout_row_dynamic(ctx, (float)item_height, 1); for (i = 0; i < count; ++i) { iter = current_item; while (*iter != separator) iter++; length = (int)(iter - current_item); if (nk_combo_item_text(ctx, current_item, length, NK_TEXT_LEFT)) selected = i; current_item = current_item + length + 1; } nk_combo_end(ctx); } return selected; } NK_API int nk_combo_string(struct nk_context *ctx, const char *items_separated_by_zeros, int selected, int count, int item_height, struct nk_vec2 size) {return nk_combo_separator(ctx, items_separated_by_zeros, '\0', selected, count, item_height, size);} NK_API int nk_combo_callback(struct nk_context *ctx, void(*item_getter)(void*, int, const char**), void *userdata, int selected, int count, int item_height, struct nk_vec2 size) { int i; int max_height; struct nk_panel combo; struct nk_vec2 item_spacing; struct nk_vec2 window_padding; const char *item; NK_ASSERT(ctx); NK_ASSERT(item_getter); if (!ctx || !item_getter) return selected; /* calculate popup window */ item_spacing = ctx->style.window.spacing; window_padding = nk_panel_get_padding(&ctx->style, ctx->current->layout->type); max_height = count * item_height + count * (int)item_spacing.y; max_height += (int)item_spacing.y * 2 + (int)window_padding.y * 2; size.y = NK_MIN(size.y, (float)max_height); item_getter(userdata, selected, &item); if (nk_combo_begin_label(ctx, &combo, item, size)) { nk_layout_row_dynamic(ctx, (float)item_height, 1); for (i = 0; i < count; ++i) { item_getter(userdata, i, &item); if (nk_combo_item_label(ctx, item, NK_TEXT_LEFT)) selected = i; } nk_combo_end(ctx); } return selected; } NK_API void nk_combobox(struct nk_context *ctx, const char **items, int count, int *selected, int item_height, struct nk_vec2 size) {*selected = nk_combo(ctx, items, count, *selected, item_height, size);} NK_API void nk_combobox_string(struct nk_context *ctx, const char *items_separated_by_zeros, int *selected, int count, int item_height, struct nk_vec2 size) {*selected = nk_combo_string(ctx, items_separated_by_zeros, *selected, count, item_height, size);} NK_API void nk_combobox_separator(struct nk_context *ctx, const char *items_separated_by_separator, int separator,int *selected, int count, int item_height, struct nk_vec2 size) {*selected = nk_combo_separator(ctx, items_separated_by_separator, separator, *selected, count, item_height, size);} NK_API void nk_combobox_callback(struct nk_context *ctx, void(*item_getter)(void* data, int id, const char **out_text), void *userdata, int *selected, int count, int item_height, struct nk_vec2 size) {*selected = nk_combo_callback(ctx, item_getter, userdata, *selected, count, item_height, size);} /* * ------------------------------------------------------------- * * MENU * * -------------------------------------------------------------- */ NK_INTERN int nk_menu_begin(struct nk_panel *layout, struct nk_context *ctx, struct nk_window *win, const char *id, int is_clicked, struct nk_rect header, struct nk_vec2 size) { int is_open = 0; int is_active = 0; struct nk_rect body; struct nk_window *popup; nk_hash hash = nk_murmur_hash(id, (int)nk_strlen(id), NK_PANEL_MENU); NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; body.x = header.x; body.w = size.x; body.y = header.y + header.h; body.h = size.y; popup = win->popup.win; is_open = popup ? nk_true : nk_false; is_active = (popup && (win->popup.name == hash) && win->popup.type == NK_PANEL_MENU); if ((is_clicked && is_open && !is_active) || (is_open && !is_active) || (!is_open && !is_active && !is_clicked)) return 0; if (!nk_nonblock_begin(layout, ctx, NK_WINDOW_NO_SCROLLBAR, body, header, NK_PANEL_MENU)) return 0; win->popup.type = NK_PANEL_MENU; win->popup.name = hash; return 1; } NK_API int nk_menu_begin_text(struct nk_context *ctx, struct nk_panel *layout, const char *title, int len, nk_flags align, struct nk_vec2 size) { struct nk_window *win; const struct nk_input *in; struct nk_rect header; int is_clicked = nk_false; nk_flags state; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; in = (state == NK_WIDGET_ROM || win->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_text(&ctx->last_widget_state, &win->buffer, header, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in, ctx->style.font)) is_clicked = nk_true; return nk_menu_begin(layout, ctx, win, title, is_clicked, header, size); } NK_API int nk_menu_begin_label(struct nk_context *ctx, struct nk_panel *layout, const char *text, nk_flags align, struct nk_vec2 size) {return nk_menu_begin_text(ctx, layout, text, nk_strlen(text), align, size);} NK_API int nk_menu_begin_image(struct nk_context *ctx, struct nk_panel *layout, const char *id, struct nk_image img, struct nk_vec2 size) { struct nk_window *win; struct nk_rect header; const struct nk_input *in; int is_clicked = nk_false; nk_flags state; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_image(&ctx->last_widget_state, &win->buffer, header, img, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in)) is_clicked = nk_true; return nk_menu_begin(layout, ctx, win, id, is_clicked, header, size); } NK_API int nk_menu_begin_symbol(struct nk_context *ctx, struct nk_panel *layout, const char *id, enum nk_symbol_type sym, struct nk_vec2 size) { struct nk_window *win; const struct nk_input *in; struct nk_rect header; int is_clicked = nk_false; nk_flags state; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_symbol(&ctx->last_widget_state, &win->buffer, header, sym, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in, ctx->style.font)) is_clicked = nk_true; return nk_menu_begin(layout, ctx, win, id, is_clicked, header, size); } NK_API int nk_menu_begin_image_text(struct nk_context *ctx, struct nk_panel *layout, const char *title, int len, nk_flags align, struct nk_image img, struct nk_vec2 size) { struct nk_window *win; struct nk_rect header; const struct nk_input *in; int is_clicked = nk_false; nk_flags state; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_text_image(&ctx->last_widget_state, &win->buffer, header, img, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, ctx->style.font, in)) is_clicked = nk_true; return nk_menu_begin(layout, ctx, win, title, is_clicked, header, size); } NK_API int nk_menu_begin_image_label(struct nk_context *ctx, struct nk_panel *layout, const char *title, nk_flags align, struct nk_image img, struct nk_vec2 size) {return nk_menu_begin_image_text(ctx, layout, title, nk_strlen(title), align, img, size);} NK_API int nk_menu_begin_symbol_text(struct nk_context *ctx, struct nk_panel *layout, const char *title, int len, nk_flags align, enum nk_symbol_type sym, struct nk_vec2 size) { struct nk_window *win; struct nk_rect header; const struct nk_input *in; int is_clicked = nk_false; nk_flags state; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return 0; win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_text_symbol(&ctx->last_widget_state, &win->buffer, header, sym, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, ctx->style.font, in)) is_clicked = nk_true; return nk_menu_begin(layout, ctx, win, title, is_clicked, header, size); } NK_API int nk_menu_begin_symbol_label(struct nk_context *ctx, struct nk_panel *layout, const char *title, nk_flags align, enum nk_symbol_type sym, struct nk_vec2 size ) {return nk_menu_begin_symbol_text(ctx, layout, title, nk_strlen(title), align,sym,size);} NK_API int nk_menu_item_text(struct nk_context *ctx, const char *title, int len, nk_flags align) {return nk_contextual_item_text(ctx, title, len, align);} NK_API int nk_menu_item_label(struct nk_context *ctx, const char *label, nk_flags align) {return nk_contextual_item_label(ctx, label, align);} NK_API int nk_menu_item_image_label(struct nk_context *ctx, struct nk_image img, const char *label, nk_flags align) {return nk_contextual_item_image_label(ctx, img, label, align);} NK_API int nk_menu_item_image_text(struct nk_context *ctx, struct nk_image img, const char *text, int len, nk_flags align) {return nk_contextual_item_image_text(ctx, img, text, len, align);} NK_API int nk_menu_item_symbol_text(struct nk_context *ctx, enum nk_symbol_type sym, const char *text, int len, nk_flags align) {return nk_contextual_item_symbol_text(ctx, sym, text, len, align);} NK_API int nk_menu_item_symbol_label(struct nk_context *ctx, enum nk_symbol_type sym, const char *label, nk_flags align) {return nk_contextual_item_symbol_label(ctx, sym, label, align);} NK_API void nk_menu_close(struct nk_context *ctx) {nk_contextual_close(ctx);} NK_API void nk_menu_end(struct nk_context *ctx) {nk_contextual_end(ctx);} #endif
bsmr-java/lwjgl3
modules/core/src/main/include/nuklear/nuklear.h
C
bsd-3-clause
758,314
{-# LANGUAGE OverloadedStrings,GADTs,DeriveDataTypeable,DeriveFunctor,GeneralizedNewtypeDeriving,MultiParamTypeClasses,QuasiQuotes,TemplateHaskell,TypeFamilies,PackageImports,NamedFieldPuns,RecordWildCards,TypeSynonymInstances,FlexibleContexts #-} module Main where import Data.Crawler import Data.CrawlerParameters import Misc import WWW.SimpleTable import Control.Applicative import Control.Concurrent import qualified Control.Exception as Ex import Control.Monad import Control.Monad.Catch import Control.Monad.Error import Control.Monad.IO.Class import Control.Monad.Reader import Control.Monad.Trans.Control (MonadBaseControl) import Control.Monad.Writer.Lazy import Data.Attoparsec.Text (Parser) import qualified Data.Attoparsec.Text as AP import Data.ByteString (ByteString,empty,writeFile) import qualified Data.ByteString as B (empty,writeFile) import Data.Char import Data.List import Data.Maybe import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.IO as T import qualified Data.Text.Read as T import Data.Time import Data.Word import Database.Persist import qualified Database.Persist.MongoDB as Mongo import Database.Persist.TH import Language.Haskell.TH.Syntax (Type(ConT)) import Network (PortID (PortNumber)) import Network.Curl import Network.Socket (PortNumber(..)) import "network" Network.URI import System.Console.CmdArgs.Implicit import System.Exit (ExitCode(..),exitWith) import System.FilePath.Posix import Text.HTML.TagSoup import qualified Text.Pandoc as P import Text.Poppler main :: IO () main = do (mongoP,crawlP) <- processParams docs <- crawlBisBcbsPublications (courtesyPeriod crawlP) (publishedFrom crawlP) (publishedUntil crawlP) Ex.catch (do Mongo.withMongoDBConn (db mongoP) (host mongoP) (port mongoP) (auth mongoP) (dt mongoP) $ \pool -> do Mongo.runMongoDBPool Mongo.master (writeDocs (courtesyPeriod crawlP) docs (pdfPath crawlP)) pool) gobalExceptionHandler gobalExceptionHandler :: Ex.SomeException -> IO () gobalExceptionHandler e = do putStrLn $ "gobalExceptionHandler: Got an exception --> " ++ show e writeDocs :: Int -> [BisDoc] -> FilePath -> Mongo.Action IO () writeDocs ct docs pdfPath = do liftIO $ putStrLn "Insert publications..." forM_ docs (\d -> writeOneDoc d ct pdfPath) writeDocsHandler :: Ex.SomeException -> IO (Either (Int, String) Text) writeDocsHandler e = do putStrLn $ "writeDocsHandler: Got an exception --> " ++ show e return $ Left (-1,show e) writeOneDoc :: BisDoc -> Int -> FilePath -> Mongo.Action IO () writeOneDoc d ct pdfPath = do let title = T.unpack $ bisDocTitle d liftIO $ putStrLn $ "Download and process '"++title++"'" case bisDocDetails d of Just det -> case bisDocumentDetailsFullTextLink det of Just url -> do mFullPdf <- liftIO $ getFile ct url case mFullPdf of Just fullPdf -> do fullHtml <- liftIO $ Ex.handle writeDocsHandler $ do let fname = snd (splitFileName (uriPath (fromJust (parseURI url)))) B.writeFile (pdfPath++fname) fullPdf fullHtml <- pdfToHtmlTextOnly [] fullPdf return fullHtml case fullHtml of Right html -> do let fullMd = htmlToMarkdown html let det' = det{bisDocumentDetailsFullTextMarkdown=Just fullMd} Mongo.insert_ (d {bisDocDetails=Just det'}) Left (e,stderr) -> do liftIO $ putStrLn $ "Error: "++show e liftIO $ putStrLn stderr Mongo.insert_ d Nothing -> do liftIO $ putStrLn $ "Error: Could not load pdf file." Mongo.insert_ d Nothing -> do liftIO $ putStrLn $ "No file to download for '"++title++"'" Mongo.insert_ d Nothing -> do liftIO $ putStrLn $ "No details for '"++title++"'" Mongo.insert_ d type TTag = Tag Text getFile :: Int -> URLString -> IO (Maybe ByteString) getFile ct url = Ex.catch (do resp <- curlGetResponse_ url [] :: IO (CurlResponse_ [(String,String)] ByteString) threadDelay ct return $ Just $ respBody resp) handler where handler :: Ex.SomeException -> IO (Maybe ByteString) handler e = do putStrLn $ "getFile: Got an exception --> " ++ show e return Nothing openUrlUtf8 :: Int -> URLString -> IO Text openUrlUtf8 ct url = Ex.catch (do resp <- curlGetResponse_ url [] :: IO (CurlResponse_ [(String,String)] ByteString) threadDelay ct return (T.decodeUtf8 (respBody resp))) handler where handler :: Ex.SomeException -> IO Text handler e = do putStrLn $ "openUrlUtf8: Got an exception --> " ++ show e return "" collectWhile :: Monad m => Maybe t -> (t -> m [a]) -> (t -> m (Maybe t)) -> [a] -> m [a] collectWhile (Just jx) process next bag = do x1 <- next jx new <- process jx collectWhile x1 process next (bag++new) collectWhile Nothing _ _ bag = return bag ppTags tags = putStrLns (map showT tags) bisSite :: URLString bisSite = "http://www.bis.org" crawlBisBcbsPublications :: Int -> Maybe Day -> Maybe Day -> IO [BisDoc] crawlBisBcbsPublications ct t0 t1 = withCurlDo $ do putStrLn $ "Start with page "++startingPoint src <- openUrlUtf8 ct startingPoint if src=="" then do T.putStrLn "Cannot get page." return [] else do let tags = parseTags src collectWhile (Just tags) (processBISDocPage ct t0 t1) (getNextBISDocPage ct) [] where startingPoint = bisSite++"/bcbs/publications.htm" processBISDocPage :: Int -> Maybe Day -> Maybe Day -> [TTag] -> IO [BisDoc] processBISDocPage ct t0 t1 tags = do let ts = simpleTables tags if null ts then do T.putStrLn "No table found on page." return [] else do let ts1 = head ts docs <- catMaybes <$> mapM (processDoc ct t0 t1) (rows ts1) T.putStrLn "Found: " T.putStrLn $ T.intercalate "\n" (map (\ d -> "-- " `T.append` (bisDocTitle d)) docs) return docs processDoc :: Int -> Maybe Day -> Maybe Day -> TableRow -> IO (Maybe BisDoc) processDoc ct t0 t1 row = do let es = elements row dt = getDateFromRow es typ = getTypeFromRow es lnk = getLinkFromRow es ttl = getTitleFromRow es if not (between dt t0 t1) then return Nothing else do details <- case lnk of Nothing -> return Nothing Just l -> if "pdf" `isSuffixOf` l then do resp <- curlGetResponse_ l [] :: IO (CurlResponse_ [(String,String)] ByteString) threadDelay ct return $ Just BisDocumentDetails { bisDocumentDetailsDocumentTitle=ttl, bisDocumentDetailsSummary = "", bisDocumentDetailsFullTextLink = Just l, bisDocumentDetailsFullTextMarkdown = Nothing, bisDocumentDetailsLocalFile = Just $ filenameFromUrl l, bisDocumentDetailsOtherLinks = []} else analyzeBisSingleDocPage ct l return $ Just $ BisDoc dt typ lnk ttl details getDateFromRow tags = let ds = deleteAll ["\n","\t","\r"] $ fromTagText (head (head tags)) in case AP.parseOnly parseDate ds of Left m -> error $ "Parse error while processing a date: "++m Right d -> d getTypeFromRow tags = let tag = (tags!!1)!!3 in if isTagOpen tag then let attr = fromAttrib "title" tag in if attr=="" then Nothing else Just attr else Nothing getLinkFromRow :: [[TTag]] -> Maybe URLString getLinkFromRow tags = let tag = (tags!!2)!!3 in if isTagOpen tag then Just $ bisSite++(T.unpack $ fromAttrib "href" tag) else Nothing getTitleFromRow tags = let tag = (tags!!2)!!4 in if isTagText tag then deleteAll ["\t","\r","\n"] $ fromTagText tag else "" getNextBISDocPage :: Int -> [TTag] -> IO (Maybe [TTag]) getNextBISDocPage ct tags = do let nextLink = getNextDocLink tags case nextLink of Just lnk -> do putStrLn $ "Follow link: "++lnk src <- openUrlUtf8 ct lnk let tags1 = parseTags src return (Just tags1) Nothing -> return Nothing getNextDocLink :: [TTag] -> Maybe URLString getNextDocLink tags = let s = sections (~== (TagOpen ("a"::Text) [("class","next")])) tags in if null s then Nothing else let t = head (head s) in let href = fromAttrib "href" t in if href=="" then Nothing else Just (if T.head href=='/' then bisSite++(T.unpack href) else T.unpack href) analyzeBisSingleDocPage :: Int -> URLString -> IO (Maybe BisDocumentDetails) analyzeBisSingleDocPage ct url = do putStrLn $ "Analyse "++url allTags <- return . partitionIt =<< (return . parseTags) =<< openUrlUtf8 ct url if not (null allTags) then if length allTags==3 then do let contentTags = allTags!!0 annotationTags = allTags!!1 docTitle = fromTagText (contentTags!!1) docSummary = let divSections = sections (~== (TagClose ("div"::Text))) contentTags summaryHtml = if length divSections>=2 then purgeHtmlText $ tail (divSections!!1) else error "Cannot parse page because structure has changed." in T.pack $ P.writeMarkdown P.def $ P.readHtml P.def $ T.unpack $ renderTags summaryHtml fullTextLink = let fBox = sections (~==divFullText) annotationTags in if not (null fBox) then let aTag = sections (~==aLinkTag) (head fBox) link = T.unpack $ fromAttrib "href" (head $ head aTag) in if "/" `isPrefixOf` link then Just $ bisSite++link else Just link else Nothing let otherBoxes = partitions (~== otherBox) annotationTags let others = map processOtherBox otherBoxes return $ Just $ BisDocumentDetails docTitle docSummary fullTextLink Nothing (fmap filenameFromUrl fullTextLink) others else do putStrLn $ "Cannot parse page because structure has changed. " ++"Content:\n" ++show allTags return Nothing else do putStrLn "No input. Probably You are not connected to the internet." return Nothing where tagContent = TagOpen "h1" [] :: TTag tagAnnotations = TagOpen "div" [("id","right"), ("class","column"), ("role","complementary")] :: TTag tagFooter = TagOpen "div" [("id","footer"),("role","contentinfo")] :: TTag partitionIt = partitions (\tag -> tag~==tagContent || tag~==tagAnnotations || tag~==tagFooter) divFullText = TagOpen "div" [("class","list_box full_text")] :: TTag otherBox = TagOpen "div" [("class","list_box")] :: TTag processOtherBox :: [Tag Text] -> DocumentLink processOtherBox tags = let t1 = sections (~== (TagOpen "h4" [] :: TTag)) tags typ = fromTagText ((head t1)!!1) t2 = partitions (~==aLinkTag) tags link tags = if null tags then "" else let lnk' = T.unpack $ fromAttrib "href" (head tags) lnk = if lnk'=="" then "" else if "/" `isPrefixOf` lnk' then bisSite++lnk' else lnk' in lnk links = map link t2 in (DocumentLink typ links)
tkemps/bcbs-crawler
src/BcbsCrawler-old.hs
Haskell
bsd-3-clause
13,475
.PHONY: clean-pyc clean-build docs clean help: @echo "clean - remove all build, test, coverage and Python artifacts" @echo "clean-build - remove build artifacts" @echo "clean-pyc - remove Python file artifacts" @echo "clean-test - remove test and coverage artifacts" @echo "lint - check style with flake8" @echo "test - run tests quickly with the default Python" @echo "test-all - run tests on every Python version with tox" @echo "coverage - check code coverage quickly with the default Python" @echo "docs - generate Sphinx HTML documentation, including API docs" @echo "release - package and upload a release" @echo "dist - package" @echo "install - install the package to the active Python's site-packages" clean: clean-build clean-pyc clean-test clean-build: rm -fr build/ rm -fr dist/ rm -fr .eggs/ find . -name '*.egg-info' -exec rm -fr {} + find . -name '*.egg' -exec rm -f {} + clean-pyc: find . -name '*.pyc' -exec rm -f {} + find . -name '*.pyo' -exec rm -f {} + find . -name '*~' -exec rm -f {} + find . -name '__pycache__' -exec rm -fr {} + clean-test: rm -fr .tox/ rm -f .coverage rm -fr htmlcov/ lint: flake8 poodletesttwo tests test: python setup.py test test-all: tox coverage: coverage run --source poodletesttwo setup.py test coverage report -m coverage html open htmlcov/index.html docs: rm -f docs/poodletesttwo.rst rm -f docs/modules.rst sphinx-apidoc -o docs/ poodletesttwo $(MAKE) -C docs clean $(MAKE) -C docs html open docs/_build/html/index.html release: clean python setup.py sdist upload python setup.py bdist_wheel upload dist: clean python setup.py sdist python setup.py bdist_wheel ls -l dist install: clean python setup.py install
gautsi/poodletesttwo
Makefile
Makefile
bsd-3-clause
1,720
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include <xenia/kernel/objects/xnotify_listener.h> using namespace xe; using namespace xe::kernel; XNotifyListener::XNotifyListener(KernelState* kernel_state) : XObject(kernel_state, kTypeNotifyListener), wait_handle_(NULL), lock_(0), mask_(0), notification_count_(0) { } XNotifyListener::~XNotifyListener() { xe_mutex_free(lock_); if (wait_handle_) { CloseHandle(wait_handle_); } } void XNotifyListener::Initialize(uint64_t mask) { XEASSERTNULL(wait_handle_); lock_ = xe_mutex_alloc(); wait_handle_ = CreateEvent(NULL, TRUE, FALSE, NULL); mask_ = mask; } void XNotifyListener::EnqueueNotification(XNotificationID id, uint32_t data) { xe_mutex_lock(lock_); auto existing = notifications_.find(id); if (existing != notifications_.end()) { // Already exists. Overwrite. notifications_[id] = data; } else { // New. notification_count_++; } SetEvent(wait_handle_); xe_mutex_unlock(lock_); } bool XNotifyListener::DequeueNotification( XNotificationID* out_id, uint32_t* out_data) { bool dequeued = false; xe_mutex_lock(lock_); if (notification_count_) { dequeued = true; auto it = notifications_.begin(); *out_id = it->first; *out_data = it->second; notifications_.erase(it); notification_count_--; if (!notification_count_) { ResetEvent(wait_handle_); } } xe_mutex_unlock(lock_); return dequeued; } bool XNotifyListener::DequeueNotification( XNotificationID id, uint32_t* out_data) { bool dequeued = false; xe_mutex_lock(lock_); if (notification_count_) { dequeued = true; auto it = notifications_.find(id); if (it != notifications_.end()) { *out_data = it->second; notifications_.erase(it); notification_count_--; if (!notification_count_) { ResetEvent(wait_handle_); } } } xe_mutex_unlock(lock_); return dequeued; }
shuffle2/xenia
src/xenia/kernel/objects/xnotify_listener.cc
C++
bsd-3-clause
2,393
#pragma once ///---------------------------------------------------------------------------------------------------- /// World.h - Container for the Discrete Event Engine and Memory Allocator ///---------------------------------------------------------------------------------------------------- #include "Simulation_Engine.h" namespace polaris { ///---------------------------------------------------------------------------------------------------- /// Simulation_Configuration.h - Configuration Object for World ///---------------------------------------------------------------------------------------------------- struct Simulation_Configuration { Simulation_Configuration():_num_sim_threads(-1),_preallocation_bytes(-1),_num_iterations(-1),_execution_segments_per_thread(-1), _execution_objects_per_block(-1),_max_execution_objects_per_block(-1),_max_free_blocks(-1),_num_free_blocks_buffer(-1){} void Check_Configuration() { if(_num_sim_threads <= 0) { THROW_EXCEPTION("num_threads not configured"); } if(_preallocation_bytes < 0) { THROW_EXCEPTION("pre_allocation_amount not configured"); } if(_num_iterations <= 0) { THROW_EXCEPTION("num_iterations not configured"); } if(_execution_segments_per_thread <= 0) { THROW_EXCEPTION("execution_blocks_per_thread not configured"); } if(_execution_objects_per_block <= 0) { THROW_EXCEPTION("execution_objects_per_block not configured"); } if(_max_execution_objects_per_block <= 0) { THROW_EXCEPTION("max_execution_objects_per_block not configured"); } if(_max_free_blocks <= 0) { THROW_EXCEPTION("max_free_blocks not configured"); } if(_num_free_blocks_buffer <= 0) { THROW_EXCEPTION("num_free_blocks_buffer not configured"); } } void Single_Threaded_Setup(int num_iterations) { _num_sim_threads = 1; _preallocation_bytes = 0; _num_iterations = num_iterations; _execution_segments_per_thread = 20; _execution_objects_per_block = 100; _max_execution_objects_per_block = 1000; _max_free_blocks = 10; _num_free_blocks_buffer = 5; } void Multi_Threaded_Setup(int num_iterations,int num_threads) { _num_sim_threads = num_threads; _preallocation_bytes = 0; _num_iterations = num_iterations; _execution_segments_per_thread = 20; _execution_objects_per_block = 100; _max_execution_objects_per_block = 1000; _max_free_blocks = 10; _num_free_blocks_buffer = 5; } int _num_sim_threads; int _preallocation_bytes; int _num_iterations; int _execution_segments_per_thread; int _execution_objects_per_block; int _max_execution_objects_per_block; int _max_free_blocks; int _num_free_blocks_buffer; }; ///---------------------------------------------------------------------------------------------------- /// World - Container for the Discrete Event Engine and Memory Allocator ///---------------------------------------------------------------------------------------------------- class World { public: //---------------------------------------------------------------------------------------------------- // Construction / Destruction Functions //---------------------------------------------------------------------------------------------------- void Initialize(Simulation_Configuration& cfg); void Terminate(); //---------------------------------------------------------------------------------------------------- // Simulation Functions //---------------------------------------------------------------------------------------------------- void Start_Turning(); __forceinline bool Is_Running(){return (bool)_running;} Simulation_Engine* simulation_engine(){ return _simulation_engine; } //---------------------------------------------------------------------------------------------------- // Timing Coordination Functions //---------------------------------------------------------------------------------------------------- void Send_Signal_To_World(); void Send_Finished_Signal_To_World(); void Wait_For_Signal_From_World(); void Send_Signal_To_Threads(); void Wait_For_Signal_From_Threads(); __forceinline long Mark_Thread_As_Idle(){ return AtomicIncrement(&_threads_idle_counter); } __forceinline void Spin_Until_All_Threads_Idle(){ while(_threads_idle_counter!=_num_sim_threads) SLEEP(0); } __forceinline long Mark_Thread_As_Ready(){ return AtomicIncrement(&_threads_ready_counter); } __forceinline void Spin_Until_All_Threads_Ready(){ while(_threads_ready_counter!=_num_sim_threads) SLEEP(0); } //---------------------------------------------------------------------------------------------------- // Global Accessor Functions //---------------------------------------------------------------------------------------------------- unsigned int num_iterations(){return _num_iterations;} void num_iterations(unsigned int value){_num_iterations = value;} unsigned int num_sim_threads(){return _num_sim_threads;} void num_sim_threads(unsigned int value){_num_sim_threads = value;} unsigned int num_antares_threads(){return _num_antares_threads;} void num_antares_threads(unsigned int value){_num_antares_threads = value;} unsigned int execution_segments_per_thread(){return _execution_segments_per_thread;} void execution_segments_per_thread(unsigned int value){_execution_segments_per_thread = value;} unsigned int execution_objects_per_block(){return _execution_objects_per_block;} void execution_objects_per_block(unsigned int value){_execution_objects_per_block = value;} unsigned int max_execution_objects_per_block(){return _max_execution_objects_per_block;} void max_execution_objects_per_block(unsigned int value){_max_execution_objects_per_block = value;} unsigned int max_free_blocks(){return _max_free_blocks;} void max_free_blocks(unsigned int value){_max_free_blocks = value;} unsigned int num_free_blocks_buffer(){return _num_free_blocks_buffer;} void num_free_blocks_buffer(unsigned int value){_num_free_blocks_buffer = value;} long long preallocation_bytes(){return _preallocation_bytes;} void preallocation_bytes(long long value){_preallocation_bytes = value;} int iteration(){return _revision._iteration;} void iteration(int value){_revision._iteration = value;} int sub_iteration(){return _revision._sub_iteration;} void sub_iteration(int value){_revision._sub_iteration = value;} const Revision& revision(){return _revision;} void revision(const Revision& value){_revision = value;} private: friend class Simulation_Engine; unsigned int _num_iterations; unsigned int _num_sim_threads; unsigned int _num_antares_threads; unsigned int _execution_segments_per_thread; unsigned int _execution_objects_per_block; unsigned int _max_execution_objects_per_block; unsigned int _max_free_blocks; unsigned int _num_free_blocks_buffer; long long _preallocation_bytes; volatile long _threads_idle_counter; volatile long _threads_ready_counter; volatile bool _running; Simulation_Engine* _simulation_engine; Revision _revision; #ifdef _MSC_VER HANDLE _threads_finished_event; HANDLE _threads_start_event; void** _threads; #else pthread_mutex_t _threads_finished_mutex; pthread_cond_t _threads_finished_conditional; pthread_mutex_t _threads_start_mutex; pthread_cond_t _threads_start_conditional; pthread_t* _threads; #endif }; extern World* _world; static unsigned int num_threads(){return _world->num_sim_threads()+1;} static int iteration(){return _world->iteration();} //static void iteration(unsigned int value){_world->iteration(value);} static int sub_iteration(){return _world->sub_iteration();} //static void sub_iteration(unsigned int value){_world->sub_iteration(value);} static const Revision& revision(){return _world->revision();} //static void revision(const Revision& value){_world->revision(value);} static unsigned int num_iterations(){return _world->num_iterations();} //static void num_iterations(unsigned int value){_world->num_iterations(value);} static unsigned int num_sim_threads(){return _world->num_sim_threads();} //static void num_sim_threads(unsigned int value){_world->num_sim_threads(value);} static unsigned int num_antares_threads(){return _world->num_antares_threads();} //static void num_antares_threads(unsigned int value){_world->num_antares_threads(value);} static unsigned int execution_segments_per_thread(){return _world->execution_segments_per_thread();} //static void execution_segments_per_thread(unsigned int value){_world->execution_segments_per_thread(value);} static unsigned int execution_objects_per_block(){return _world->execution_objects_per_block();} //static void execution_objects_per_block(unsigned int value){_world->execution_objects_per_block(value);} static unsigned int max_execution_objects_per_block(){return _world->max_execution_objects_per_block();} //static void max_execution_objects_per_block(unsigned int value){_world->max_execution_objects_per_block(value);} static unsigned int max_free_blocks(){return _world->max_free_blocks();} //static void max_free_blocks(unsigned int value){_world->max_free_blocks(value);} static unsigned int num_free_blocks_buffer(){return _world->num_free_blocks_buffer();} //static void num_free_blocks_buffer(unsigned int value){_world->num_free_blocks_buffer(value);} static long long preallocation_bytes(){return _world->preallocation_bytes();} //static void preallocation_bytes(long long value){_world->preallocation_bytes(value);} }
Symcies/polaris
libs/core/World.h
C
bsd-3-clause
9,658
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="ja"> <head> <!-- Generated by javadoc (1.8.0_60) on Fri Jan 29 17:30:57 JST 2016 --> <title>jp.ac.maslab.ando.aiwolf.client.player.base</title> <meta name="date" content="28-01-29"> <link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../../script.js"></script> </head> <body> <h1 class="bar"><a href="../../../../../../../../jp/ac/maslab/ando/aiwolf/client/player/base/package-summary.html" target="classFrame">jp.ac.maslab.ando.aiwolf.client.player.base</a></h1> <div class="indexContainer"> <h2 title="クラス">クラス</h2> <ul title="クラス"> <li><a href="BodyGuardBase.html" title="jp.ac.maslab.ando.aiwolf.client.player.base内のクラス" target="classFrame">BodyGuardBase</a></li> <li><a href="MediumBase.html" title="jp.ac.maslab.ando.aiwolf.client.player.base内のクラス" target="classFrame">MediumBase</a></li> <li><a href="PossessedBase.html" title="jp.ac.maslab.ando.aiwolf.client.player.base内のクラス" target="classFrame">PossessedBase</a></li> <li><a href="RoleBase.html" title="jp.ac.maslab.ando.aiwolf.client.player.base内のクラス" target="classFrame">RoleBase</a></li> <li><a href="SeerBase.html" title="jp.ac.maslab.ando.aiwolf.client.player.base内のクラス" target="classFrame">SeerBase</a></li> <li><a href="VillagerBase.html" title="jp.ac.maslab.ando.aiwolf.client.player.base内のクラス" target="classFrame">VillagerBase</a></li> <li><a href="VillagerSide.html" title="jp.ac.maslab.ando.aiwolf.client.player.base内のクラス" target="classFrame">VillagerSide</a></li> <li><a href="WerewolfSide.html" title="jp.ac.maslab.ando.aiwolf.client.player.base内のクラス" target="classFrame">WerewolfSide</a></li> </ul> </div> </body> </html>
NONONOexe/AndoAgent
doc/jp/ac/maslab/ando/aiwolf/client/player/base/package-frame.html
HTML
bsd-3-clause
1,928
package org.broadinstitute.dsde.workbench.sam.config import org.broadinstitute.dsde.workbench.google.{KeyId, KeyRingId, Location} import org.broadinstitute.dsde.workbench.model.google.GoogleProject import scala.concurrent.duration.FiniteDuration /** * created by mtalbott 1/25/18 * * @param project google project for the key * @param location location for the key * @param keyRingId name of the key ring that contains the key * @param keyId name of the key */ final case class GoogleKmsConfig( project: GoogleProject, location: Location, keyRingId: KeyRingId, keyId: KeyId, rotationPeriod: FiniteDuration )
broadinstitute/sam
src/main/scala/org/broadinstitute/dsde/workbench/sam/config/KmsConfig.scala
Scala
bsd-3-clause
822
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model app\models\PembayaranPinjaman */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="pembayaran-pinjaman-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'kode_trans')->textInput(['maxlength' => 10]) ?> <?= $form->field($model, 'tgl_bayar')->textInput(['type' => 'date']) ?> <?= $form->field($model, 'no_angsuran')->textInput() ?> <?= $form->field($model, 'jumlah')->textInput() ?> <?= $form->field($model, 'jasa')->textInput() ?> <?= $form->field($model, 'denda')->textInput() ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div>
mslx28/sikui
views/pembayaran-pinjaman/_form.php
PHP
bsd-3-clause
875
var fs = require('fs'); var path = require('path'); var sourceFile = '/proc/diskstats', collectionGroup = '/proc/diskstats', lastValueFile = __filename + '.lastvalue', deviceNameRegexp = /^(?:(?:h|s)d[a-z]{1,3}|dm\-\d+)$/; var lvmList, dmPath = '/dev/mapper'; var lookupLVMName = function (name) { // init if (!lvmList) { lvmList = {}; try { fs.readdirSync(dmPath).forEach(function (e) { try { var dm = path.basename(fs.readlinkSync(path.join(dmPath, e))); if (dm) { lvmList[dm] = e; } } catch (e) { } }); } catch (e) { } } return lvmList[name] || null; }; var parseSource = function () { try { var source = fs.readFileSync(sourceFile).toString().split(/\n/); } catch (e) { return []; } var lastValue = {}; try { lastValue = JSON.parse(fs.readFileSync(lastValueFile).toString()); } catch (e) { } var result = [], now = new Date().getTime(), deltaMS = now - (lastValue.time || 0), ps = function (v) { return v / deltaMS * 1000; }, nr = function (v, digits) { var a = Math.pow(10, digits || 3); return Math.round(v * a) / a; }; // build source.forEach(function (line) { var v = line.trim().split(/\s+/); if (v.length < 14 || !deviceNameRegexp.test(v[2])) { return; } // 0.rd_ios 1.rd_merges 2.rd_sectors, 3.rd_ticks, // 4.wr_ios, 5.wr_merges, 6.wr_sectors, 7.wr_ticks, // 8.ios_progress 9.ticks_request, 10.total_ticks var deviceName = lookupLVMName(v[2]) || v[2], values = v.slice(3).map(function (v) { return parseInt(v) || 0; }), lastValues = lastValue[deviceName] || {}, diffValues = values.map(function (v, i) { return v - (lastValues[i] || 0); }); var d_result = []; // I/O completed d_result.push({ colName: 'Requests completed per second', data: { read: nr(ps(diffValues[0])), write: nr(ps(diffValues[4])), }, params: { read: {}, write: {}, }, }); // I/O merged d_result.push({ colName: 'Requests merged per second', data: { read: nr(ps(diffValues[1])), write: nr(ps(diffValues[5])), }, params: { read: {}, write: {}, }, }); // I/O sectors d_result.push({ colName: 'Sectors read/write the device per second', data: { read: nr(ps(diffValues[2])), write: nr(ps(diffValues[6])), }, params: { read: {unit: 'sectors'}, write: {unit: 'sectors'}, }, }); // I/O time d_result.push({ colName: 'The average time for I/O requests', data: { read: nr(diffValues[0] ? diffValues[3] / diffValues[0] : 0), write: nr(diffValues[4] ? diffValues[7] / diffValues[4] : 0), service: nr(diffValues[0] + diffValues[4] ? diffValues[9] / (diffValues[0] + diffValues[4]) : 0), }, params: { read: {unit: 'ms'}, write: {unit: 'ms'}, service: {unit: 'ms'}, }, }); // average request size d_result.push({ colName: 'The average size of the requests', data: { read: nr(diffValues[0] ? diffValues[2] / diffValues[0] : 0), write: nr(diffValues[4] ? diffValues[6] / diffValues[4] : 0), }, params: { read: {unit: 'sectors'}, write: {unit: 'sectors'}, }, }); // average queue time d_result.push({ colName: 'The average queue time of the requests', data: { value: nr(deltaMS ? diffValues[10] / deltaMS : 0), }, params: { value: {unit: 'ms'}, }, }); // request on progress /*d_result.push({ colName: 'Requests on progress per second', data: { value: nr(ps(values[8])), }, params: { value: {}, }, });*/ // Bandwidth utilization d_result.push({ colName: 'Bandwidth utilization', data: { value: Math.min(100, nr(deltaMS ? 100 * diffValues[9] / deltaMS : 0)), }, params: { value: {unit: '%'}, }, }); lastValue[deviceName] = values; result = result.concat(d_result.map(function (el) { el.colName = [collectionGroup, deviceName, el.colName].join('::'); return el; })); }); try { lastValue.time = now; fs.writeFileSync(lastValueFile, JSON.stringify(lastValue)); } catch (e) { } return result; }; module.exports.polling = function (save) { save(parseSource().map(function (el) { delete el.params; return el; })); }; module.exports.attrs = function () { return parseSource().map(function (el) { delete el.data; for (var k in el.params) { el.params[k].interpolate = 'step-before'; } return el; }); };
a-c-t-i-n-i-u-m/hydrangea
dataModules/proc_diskstats.js
JavaScript
bsd-3-clause
5,747
<?php namespace backend\controllers; class ProductController extends SiteController { public function actionCreate() { return $this->render('create'); } }
acer4552/dlshili
backend/controllers/ProductController.php
PHP
bsd-3-clause
184
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"> <title>gem5: MipsISA::ThreadFault Class Reference</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> <link href="tabs.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.4.7 --> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li id="current"><a href="classes.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="pages.html"><span>Related&nbsp;Pages</span></a></li> <li> <form action="search.php" method="get"> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td><label>&nbsp;<u>S</u>earch&nbsp;for&nbsp;</label></td> <td><input type="text" name="query" value="" size="20" accesskey="s"/></td> </tr> </table> </form> </li> </ul></div> <div class="tabs"> <ul> <li><a href="classes.html"><span>Alphabetical&nbsp;List</span></a></li> <li><a href="annotated.html"><span>Class&nbsp;List</span></a></li> <li><a href="hierarchy.html"><span>Class&nbsp;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&nbsp;Members</span></a></li> </ul></div> <div class="nav"> <a class="el" href="namespaceMipsISA.html">MipsISA</a>::<a class="el" href="classMipsISA_1_1ThreadFault.html">ThreadFault</a></div> <h1>MipsISA::ThreadFault Class Reference</h1><!-- doxytag: class="MipsISA::ThreadFault" --><!-- doxytag: inherits="MipsISA::MipsFault" --><code>#include &lt;<a class="el" href="arch_2mips_2faults_8hh-source.html">faults.hh</a>&gt;</code> <p> <p>Inheritance diagram for MipsISA::ThreadFault: <p><center><img src="classMipsISA_1_1ThreadFault.png" usemap="#MipsISA::ThreadFault_map" border="0" alt=""></center> <map name="MipsISA::ThreadFault_map"> <area href="classMipsISA_1_1MipsFault.html" alt="MipsISA::MipsFault< T >" shape="rect" coords="0,168,151,192"> <area href="classMipsISA_1_1MipsFaultBase.html" alt="MipsISA::MipsFaultBase" shape="rect" coords="0,112,151,136"> <area href="classFaultBase.html" alt="FaultBase" shape="rect" coords="0,56,151,80"> <area href="classRefCounted.html" alt="RefCounted" shape="rect" coords="0,0,151,24"> </map> <a href="classMipsISA_1_1ThreadFault-members.html">List of all members.</a><table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> </table> <hr><a name="_details"></a><h2>Detailed Description</h2> <p> <p> Definition at line <a class="el" href="arch_2mips_2faults_8hh-source.html#l00122">122</a> of file <a class="el" href="arch_2mips_2faults_8hh-source.html">faults.hh</a>.<hr>The documentation for this class was generated from the following file:<ul> <li>arch/mips/<a class="el" href="arch_2mips_2faults_8hh-source.html">faults.hh</a></ul> <hr size="1"><address style="align: right;"><small> Generated on Fri Apr 17 12:41:15 2015 for gem5 by <a href="http://www.doxygen.org/index.html"> doxygen</a> 1.4.7</small></address> </body> </html>
wnoc-drexel/gem5-stable
src/doxygen/html/classMipsISA_1_1ThreadFault.html
HTML
bsd-3-clause
3,243
/* Copyright (c) 2000, Sean O'Neil (s_p_oneil@hotmail.com) 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 name of the project 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. */ #include <EngineCore.h> #include "PlanetaryMapNode.h" CNodeBuilder builder; SBufferShape CPlanetaryMapNode::m_shape; // Offsets to the start of each quadrant (useful for splitting, merging, and rendering) unsigned short CPlanetaryMapNode::m_nQuadrantOffset[4] = {0, 4, 36, 40}; unsigned short CPlanetaryMapNode::m_nQuadrantHeightOffset[4] = {0, 8, 136, 144}; // A list of each face's neighbors unsigned short CPlanetaryMapNode::m_nFaceNeighbor[6][4]; class CInitPlanetaryMapNode { public: CInitPlanetaryMapNode() { CPlanetaryMapNode::InitTables(); } }; CInitPlanetaryMapNode g_cInitPlanetaryMapNode; void CPlanetaryMapNode::InitTables() { int nTexCoord[4] = {2, 0, 0, 0}; m_shape.Init(true, true, false, nTexCoord); // Calculate the offset to each quadrant in the vertex table m_nQuadrantOffset[TopLeft] = 0; m_nQuadrantOffset[TopRight] = (SURFACE_MAP_WIDTH-1) / 2; m_nQuadrantOffset[BottomRight] = (SURFACE_MAP_COUNT-1) / 2; m_nQuadrantOffset[BottomLeft] = m_nQuadrantOffset[BottomRight] - m_nQuadrantOffset[TopRight]; // Calculate the offset to each quadrant in the height table m_nQuadrantHeightOffset[TopLeft] = 0; m_nQuadrantHeightOffset[TopRight] = (HEIGHT_MAP_WIDTH-1) / 2; m_nQuadrantHeightOffset[BottomRight] = (HEIGHT_MAP_COUNT-1) / 2; m_nQuadrantHeightOffset[BottomLeft] = m_nQuadrantHeightOffset[BottomRight] - m_nQuadrantHeightOffset[TopRight]; // Set up the N/E/S/W neighbors of the front face of the cube m_nFaceNeighbor[FrontFace][TopEdge] = TopFace; m_nFaceNeighbor[FrontFace][RightEdge] = RightFace; m_nFaceNeighbor[FrontFace][BottomEdge] = BottomFace; m_nFaceNeighbor[FrontFace][LeftEdge] = LeftFace; // Set up the N/E/S/W neighbors of the back face of the cube m_nFaceNeighbor[BackFace][TopEdge] = TopFace; m_nFaceNeighbor[BackFace][RightEdge] = LeftFace; m_nFaceNeighbor[BackFace][BottomEdge] = BackFace; m_nFaceNeighbor[BackFace][LeftEdge] = RightFace; // Set up the N/E/S/W neighbors of the right face of the cube m_nFaceNeighbor[RightFace][TopEdge] = TopFace; m_nFaceNeighbor[RightFace][RightEdge] = BackFace; m_nFaceNeighbor[RightFace][BottomEdge] = BottomFace; m_nFaceNeighbor[RightFace][LeftEdge] = FrontFace; // Set up the N/E/S/W neighbors of the left face of the cube m_nFaceNeighbor[LeftFace][TopEdge] = TopFace; m_nFaceNeighbor[LeftFace][RightEdge] = FrontFace; m_nFaceNeighbor[LeftFace][BottomEdge] = BottomFace; m_nFaceNeighbor[LeftFace][LeftEdge] = BackFace; // Set up the N/E/S/W neighbors of the top face of the cube m_nFaceNeighbor[TopFace][TopEdge] = BackFace; m_nFaceNeighbor[TopFace][RightEdge] = RightFace; m_nFaceNeighbor[TopFace][BottomEdge] = FrontFace; m_nFaceNeighbor[TopFace][LeftEdge] = LeftFace; // Set up the N/E/S/W neighbors of the bottom face of the cube m_nFaceNeighbor[BottomFace][TopEdge] = FrontFace; m_nFaceNeighbor[BottomFace][RightEdge] = RightFace; m_nFaceNeighbor[BottomFace][BottomEdge] = BackFace; m_nFaceNeighbor[BottomFace][LeftEdge] = LeftFace; } CPlanetaryMapNode::CPlanetaryMapNode(CPlanetaryMap *pMap, int nFace) { // Initialize flags and corners, then call the map builder to build this node m_pParent = NULL; m_pChild[0] = m_pChild[1] = m_pChild[2] = m_pChild[3] = NULL; m_pMap = pMap; InitNode(nFace, -1); } CPlanetaryMapNode::CPlanetaryMapNode(CPlanetaryMapNode *pParent, int nQuadrant) { // Initialize flags, corners, and neighbor pointers, then call the map builder to build this node m_pParent = pParent; m_pChild[0] = m_pChild[1] = m_pChild[2] = m_pChild[3] = NULL; m_pMap = pParent->m_pMap; InitNode(pParent->GetFace(), nQuadrant); } CPlanetaryMapNode::~CPlanetaryMapNode() { if(m_nBumpID != (unsigned short)-1) m_pMap->GetTextureArray().ReleaseTexture(m_nBumpID); if(HasTexture()) m_pMap->GetTextureArray().ReleaseTexture(m_nTextureID); m_boVertex.Cleanup(); // Clear the parent and neighbor pointers that point to this node if(m_pParent) { m_pParent->m_pChild[GetQuadrant()] = NULL; for(int i=0; i<4; i++) { if(m_pNeighbor[i]) { for(int j=0; j<4; j++) if(m_pNeighbor[i]->m_pNeighbor[j] == this) m_pNeighbor[i]->m_pNeighbor[j] = NULL; } } } // Now pass this node to all factories and objects that might affect it for(CPlanetaryMap::iterator it = m_pMap->begin(); it != m_pMap->end(); it++) { if((*it)->AffectsNode(this)) (*it)->DestroyNode(this); } } void CPlanetaryMapNode::InitNode(int nFace, int nQuadrant) { m_nTextureID = (unsigned short)-1; m_nBumpID = (unsigned short)-1; // Set up node flags int nLevel = m_pParent ? m_pParent->GetLevel() + 1 : 0; m_nNodeFlags = NodeDirty | ((nLevel << 5) & LevelMask) | ((nQuadrant << 3) & QuadrantMask) | (nFace & FaceMask); m_nSort[0] = 0; m_nSort[1] = 1; m_nSort[2] = 2; m_nSort[3] = 3; if(m_pParent) { // Update neighbor pointers (and our neighbors' neighbor pointers) m_pParent->m_pChild[nQuadrant] = this; UpdateNeighbors(); for(int i=0; i<4; i++) { if(m_pNeighbor[i]) m_pNeighbor[i]->UpdateNeighbors(); } } // Set up the corner boundaries for this node switch(nQuadrant) { case TopLeft: m_fCorner[0] = m_pParent->m_fCorner[0]; m_fCorner[1] = m_pParent->m_fCorner[1]; m_fCorner[2] = m_pParent->m_fCorner[0] + (m_pParent->m_fCorner[2] - m_pParent->m_fCorner[0]) * 0.5f; m_fCorner[3] = m_pParent->m_fCorner[1] + (m_pParent->m_fCorner[3] - m_pParent->m_fCorner[1]) * 0.5f; break; case TopRight: m_fCorner[0] = m_pParent->m_fCorner[0] + (m_pParent->m_fCorner[2] - m_pParent->m_fCorner[0]) * 0.5f; m_fCorner[1] = m_pParent->m_fCorner[1]; m_fCorner[2] = m_pParent->m_fCorner[2]; m_fCorner[3] = m_pParent->m_fCorner[1] + (m_pParent->m_fCorner[3] - m_pParent->m_fCorner[1]) * 0.5f; break; case BottomLeft: m_fCorner[0] = m_pParent->m_fCorner[0]; m_fCorner[1] = m_pParent->m_fCorner[1] + (m_pParent->m_fCorner[3] - m_pParent->m_fCorner[1]) * 0.5f; m_fCorner[2] = m_pParent->m_fCorner[0] + (m_pParent->m_fCorner[2] - m_pParent->m_fCorner[0]) * 0.5f; m_fCorner[3] = m_pParent->m_fCorner[3]; break; case BottomRight: m_fCorner[0] = m_pParent->m_fCorner[0] + (m_pParent->m_fCorner[2] - m_pParent->m_fCorner[0]) * 0.5f; m_fCorner[1] = m_pParent->m_fCorner[1] + (m_pParent->m_fCorner[3] - m_pParent->m_fCorner[1]) * 0.5f; m_fCorner[2] = m_pParent->m_fCorner[2]; m_fCorner[3] = m_pParent->m_fCorner[3]; break; default: // Top-level node, no parent exists m_fCorner[0] = 0.0f; m_fCorner[1] = 0.0f; m_fCorner[2] = 1.0f; m_fCorner[3] = 1.0f; break; } // Initialize the node builder structure for this node int x, y, nIndex = 0; float fXOffset = (m_fCorner[2] - m_fCorner[0]) / (HEIGHT_MAP_WIDTH-1); float fYOffset = (m_fCorner[3] - m_fCorner[1]) / (HEIGHT_MAP_WIDTH-1); float fY = m_fCorner[1] - fYOffset; for(y=0; y<BORDER_MAP_WIDTH; y++) { float fX = m_fCorner[0] - fXOffset; for(x=0; x<BORDER_MAP_WIDTH; x++) { builder.coord[nIndex++].Init(nFace, fX, fY, m_pMap->GetRadius()); fX += fXOffset; } fY += fYOffset; } // Now pass this node to all factories and objects that might affect it for(CPlanetaryMap::iterator it = m_pMap->begin(); it != m_pMap->end(); it++) { if((*it)->AffectsNode(this)) (*it)->BuildNode(this); } if(builder.pb.GetBuffer() != NULL) { m_nTextureID = m_pMap->GetTextureArray().LockTexture(); m_pMap->GetTextureArray().Update(m_nTextureID, &builder.pb); } builder.ComputeNormals(); m_nBumpID = m_pMap->GetTextureArray().LockTexture(); unsigned char *pBuffer = (unsigned char *)builder.pb.GetBuffer(); nIndex = 0; for(y=0; y<HEIGHT_MAP_WIDTH; y++) { for(x=0; x<HEIGHT_MAP_WIDTH; x++) { CVector vNormal = builder.vNormal[nIndex]; vNormal *= 128.0f / vNormal.Magnitude(); *pBuffer++ = (unsigned char)(vNormal.x + 128.0f); *pBuffer++ = (unsigned char)(vNormal.y + 128.0f); *pBuffer++ = (unsigned char)(vNormal.z + 128.0f); nIndex++; } } m_pMap->GetTextureArray().Update(m_nBumpID, &builder.pb); // Initialize the vertex map m_pbHeightMap.Init(SURFACE_MAP_WIDTH, SURFACE_MAP_WIDTH, 1, 1, GL_ALPHA, GL_FLOAT); float *pfHeightMap = (float *)m_pbHeightMap.GetBuffer(); nIndex = 0; for(y=0; y<SURFACE_MAP_WIDTH; y++) { int nCoord = (y*HEIGHT_MAP_SCALE+1) * BORDER_MAP_WIDTH + 1; int nNormal = y*HEIGHT_MAP_SCALE * HEIGHT_MAP_WIDTH; for(x=0; x<SURFACE_MAP_WIDTH; x++) { *pfHeightMap++ = builder.coord[nCoord].GetHeight(); CPlanetaryVertex *pVertex = &m_vNode[nIndex++]; pVertex->m_vPosition = builder.coord[nCoord].GetPositionVector(); pVertex->m_vNormal = builder.vNormal[nNormal]; pVertex->m_fTexCoord[0] = builder.coord[nCoord].x; pVertex->m_fTexCoord[1] = builder.coord[nCoord].y; nCoord += HEIGHT_MAP_SCALE; nNormal += HEIGHT_MAP_SCALE; } } m_boVertex.Init(&m_shape, SURFACE_MAP_COUNT, m_vNode); } CPlanetaryMapNode *CPlanetaryMapNode::FindQuadrantNeighbor(int nQuadrant, int nEdge, bool bForceSplit) { // When neighbors cross from one face of the cube to another, a mapping is needed to find the correct quadrant static const unsigned char nTopLeftTopEdge[6] = { BottomRight, TopLeft, TopRight, BottomLeft, BottomLeft, TopRight }; static const unsigned char nTopLeftLeftEdge[6] = { TopRight, TopRight, TopLeft, BottomRight, TopRight, TopRight }; static const unsigned char nTopRightTopEdge[6] = { TopRight, BottomLeft, TopLeft, BottomRight, BottomRight, TopLeft }; static const unsigned char nTopRightRightEdge[6] = { TopLeft, TopLeft, TopRight, BottomLeft, TopLeft, TopLeft }; static const unsigned char nBottomLeftBottomEdge[6] = { TopRight, BottomLeft, TopLeft, BottomRight, TopLeft, BottomRight }; static const unsigned char nBottomLeftLeftEdge[6] = { BottomRight, BottomRight, TopRight, BottomLeft, BottomRight, BottomRight }; static const unsigned char nBottomRightBottomEdge[6] = { BottomRight, TopLeft, TopRight, BottomLeft, TopRight, BottomLeft }; static const unsigned char nBottomRightRightEdge[6] = { BottomLeft, BottomLeft, TopLeft, BottomRight, BottomLeft, BottomLeft }; CPlanetaryMapNode *pNeighbor = NULL; int nChild; switch(nQuadrant) { case TopLeft: switch(nEdge) { case TopEdge: if(m_pNeighbor[nEdge]) { nChild = (m_pNeighbor[nEdge]->GetFace() == GetFace()) ? BottomLeft : nTopLeftTopEdge[GetFace()]; if(bForceSplit) m_pNeighbor[nEdge]->Split(nChild); pNeighbor = m_pNeighbor[nEdge]->m_pChild[nChild]; } break; case RightEdge: pNeighbor = m_pChild[TopRight]; break; case BottomEdge: pNeighbor = m_pChild[BottomLeft]; break; case LeftEdge: if(m_pNeighbor[nEdge]) { nChild = (m_pNeighbor[nEdge]->GetFace() == GetFace()) ? TopRight : nTopLeftLeftEdge[GetFace()]; if(bForceSplit) m_pNeighbor[nEdge]->Split(nChild); pNeighbor = m_pNeighbor[nEdge]->m_pChild[nChild]; } break; } break; case TopRight: switch(nEdge) { case TopEdge: if(m_pNeighbor[nEdge]) { nChild = (m_pNeighbor[nEdge]->GetFace() == GetFace()) ? BottomRight : nTopRightTopEdge[GetFace()]; if(bForceSplit) m_pNeighbor[nEdge]->Split(nChild); pNeighbor = m_pNeighbor[nEdge]->m_pChild[nChild]; } break; case RightEdge: if(m_pNeighbor[nEdge]) { nChild = (m_pNeighbor[nEdge]->GetFace() == GetFace()) ? TopLeft : nTopRightRightEdge[GetFace()]; if(bForceSplit) m_pNeighbor[nEdge]->Split(nChild); pNeighbor = m_pNeighbor[nEdge]->m_pChild[nChild]; } break; case BottomEdge: pNeighbor = m_pChild[BottomRight]; break; case LeftEdge: pNeighbor = m_pChild[TopLeft]; break; } break; case BottomLeft: switch(nEdge) { case TopEdge: pNeighbor = m_pChild[TopLeft]; break; case RightEdge: pNeighbor = m_pChild[BottomRight]; break; case BottomEdge: if(m_pNeighbor[nEdge]) { nChild = (m_pNeighbor[nEdge]->GetFace() == GetFace()) ? TopLeft : nBottomLeftBottomEdge[GetFace()]; if(bForceSplit) m_pNeighbor[nEdge]->Split(nChild); pNeighbor = m_pNeighbor[nEdge]->m_pChild[nChild]; } break; case LeftEdge: if(m_pNeighbor[nEdge]) { nChild = (m_pNeighbor[nEdge]->GetFace() == GetFace()) ? BottomRight : nBottomLeftLeftEdge[GetFace()]; if(bForceSplit) m_pNeighbor[nEdge]->Split(nChild); pNeighbor = m_pNeighbor[nEdge]->m_pChild[nChild]; } break; } break; case BottomRight: switch(nEdge) { case TopEdge: pNeighbor = m_pChild[TopRight]; break; case RightEdge: if(m_pNeighbor[nEdge]) { nChild = (m_pNeighbor[nEdge]->GetFace() == GetFace()) ? BottomLeft : nBottomRightRightEdge[GetFace()]; if(bForceSplit) m_pNeighbor[nEdge]->Split(nChild); pNeighbor = m_pNeighbor[nEdge]->m_pChild[nChild]; } break; case BottomEdge: if(m_pNeighbor[nEdge]) { nChild = (m_pNeighbor[nEdge]->GetFace() == GetFace()) ? TopRight : nBottomRightBottomEdge[GetFace()]; if(bForceSplit) m_pNeighbor[nEdge]->Split(nChild); pNeighbor = m_pNeighbor[nEdge]->m_pChild[nChild]; } break; case LeftEdge: pNeighbor = m_pChild[BottomLeft]; break; } break; } return pNeighbor; } void CPlanetaryMapNode::Split(int nQuadrant) { // If the requested quadrant is already split, return if(m_pChild[nQuadrant]) return; // Make sure the affected edges have neighbors by calling the force-splitting version of FindNeighbor() switch(nQuadrant) { case TopLeft: if(!FindNeighbor(TopEdge, true) || !FindNeighbor(LeftEdge, true)) return; break; case TopRight: if(!FindNeighbor(TopEdge, true) || !FindNeighbor(RightEdge, true)) return; break; case BottomLeft: if(!FindNeighbor(BottomEdge, true) || !FindNeighbor(LeftEdge, true)) return; break; case BottomRight: if(!FindNeighbor(BottomEdge, true) || !FindNeighbor(RightEdge, true)) return; break; } // Finally, check the map to see if we've already split too many times during this frame if(m_pMap->CanSplit()) m_pChild[nQuadrant] = new CPlanetaryMapNode(this, nQuadrant); } bool CPlanetaryMapNode::CanMerge() { // If this node has children of its own, it can't be merged if(!IsLeaf()) return false; // If this node has any neighbors with children bordering this node, it can't be merged if(m_pNeighbor[TopEdge] && (FindQuadrantNeighbor(TopLeft, TopEdge) || FindQuadrantNeighbor(TopRight, TopEdge))) return false; if(m_pNeighbor[RightEdge] && (FindQuadrantNeighbor(TopRight, RightEdge) || FindQuadrantNeighbor(BottomRight, RightEdge))) return false; if(m_pNeighbor[BottomEdge] && (FindQuadrantNeighbor(BottomRight, BottomEdge) || FindQuadrantNeighbor(BottomLeft, BottomEdge))) return false; if(m_pNeighbor[LeftEdge] && (FindQuadrantNeighbor(BottomLeft, LeftEdge) || FindQuadrantNeighbor(TopLeft, LeftEdge))) return false; // If none of the above restrictions apply, this node can be merged return true; } bool CPlanetaryMapNode::Merge(int nQuadrant) { // If the requested quadrant does not exist, return success (nothing to do) CPlanetaryMapNode *pNode = m_pChild[nQuadrant]; if(!pNode) return true; // If any of its children fail to merge, or if it fails the merge test, return failure bool bSuccess = true; if(!pNode->Merge(0)) bSuccess = false; if(!pNode->Merge(1)) bSuccess = false; if(!pNode->Merge(2)) bSuccess = false; if(!pNode->Merge(3)) bSuccess = false; if(!bSuccess || !pNode->CanMerge()) return false; // Remove the quadrant delete m_pChild[nQuadrant]; return true; } void CPlanetaryMapNode::UpdateSurface() { // Get the camera position and clear the node flags set by this function CVector vCamera = m_pMap->GetCameraPosition(); m_nNodeFlags &= ~(CameraInMask | BeyondHorizonMask | OutsideFrustumMask); // Calculate the map coordinates for the center of each quadrant short nFace = GetFace(); float fMid[2] = {CMath::Avg(m_fCorner[0], m_fCorner[2]), CMath::Avg(m_fCorner[1], m_fCorner[3])}; float x[2] = {CMath::Avg(m_fCorner[0], fMid[0]), CMath::Avg(m_fCorner[2], fMid[0])}; float y[2] = {CMath::Avg(m_fCorner[1], fMid[1]), CMath::Avg(m_fCorner[3], fMid[1])}; CPlanetaryMapCoord cQuadrant[4] = { CPlanetaryMapCoord(nFace, x[0], y[0]), CPlanetaryMapCoord(nFace, x[1], y[0]), CPlanetaryMapCoord(nFace, x[0], y[1]), CPlanetaryMapCoord(nFace, x[1], y[1]) }; // Calculate the 3D position for the center of each quadrant CVector vQuadrant[4] = { cQuadrant[0].GetPositionVector(m_pMap->GetFrustumRadius()), cQuadrant[1].GetPositionVector(m_pMap->GetFrustumRadius()), cQuadrant[2].GetPositionVector(m_pMap->GetFrustumRadius()), cQuadrant[3].GetPositionVector(m_pMap->GetFrustumRadius()), }; // Calculate the distance to the camera for the center of each quadrant float fDistance[4] = { vCamera.Distance(vQuadrant[0]), vCamera.Distance(vQuadrant[1]), vCamera.Distance(vQuadrant[2]), vCamera.Distance(vQuadrant[3]), }; // Now sort the quadrants by distance (used for updating and rendering order) // Don't use the actual distances because there will be precision problems float xCoord, yCoord; GetFaceCoordinates(nFace, vCamera, xCoord, yCoord); if(xCoord < fMid[0]) { if(yCoord < fMid[1]) { m_nSort[0] = 0; // Closest m_nSort[1] = 1; // Doesn't matter m_nSort[2] = 2; // Doesn't matter m_nSort[3] = 3; // Farthest } else { m_nSort[0] = 2; // Closest m_nSort[1] = 0; // Doesn't matter m_nSort[2] = 3; // Doesn't matter m_nSort[3] = 1; // Farthest } } else { if(yCoord < fMid[1]) { m_nSort[0] = 1; // Closest m_nSort[1] = 0; // Doesn't matter m_nSort[2] = 3; // Doesn't matter m_nSort[3] = 2; // Farthest } else { m_nSort[0] = 3; // Closest m_nSort[1] = 1; // Doesn't matter m_nSort[2] = 2; // Doesn't matter m_nSort[3] = 0; // Farthest } } // Calculate the quadrant size (the length of the diagonal), and use that to calculate the radius for view frustum culling float fQuadrantSize = vQuadrant[TopLeft].Distance(vQuadrant[BottomRight] * (m_pMap->GetRadius()/m_pMap->GetFrustumRadius())); float fRadius = CMath::Max(fQuadrantSize, m_pMap->GetMaxHeight()); // For split priority, we can't use the true quadrant size because quadrants near the corners of cube faces are smaller than quadrants mear the center // This caused an odd-looking artifact at the corners where nodes nearest the camera were at a lower detail level than nodes farther away fQuadrantSize = (m_fCorner[2]-m_fCorner[0]) * m_pMap->GetRadius(); float fPriority = (fQuadrantSize <= m_pMap->GetMaxHeight()*0.001f) ? 0.0f : m_pMap->GetSplitFactor() * powf(fQuadrantSize, m_pMap->GetSplitPower()); // Update each quadrant in forward Z order (to split nodes closer to the camera first) for(int i=0; i<4; i++) { int nQuadrant = m_nSort[i]; // Check to see if the camera's in this quadrant if(HitTest(m_pMap->GetCameraCoord(), nQuadrant)) m_nNodeFlags |= (nQuadrant << 10) & CameraInMask; else { // Check the quadrant against the horizon distance if(m_pMap->GetHorizonDistance() > 0.0f && fDistance[nQuadrant]-fRadius > m_pMap->GetHorizonDistance()) { m_nNodeFlags |= 1 << (16+nQuadrant); Merge(nQuadrant); continue; } // Check the quadrant against the view frustum if(!m_pMap->GetViewFrustum().IsInFrustum(vQuadrant[nQuadrant], fRadius)) { m_nNodeFlags |= 1 << (20+nQuadrant); Merge(nQuadrant); continue; } } // If the quadrant wasn't culled, check its distance against the priority to see if it should be merged if(fDistance[nQuadrant] > fPriority) { Merge(nQuadrant); continue; } // If we're not trying to merge it, we should split it (if it doesn't already exist) and update its children Split(nQuadrant); if(m_pChild[nQuadrant]) m_pChild[nQuadrant]->UpdateSurface(); } } int CPlanetaryMapNode::DrawSurface() { m_pMap->UpdateMaxDepth(GetLevel()); static const unsigned short nFan[10] = {20, 22, 12, 2, 10, 18, 28, 38, 30, 22}; static const unsigned short nOther[4][6] = {{0, 10, 2, 2, 12, 4}, {4, 12, 22, 22, 30, 40}, {40, 30, 38, 38, 28, 36}, {36, 28, 18, 18, 10, 0}}; static const unsigned short nEdge[4][2] = {{1, 3}, {13, 31}, {39, 37}, {27, 9}}; static unsigned short nMesh[48]; static unsigned short nMeshIndex; int i, n, nQuadrant; int nTriangles = 0; // If we need it, set up the texture state for this node bool bUseTexture = HasTexture() && (!m_pChild[0] || !m_pChild[1] || !m_pChild[2] || !m_pChild[3]); if(bUseTexture) { CMatrix4 mTexture; glActiveTexture(GL_TEXTURE1); m_pMap->GetTextureArray().MapCorners(m_nBumpID, mTexture, m_fCorner[0], m_fCorner[1], m_fCorner[2], m_fCorner[3]); glPushMatrix(); glLoadMatrixf(mTexture); glActiveTexture(GL_TEXTURE0); m_pMap->GetTextureArray().MapCorners(m_nTextureID, mTexture, m_fCorner[0], m_fCorner[1], m_fCorner[2], m_fCorner[3]); glPushMatrix(); glLoadMatrixf(mTexture); } // Then draw the quadrants in forward-Z order (to avoid pixel overdraw) for(i=0; i<4; i++) { nQuadrant = m_nSort[i]; if(IsBeyondHorizon(nQuadrant) || IsOutsideFrustum(nQuadrant)) continue; if(m_pChild[nQuadrant]) nTriangles += m_pChild[nQuadrant]->DrawSurface(); else { m_pMap->IncrementNodeCount(); m_boVertex.Enable(&m_shape); // Regardless of whether any of the neighbors are split, each quadrant has a fan of 8 triangles in its center for(n=0; n<10; n++) nMesh[n] = nFan[n] + m_nQuadrantOffset[nQuadrant]; glDrawElements(GL_TRIANGLE_FAN, 10, GL_UNSIGNED_SHORT, nMesh); nTriangles += 8; // Each quadrant has 2 triangles on each edge, which are split into 4 if the quadrant's neighbor is split. nMeshIndex = 0; for(n=0; n<4; n++) { bool bNeighborSplit = FindQuadrantNeighbor(nQuadrant, n) != NULL; nMesh[nMeshIndex++] = nOther[n][0] + m_nQuadrantOffset[nQuadrant]; nMesh[nMeshIndex++] = nOther[n][1] + m_nQuadrantOffset[nQuadrant]; if(bNeighborSplit) { nMesh[nMeshIndex++] = nEdge[n][0] + m_nQuadrantOffset[nQuadrant]; nMesh[nMeshIndex++] = nEdge[n][0] + m_nQuadrantOffset[nQuadrant]; nMesh[nMeshIndex++] = nOther[n][1] + m_nQuadrantOffset[nQuadrant]; } nMesh[nMeshIndex++] = nOther[n][2] + m_nQuadrantOffset[nQuadrant]; nMesh[nMeshIndex++] = nOther[n][3] + m_nQuadrantOffset[nQuadrant]; nMesh[nMeshIndex++] = nOther[n][4] + m_nQuadrantOffset[nQuadrant]; if(bNeighborSplit) { nMesh[nMeshIndex++] = nEdge[n][1] + m_nQuadrantOffset[nQuadrant]; nMesh[nMeshIndex++] = nEdge[n][1] + m_nQuadrantOffset[nQuadrant]; nMesh[nMeshIndex++] = nOther[n][4] + m_nQuadrantOffset[nQuadrant]; } nMesh[nMeshIndex++] = nOther[n][5] + m_nQuadrantOffset[nQuadrant]; } // Draw the mesh for this quadrant glDrawElements(GL_TRIANGLES, nMeshIndex, GL_UNSIGNED_SHORT, nMesh); nTriangles += nMeshIndex/3; } } // Clean up the texture states for this node if(bUseTexture) { glClientActiveTexture(GL_TEXTURE1); glActiveTexture(GL_TEXTURE1); glPopMatrix(); glClientActiveTexture(GL_TEXTURE0); glActiveTexture(GL_TEXTURE0); glPopMatrix(); } return nTriangles; }
logzero/sandbox
src/Planet/PlanetaryMapNode.cpp
C++
bsd-3-clause
25,444
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include "base/files/file_enumerator.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/values.h" #include "chrome/browser/extensions/extension_garbage_collector.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_service_test_base.h" #include "chrome/browser/extensions/install_tracker.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_constants.h" #include "chrome/test/base/testing_profile.h" #include "components/prefs/scoped_user_pref_update.h" #include "content/public/browser/plugin_service.h" #include "content/public/test/browser_task_environment.h" #include "content/public/test/test_utils.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/pref_names.h" #include "ppapi/buildflags/buildflags.h" namespace extensions { class ExtensionGarbageCollectorUnitTest : public ExtensionServiceTestBase { protected: void InitPluginService() { #if BUILDFLAG(ENABLE_PLUGINS) content::PluginService::GetInstance()->Init(); #endif } // A delayed task to call GarbageCollectExtensions is posted by // ExtensionGarbageCollector's constructor. But, as the test won't wait for // the delayed task to be called, we have to call it manually instead. void GarbageCollectExtensions() { ExtensionGarbageCollector::Get(profile_.get()) ->GarbageCollectExtensionsForTest(); // Wait for GarbageCollectExtensions task to complete. content::RunAllTasksUntilIdle(); } }; // Test that partially deleted extensions are cleaned up during startup. TEST_F(ExtensionGarbageCollectorUnitTest, CleanupOnStartup) { const std::string kExtensionId = "behllobkkfkfnphdnhnkndlbkcpglgmj"; InitPluginService(); InitializeGoodInstalledExtensionService(); // Simulate that one of them got partially deleted by clearing its pref. { DictionaryPrefUpdate update(profile_->GetPrefs(), pref_names::kExtensions); base::DictionaryValue* dict = update.Get(); ASSERT_TRUE(dict != NULL); dict->Remove(kExtensionId, NULL); } service_->Init(); GarbageCollectExtensions(); base::FileEnumerator dirs(extensions_install_dir(), false, // not recursive base::FileEnumerator::DIRECTORIES); size_t count = 0; while (!dirs.Next().empty()) count++; // We should have only gotten two extensions now. EXPECT_EQ(2u, count); // And extension1 dir should now be toast. base::FilePath extension_dir = extensions_install_dir().AppendASCII(kExtensionId); ASSERT_FALSE(base::PathExists(extension_dir)); } // Test that garbage collection doesn't delete anything while a crx is being // installed. TEST_F(ExtensionGarbageCollectorUnitTest, NoCleanupDuringInstall) { const std::string kExtensionId = "behllobkkfkfnphdnhnkndlbkcpglgmj"; InitPluginService(); InitializeGoodInstalledExtensionService(); // Simulate that one of them got partially deleted by clearing its pref. { DictionaryPrefUpdate update(profile_->GetPrefs(), pref_names::kExtensions); base::DictionaryValue* dict = update.Get(); ASSERT_TRUE(dict != NULL); dict->Remove(kExtensionId, NULL); } service_->Init(); // Simulate a CRX installation. InstallTracker::Get(profile_.get())->OnBeginCrxInstall(kExtensionId); GarbageCollectExtensions(); // extension1 dir should still exist. base::FilePath extension_dir = extensions_install_dir().AppendASCII(kExtensionId); ASSERT_TRUE(base::PathExists(extension_dir)); // Finish CRX installation and re-run garbage collection. InstallTracker::Get(profile_.get())->OnFinishCrxInstall(kExtensionId, false); GarbageCollectExtensions(); // extension1 dir should be gone ASSERT_FALSE(base::PathExists(extension_dir)); } // Test that GarbageCollectExtensions deletes the right versions of an // extension. TEST_F(ExtensionGarbageCollectorUnitTest, GarbageCollectWithPendingUpdates) { InitPluginService(); base::FilePath source_install_dir = data_dir().AppendASCII("pending_updates").AppendASCII("Extensions"); base::FilePath pref_path = source_install_dir.DirName().Append(chrome::kPreferencesFilename); InitializeInstalledExtensionService(pref_path, source_install_dir); // This is the directory that is going to be deleted, so make sure it actually // is there before the garbage collection. ASSERT_TRUE(base::PathExists(extensions_install_dir().AppendASCII( "hpiknbiabeeppbpihjehijgoemciehgk/3"))); GarbageCollectExtensions(); // Verify that the pending update for the first extension didn't get // deleted. EXPECT_TRUE(base::PathExists(extensions_install_dir().AppendASCII( "bjafgdebaacbbbecmhlhpofkepfkgcpa/1.0"))); EXPECT_TRUE(base::PathExists(extensions_install_dir().AppendASCII( "bjafgdebaacbbbecmhlhpofkepfkgcpa/2.0"))); EXPECT_TRUE(base::PathExists(extensions_install_dir().AppendASCII( "hpiknbiabeeppbpihjehijgoemciehgk/2"))); EXPECT_FALSE(base::PathExists(extensions_install_dir().AppendASCII( "hpiknbiabeeppbpihjehijgoemciehgk/3"))); } // Test that pending updates are properly handled on startup. TEST_F(ExtensionGarbageCollectorUnitTest, UpdateOnStartup) { InitPluginService(); base::FilePath source_install_dir = data_dir().AppendASCII("pending_updates").AppendASCII("Extensions"); base::FilePath pref_path = source_install_dir.DirName().Append(chrome::kPreferencesFilename); InitializeInstalledExtensionService(pref_path, source_install_dir); // This is the directory that is going to be deleted, so make sure it actually // is there before the garbage collection. ASSERT_TRUE(base::PathExists(extensions_install_dir().AppendASCII( "hpiknbiabeeppbpihjehijgoemciehgk/3"))); service_->Init(); GarbageCollectExtensions(); // Verify that the pending update for the first extension got installed. EXPECT_FALSE(base::PathExists(extensions_install_dir().AppendASCII( "bjafgdebaacbbbecmhlhpofkepfkgcpa/1.0"))); EXPECT_TRUE(base::PathExists(extensions_install_dir().AppendASCII( "bjafgdebaacbbbecmhlhpofkepfkgcpa/2.0"))); EXPECT_TRUE(base::PathExists(extensions_install_dir().AppendASCII( "hpiknbiabeeppbpihjehijgoemciehgk/2"))); EXPECT_FALSE(base::PathExists(extensions_install_dir().AppendASCII( "hpiknbiabeeppbpihjehijgoemciehgk/3"))); // Make sure update information got deleted. ExtensionPrefs* prefs = ExtensionPrefs::Get(profile_.get()); EXPECT_FALSE( prefs->GetDelayedInstallInfo("bjafgdebaacbbbecmhlhpofkepfkgcpa")); } } // namespace extensions
endlessm/chromium-browser
chrome/browser/extensions/extension_garbage_collector_unittest.cc
C++
bsd-3-clause
6,823
package com.jsonde.gui.reports.custom; import javax.swing.*; public interface ReportGenerator { JComponent generateReport(); }
bedrin/jsonde
jsonde.gui/src/main/java/com/jsonde/gui/reports/custom/ReportGenerator.java
Java
bsd-3-clause
135
// Copyright © 2010 onwards, Andrew Whewell // All rights reserved. // // Redistribution and use of this software 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 name of the author nor the names of the program's 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 AUTHORS OF THE SOFTWARE 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. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using InterfaceFactory; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Test.Framework; using VirtualRadar.Interface; using VirtualRadar.Interface.BaseStation; using VirtualRadar.Interface.Database; using VirtualRadar.Interface.Listener; using VirtualRadar.Interface.Presenter; using VirtualRadar.Interface.Settings; using VirtualRadar.Interface.StandingData; using VirtualRadar.Interface.View; using VirtualRadar.Interface.WebServer; using VirtualRadar.Interface.WebSite; using VirtualRadar.Localisation; namespace Test.VirtualRadar.Library.Presenter { [TestClass] public class SplashPresenterTests { #region TestContext, Fields, TestInitialise, TestCleanup public TestContext TestContext { get; set; } private IClassFactory _ClassFactorySnapshot; private ISplashPresenter _Presenter; private Mock<ISplashPresenterProvider> _Provider; private Mock<ISplashView> _View; private Configuration _Configuration; private Mock<IConfigurationStorage> _ConfigurationStorage; private Mock<ILog> _Log; private Mock<IHeartbeatService> _HearbeatService; private Mock<IBaseStationDatabase> _BaseStationDatabase; private Mock<IAutoConfigBaseStationDatabase> _AutoConfigBaseStationDatabase; private Mock<IStandingDataManager> _StandingDataManager; private Mock<IAutoConfigListener> _AutoConfigListener; private Mock<IListener> _Listener; private Mock<IBaseStationAircraftList> _BaseStationAircraftList; private Mock<IWebServer> _WebServer; private Mock<IAutoConfigWebServer> _AutoConfigWebServer; private Mock<IWebSite> _WebSite; private Mock<ISimpleAircraftList> _FlightSimulatorXAircraftList; private Mock<IUniversalPlugAndPlayManager> _UniversalPlugAndPlayManager; private Mock<IConnectionLogger> _ConnectionLogger; private Mock<ILogDatabase> _LogDatabase; private Mock<IBackgroundDataDownloader> _BackgroundDataDownloader; private Mock<IPluginManager> _PluginManager; private Mock<IApplicationInformation> _ApplicationInformation; private Mock<IAutoConfigPictureFolderCache> _AutoConfigPictureFolderCache; private Mock<IRebroadcastServerManager> _RebroadcastServerManager; private Mock<IStatistics> _Statistics; private EventRecorder<EventArgs<Exception>> _BackgroundExceptionEvent; public interface IPluginBackgroundThreadCatcher : IPlugin, IBackgroundThreadExceptionCatcher { } [TestInitialize] public void TestInitialise() { _ClassFactorySnapshot = Factory.TakeSnapshot(); _ConfigurationStorage = TestUtilities.CreateMockSingleton<IConfigurationStorage>(); _Configuration = new Configuration(); _ConfigurationStorage.Setup(c => c.Load()).Returns(_Configuration); _AutoConfigListener = TestUtilities.CreateMockSingleton<IAutoConfigListener>(); _AutoConfigListener.Setup(r => r.Listener).Returns((IListener)null); _AutoConfigListener.Setup(r => r.Initialise()).Callback(() => { _AutoConfigListener.Setup(r => r.Listener).Returns(_Listener.Object); }); _Log = TestUtilities.CreateMockSingleton<ILog>(); _HearbeatService = TestUtilities.CreateMockSingleton<IHeartbeatService>(); _StandingDataManager = TestUtilities.CreateMockSingleton<IStandingDataManager>(); _Listener = new Mock<IListener>(MockBehavior.Default) { DefaultValue = DefaultValue.Mock }; _BaseStationAircraftList = TestUtilities.CreateMockImplementation<IBaseStationAircraftList>(); _AutoConfigWebServer = TestUtilities.CreateMockSingleton<IAutoConfigWebServer>(); _WebServer = new Mock<IWebServer>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); _AutoConfigWebServer.Setup(s => s.WebServer).Returns(_WebServer.Object); _WebSite = TestUtilities.CreateMockImplementation<IWebSite>(); _FlightSimulatorXAircraftList = TestUtilities.CreateMockImplementation<ISimpleAircraftList>(); _UniversalPlugAndPlayManager = TestUtilities.CreateMockImplementation<IUniversalPlugAndPlayManager>(); _ConnectionLogger = TestUtilities.CreateMockSingleton<IConnectionLogger>(); _LogDatabase = TestUtilities.CreateMockSingleton<ILogDatabase>(); _BackgroundDataDownloader = TestUtilities.CreateMockSingleton<IBackgroundDataDownloader>(); _PluginManager = TestUtilities.CreateMockSingleton<IPluginManager>(); _ApplicationInformation = TestUtilities.CreateMockImplementation<IApplicationInformation>(); _AutoConfigPictureFolderCache = TestUtilities.CreateMockSingleton<IAutoConfigPictureFolderCache>(); _RebroadcastServerManager = TestUtilities.CreateMockSingleton<IRebroadcastServerManager>(); _Statistics = TestUtilities.CreateMockSingleton<IStatistics>(); _BackgroundExceptionEvent = new EventRecorder<EventArgs<Exception>>(); _BaseStationDatabase = new Mock<IBaseStationDatabase>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); _AutoConfigBaseStationDatabase = TestUtilities.CreateMockSingleton<IAutoConfigBaseStationDatabase>(); _AutoConfigBaseStationDatabase.Setup(a => a.Database).Returns(_BaseStationDatabase.Object); _BaseStationDatabase.Setup(d => d.FileName).Returns("x"); _BaseStationDatabase.Setup(d => d.TestConnection()).Returns(true); _Provider = new Mock<ISplashPresenterProvider>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); _Provider.Setup(p => p.FolderExists(It.IsAny<string>())).Returns(true); _Presenter = Factory.Singleton.Resolve<ISplashPresenter>(); _Presenter.Provider = _Provider.Object; _View = new Mock<ISplashView>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); } [TestCleanup] public void TestCleanup() { Factory.RestoreSnapshot(_ClassFactorySnapshot); } #endregion #region Constructor [TestMethod] public void SplashPresenter_Constructor_Initialises_To_Known_State_And_Properties_Work() { _Presenter = Factory.Singleton.Resolve<ISplashPresenter>(); Assert.IsNotNull(_Presenter.Provider); TestUtilities.TestProperty(_Presenter, "Provider", _Presenter.Provider, _Provider.Object); } #endregion #region Initialise [TestMethod] public void SplashPresenter_Initialise_Sets_Application_Title() { _Presenter.Initialise(_View.Object); Assert.AreEqual(Strings.VirtualRadarServer, _View.Object.ApplicationName); } [TestMethod] public void SplashPresenter_Initialise_Sets_Application_Version() { _ApplicationInformation.Setup(p => p.ShortVersion).Returns("1.2.3"); _Presenter.Initialise(_View.Object); Assert.AreEqual("1.2.3", _View.Object.ApplicationVersion); } [TestMethod] public void SplashPresenter_Initialise_Initialises_Statistics() { _Presenter.Initialise(_View.Object); _Statistics.Verify(r => r.Initialise(), Times.Once()); } #endregion #region StartApplication #region Parsing command-line arguments [TestMethod] public void SplashPresenter_StartApplication_Reports_Parsing_Command_Line_Parameters() { _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _View.Verify(v => v.ReportProgress(Strings.SplashScreenParsingCommandLineParameters), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Reports_Problems_With_Unknown_Command_Line_Parameters() { foreach(string parameter in new string[] { "culture", "-culture", "workingFolder", "-workingFolder", "-SHOWCONFIGFOLDER" }) { TestCleanup(); TestInitialise(); _Presenter.Initialise(_View.Object); _Presenter.CommandLineArgs = new string[] { parameter }; _Presenter.StartApplication(); _View.Verify(v => v.ReportProblem(String.Format(Strings.UnrecognisedCommandLineParameterFull, parameter), Strings.UnrecognisedCommandLineParameterTitle, true), Times.Once()); } } [TestMethod] public void SplashPresenter_StartApplication_Does_Not_Stop_On_Acceptable_Command_Line_Parameters() { foreach(string parameter in new string[] { "-culture:", "-culture:X", "-culture:de-DE", "-CULTURE:en-US", "-WORKINGFOLDER:X", "-showConfigFolder" }) { TestCleanup(); TestInitialise(); _Presenter.Initialise(_View.Object); _Presenter.CommandLineArgs = new string[] { parameter }; _Presenter.StartApplication(); _View.Verify(v => v.ReportProblem(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()), Times.Never()); } } [TestMethod] public void SplashPresenter_StartApplication_Stops_Application_Working_Folder_Command_Line_Argument_Specifies_Invalid_Folder() { _Presenter.CommandLineArgs = new string[] { "-workingfolder:x" }; _Provider.Setup(p => p.FolderExists("x")).Returns(false); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _View.Verify(v => v.ReportProblem(String.Format(Strings.FolderDoesNotExistFull, "x"), Strings.FolderDoesNotExistTitle, true), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Overrides_Configuration_Folder_If_Command_Line_Argument_Requests_It() { _Presenter.CommandLineArgs = new string[] { "-workingfolder:x" }; _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); Assert.AreEqual("x", _ConfigurationStorage.Object.Folder); } #endregion #region Initialising the log [TestMethod] public void SplashPresenter_StartApplication_Reports_Initialising_The_Log() { _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _View.Verify(v => v.ReportProgress(Strings.SplashScreenInitialisingLog), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Truncates_The_Log() { _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _Log.Verify(g => g.Truncate(100), Times.Once()); _Log.Verify(g => g.Truncate(It.IsAny<int>()), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Records_Startup_In_Log() { _ApplicationInformation.Setup(p => p.FullVersion).Returns("5.4.3.2"); _ConfigurationStorage.Setup(c => c.Folder).Returns(@"c:\abc"); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _Log.Verify(g => g.WriteLine("Program started, version {0}", "5.4.3.2"), Times.Once()); _Log.Verify(g => g.WriteLine("Working folder {0}", @"c:\abc"), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Records_Custom_Working_Folder_In_Log() { _Presenter.CommandLineArgs = new string[] { "-workingFolder:xyz" }; _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _Log.Verify(g => g.WriteLine("Working folder {0}", @"xyz"), Times.Once()); _Log.Verify(g => g.WriteLine("Working folder {0}", It.IsAny<string>()), Times.Once()); } #endregion #region Loading the configuration for the first time [TestMethod] public void SplashPresenter_StartApplication_Does_First_Load_Of_Configuration() { string currentSection = null; _View.Setup(v => v.ReportProgress(It.IsAny<string>())).Callback((string section) => { currentSection = section; }); bool firstLoad = true; _ConfigurationStorage.Setup(c => c.Load()).Returns(_Configuration).Callback(() => { if(firstLoad) Assert.AreEqual(Strings.SplashScreenLoadingConfiguration, currentSection); firstLoad = false; }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _ConfigurationStorage.Verify(c => c.Load(), Times.AtLeastOnce()); } [TestMethod] public void SplashPresenter_StartApplication_Offers_User_Chance_To_Reset_Configuration_If_It_Cannot_Be_Loaded() { // A bug in an early version of VRS lead to configuration files that would throw an exception on load which, if left // unhandled, could prevent the application from loading at all _ConfigurationStorage.Setup(c => c.Load()).Returns(() => { throw new InvalidOperationException("Blah"); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); string message = String.Format(Strings.InvalidConfigurationFileFull, "Blah", _ConfigurationStorage.Object.Folder); _View.Verify(v => v.YesNoPrompt(message, Strings.InvalidConfigurationFileTitle, true), Times.Once()); _View.Verify(v => v.YesNoPrompt(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Will_Reset_Configuration_If_User_Requests_It_After_Load_Throws() { _ConfigurationStorage.Setup(c => c.Load()).Returns(() => { throw new InvalidOperationException("Blah"); }); _View.Setup(v => v.YesNoPrompt(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>())).Returns(true); _View.Setup(v => v.ReportProblem(Strings.DefaultSettingsSavedFull, Strings.DefaultSettingsSavedTitle, true)).Callback(() => { _ConfigurationStorage.Verify(c => c.Save(It.IsAny<Configuration>()), Times.Once()); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _View.Verify(v => v.ReportProblem(Strings.DefaultSettingsSavedFull, Strings.DefaultSettingsSavedTitle, true), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Will_Just_Quit_If_User_Requests_It_After_Load_Throws() { _ConfigurationStorage.Setup(c => c.Load()).Returns(() => { throw new InvalidOperationException("Blah"); }); _View.Setup(v => v.YesNoPrompt(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>())).Returns(false); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _ConfigurationStorage.Verify(c => c.Save(It.IsAny<Configuration>()), Times.Never()); _View.Verify(v => v.ReportProblem(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()), Times.Never()); _Provider.Verify(p => p.AbortApplication(), Times.Once()); } #endregion #region Heartbeat timer [TestMethod] public void SplashPresenter_StartApplication_Starts_The_HeartbeatService() { _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _HearbeatService.Verify(h => h.Start(), Times.Once()); } #endregion #region BaseStation database connection [TestMethod] public void SplashPresenter_StartApplication_Initialises_AutoConfigBaseStationDatabase() { string currentSection = null; _View.Setup(v => v.ReportProgress(It.IsAny<string>())).Callback((string section) => { currentSection = section; }); _AutoConfigBaseStationDatabase.Setup(a => a.Initialise()).Callback(() => { Assert.AreEqual(Strings.SplashScreenOpeningBaseStationDatabase, currentSection); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _AutoConfigBaseStationDatabase.Verify(a => a.Initialise(), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Tests_The_BaseStation_Database_Connection() { _BaseStationDatabase.Setup(d => d.TestConnection()).Callback(() => { _AutoConfigBaseStationDatabase.Verify(a => a.Initialise(), Times.Once()); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _BaseStationDatabase.Verify(d => d.TestConnection(), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Does_Not_Open_BaseStation_Database_Until_After_Configuration_Has_Been_Checked() { _BaseStationDatabase.Setup(v => v.TestConnection()).Callback(() => { _ConfigurationStorage.Verify(c => c.Load(), Times.Once()); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _BaseStationDatabase.Verify(d => d.TestConnection(), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Does_Not_Try_Opening_BaseStation_Database_If_FileName_Is_Null() { _BaseStationDatabase.Setup(d => d.FileName).Returns((string)null); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _BaseStationDatabase.Verify(d => d.TestConnection(), Times.Never()); } [TestMethod] public void SplashPresenter_StartApplication_Reports_Problem_Opening_BaseStation_Database() { _BaseStationDatabase.Setup(d => d.FileName).Returns("xyz"); _BaseStationDatabase.Setup(d => d.TestConnection()).Returns(false); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _View.Verify(v => v.ReportProblem(String.Format(Strings.CannotOpenBaseStationDatabaseFull, "xyz"), Strings.CannotOpenBaseStationDatabaseTitle, false), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Does_Not_Report_Problem_Opening_BaseStation_Database_If_FileName_Is_Null() { _BaseStationDatabase.Setup(d => d.FileName).Returns((string)null); _BaseStationDatabase.Setup(d => d.TestConnection()).Returns(false); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _View.Verify(v => v.ReportProblem(It.IsAny<string>(), Strings.CannotOpenBaseStationDatabaseTitle, It.IsAny<bool>()), Times.Never()); } [TestMethod] public void SplashPresenter_StartApplication_Does_Not_Report_Problem_If_BaseStation_Database_Can_Be_Opened() { _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _View.Verify(v => v.ReportProblem(It.IsAny<string>(), Strings.CannotOpenBaseStationDatabaseTitle, It.IsAny<bool>()), Times.Never()); } #endregion #region Picture folder cache [TestMethod] public void SplashPresenter_StartApplication_Initialises_Picture_Folder_Cache() { string currentSection = null; _View.Setup(v => v.ReportProgress(It.IsAny<string>())).Callback((string section) => { currentSection = section; }); _AutoConfigPictureFolderCache.Setup(a => a.Initialise()).Callback(() => { Assert.AreEqual(Strings.SplashScreenStartingPictureFolderCache, currentSection); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _AutoConfigPictureFolderCache.Verify(a => a.Initialise(), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Initialises_Picture_Folder_Cache_After_Loading_Configuration() { _AutoConfigPictureFolderCache.Setup(a => a.Initialise()).Callback(() => { _ConfigurationStorage.Verify(c => c.Load(), Times.Once()); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _AutoConfigPictureFolderCache.Verify(a => a.Initialise(), Times.Once()); } #endregion #region Standing data [TestMethod] public void SplashPresenter_StartApplication_Loads_Standing_Data() { string currentSection = null; _View.Setup(v => v.ReportProgress(It.IsAny<string>())).Callback((string section) => { currentSection = section; }); _StandingDataManager.Setup(m => m.Load()).Callback(() => { Assert.AreEqual(Strings.SplashScreenLoadingStandingData, currentSection); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _StandingDataManager.Verify(m => m.Load(), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Loads_Standing_Data_After_Loading_Configuration() { _StandingDataManager.Setup(m => m.Load()).Callback(() => { _ConfigurationStorage.Verify(c => c.Load(), Times.Once()); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _StandingDataManager.Verify(m => m.Load(), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Reports_Exceptions_Raised_During_Load_Of_Standing_Data() { var exception = new InvalidOperationException("oops"); _StandingDataManager.Setup(m => m.Load()).Callback(() => { throw exception; }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _Log.Verify(g => g.WriteLine("Exception caught during load of standing data: {0}", exception.ToString()), Times.Once()); _View.Verify(v => v.ReportProblem(String.Format(Strings.CannotLoadFlightRouteDataFull, exception.Message), Strings.CannotLoadFlightRouteDataTitle, false), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Starts_Background_Downloader() { _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _BackgroundDataDownloader.Verify(b => b.Start(), Times.Once()); } #endregion #region AutoConfigListener [TestMethod] public void SplashPresenter_StartApplication_Initialises_AutoConfigListener() { string currentSection = null; _View.Setup(v => v.ReportProgress(It.IsAny<string>())).Callback((string section) => { currentSection = section; }); _AutoConfigListener.Setup(m => m.Initialise()).Callback(() => { Assert.AreEqual(Strings.SplashScreenConnectingToBaseStation, currentSection); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _AutoConfigListener.Verify(b => b.Initialise(), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Initialises_AutoConfigListener_After_Loading_Configuration() { _AutoConfigListener.Setup(m => m.Initialise()).Callback(() => { _ConfigurationStorage.Verify(c => c.Load(), Times.Once()); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _StandingDataManager.Verify(m => m.Load(), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Hooks_AutoConfigListener_Background_Exception_Event() { _Presenter.BackgroundThreadExceptionHandler = _BackgroundExceptionEvent.Handler; _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _AutoConfigListener.Raise(b => b.ExceptionCaught += null, new EventArgs<Exception>(new InvalidOperationException())); Assert.AreEqual(1, _BackgroundExceptionEvent.CallCount); } [TestMethod] public void SplashPresenter_StartApplication_Connects_AutoConfigListener() { _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _Listener.Verify(b => b.Connect(It.IsAny<bool>()), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Connects_AutoConfigListener_Passing_AutoReconnectAtStartup_Configuration_Setting() { foreach(var autoReconnectAtStartup in new bool[] { true, false }) { TestCleanup(); TestInitialise(); _Configuration.BaseStationSettings.AutoReconnectAtStartup = autoReconnectAtStartup; _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _Listener.Verify(b => b.Connect(autoReconnectAtStartup), Times.Once()); } } [TestMethod] public void SplashPresenter_StartApplication_Reports_Failure_To_Connect_To_Data_Feed() { _Listener.Setup(b => b.Connect(false)).Callback(() => { throw new InvalidOperationException("msg here"); }); _Configuration.BaseStationSettings.AutoReconnectAtStartup = false; _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _View.Verify(v => v.ReportProblem(String.Format(Strings.CannotConnectToBaseStationFull, "msg here"), Strings.CannotConnectToBaseStationTitle, false), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Reports_Failure_To_Connect_To_Data_Feed_Regardless_Of_AutoReconnect_Setting() { _Listener.Setup(b => b.Connect(true)).Callback(() => { throw new InvalidOperationException("msg here"); }); _Configuration.BaseStationSettings.AutoReconnectAtStartup = true; _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _View.Verify(v => v.ReportProblem(String.Format(Strings.CannotConnectToBaseStationFull, "msg here"), Strings.CannotConnectToBaseStationTitle, false), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Logs_Failure_To_Connect_To_Data_Feed() { var exception = new InvalidOperationException("msg here"); _Listener.Setup(b => b.Connect(false)).Callback(() => { throw exception; }); _Configuration.BaseStationSettings.AutoReconnectAtStartup = false; _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _Log.Verify(g => g.WriteLine("Could not connect to data feed: {0}", exception.ToString()), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Logs_Failure_To_Connect_To_Data_Feed_Regardless_Of_AutoReconnect_Setting() { var exception = new InvalidOperationException("msg here"); _Listener.Setup(b => b.Connect(true)).Callback(() => { throw exception; }); _Configuration.BaseStationSettings.AutoReconnectAtStartup = true; _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _Log.Verify(g => g.WriteLine("Could not connect to data feed: {0}", exception.ToString()), Times.Once()); } #endregion #region BaseStationAircraftList [TestMethod] public void SplashPresenter_StartApplication_Starts_BaseStationAircraftList() { string currentSection = null; _View.Setup(v => v.ReportProgress(It.IsAny<string>())).Callback((string section) => { currentSection = section; }); _BaseStationAircraftList.Setup(a => a.Start()).Callback(() => { Assert.AreEqual(Strings.SplashScreenInitialisingAircraftList, currentSection); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _BaseStationAircraftList.Verify(a => a.Start(), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Starts_BaseStationAircraftList_After_Configuration_Has_Loaded() { _BaseStationAircraftList.Setup(a => a.Start()).Callback(() => { _ConfigurationStorage.Verify(c => c.Load(), Times.Once()); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); } [TestMethod] public void SplashPresenter_StartApplication_Starts_BaseStationAircraftList_After_Properties_Have_Been_Set() { _BaseStationAircraftList.Setup(a => a.Start()).Callback(() => { Assert.AreSame(_BaseStationDatabase.Object, _BaseStationAircraftList.Object.BaseStationDatabase); Assert.AreSame(_Listener.Object, _BaseStationAircraftList.Object.Listener); Assert.AreSame(_StandingDataManager.Object, _BaseStationAircraftList.Object.StandingDataManager); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); } [TestMethod] public void SplashPresenter_StartApplication_Hooks_BaseStationAircraftList_Background_Exception_Event() { _Presenter.BackgroundThreadExceptionHandler = _BackgroundExceptionEvent.Handler; _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); var exception = new InvalidOperationException(); _BaseStationAircraftList.Raise(b => b.ExceptionCaught += null, new EventArgs<Exception>(new InvalidOperationException())); Assert.AreEqual(1, _BackgroundExceptionEvent.CallCount); } [TestMethod] public void SplashPresenter_StartApplication_Copies_BaseStationAircraftList_To_View() { _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); Assert.AreEqual(_BaseStationAircraftList.Object, _View.Object.BaseStationAircraftList); } #endregion #region Web WebServer and Web Site [TestMethod] public void SplashPresenter_StartApplication_Initialises_AutoConfigWebServer() { _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _AutoConfigWebServer.Verify(a => a.Initialise(), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Hooks_Web_Server_Background_Exception_Event() { _Presenter.BackgroundThreadExceptionHandler = _BackgroundExceptionEvent.Handler; _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); var exception = new InvalidOperationException(); _WebServer.Raise(b => b.ExceptionCaught += null, new EventArgs<Exception>(new InvalidOperationException())); Assert.AreEqual(1, _BackgroundExceptionEvent.CallCount); } [TestMethod] public void SplashPresenter_StartApplication_Attches_ConnectionLogger_To_Server() { _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); Assert.AreSame(_WebServer.Object, _ConnectionLogger.Object.WebServer); Assert.AreSame(_LogDatabase.Object, _ConnectionLogger.Object.LogDatabase); _ConnectionLogger.Verify(c => c.Start(), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Attches_ConnectionLogger_ExceptionCaught_Handler() { _Presenter.BackgroundThreadExceptionHandler = _BackgroundExceptionEvent.Handler; _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); var exception = new InvalidOperationException(); _ConnectionLogger.Raise(b => b.ExceptionCaught += null, new EventArgs<Exception>(new InvalidOperationException())); Assert.AreEqual(1, _BackgroundExceptionEvent.CallCount); } [TestMethod] public void SplashPresenter_StartApplication_Attaches_Web_Site_To_Web_Server() { string currentSection = null; _View.Setup(v => v.ReportProgress(It.IsAny<string>())).Callback((string section) => { currentSection = section; }); _WebSite.Setup(s => s.AttachSiteToServer(_WebServer.Object)).Callback(() => { Assert.AreEqual(Strings.SplashScreenStartingWebServer, currentSection); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _WebSite.Verify(s => s.AttachSiteToServer(_WebServer.Object), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Attaches_Web_Site_After_Configuration_Has_Loaded() { _WebSite.Setup(s => s.AttachSiteToServer(_WebServer.Object)).Callback(() => { _ConfigurationStorage.Verify(c => c.Load(), Times.Once()); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); } [TestMethod] public void SplashPresenter_StartApplication_Sets_Properties_On_Web_Site() { _WebSite.Setup(s => s.AttachSiteToServer(_WebServer.Object)).Callback(() => { Assert.AreSame(_BaseStationAircraftList.Object, _WebSite.Object.BaseStationAircraftList); Assert.AreSame(_BaseStationDatabase.Object, _WebSite.Object.BaseStationDatabase); Assert.AreSame(_FlightSimulatorXAircraftList.Object, _WebSite.Object.FlightSimulatorAircraftList); Assert.AreSame(_StandingDataManager.Object, _WebSite.Object.StandingDataManager); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); } [TestMethod] public void SplashPresenter_StartApplication_Starts_Web_Server_Once_Site_And_Server_Are_Initialised() { _WebServer.SetupSet(s => s.Online = true).Callback(() => { _AutoConfigWebServer.Verify(a => a.Initialise(), Times.Once()); _WebSite.Verify(s => s.AttachSiteToServer(_WebServer.Object), Times.Once()); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _WebServer.VerifySet(s => s.Online = true, Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Picks_Up_HttpListenerExceptions_When_Starting_WebServer() { var exception = new HttpListenerException(); _WebServer.SetupSet(s => s.Online = true).Callback(() => { throw exception; }); _WebServer.Setup(a => a.Port).Returns(123); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _Log.Verify(g => g.WriteLine("Caught exception when starting web server: {0}", exception.ToString()), Times.Once()); _View.Verify(v => v.ReportProblem(String.Format(Strings.CannotStartWebServerFull, 123), Strings.CannotStartWebServerTitle, false), Times.Once()); _View.Verify(v => v.ReportProblem(Strings.SuggestUseDifferentPortFull, Strings.SuggestUseDifferentPortTitle, false), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Picks_Up_SocketExceptions_When_Starting_WebServer() { var exception = new SocketException(); _WebServer.SetupSet(s => s.Online = true).Callback(() => { throw exception; }); _WebServer.Setup(a => a.Port).Returns(123); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _Log.Verify(g => g.WriteLine("Caught exception when starting web server: {0}", exception.ToString()), Times.Once()); _View.Verify(v => v.ReportProblem(String.Format(Strings.CannotStartWebServerFull, 123), Strings.CannotStartWebServerTitle, false), Times.Once()); _View.Verify(v => v.ReportProblem(Strings.SuggestUseDifferentPortFull, Strings.SuggestUseDifferentPortTitle, false), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Copies_Web_Site_Flight_Simulator_Aircraft_List_To_View() { _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); Assert.AreEqual(_FlightSimulatorXAircraftList.Object, _View.Object.FlightSimulatorXAircraftList); } #endregion #region RebroadcastManager [TestMethod] public void SplashPresenter_StartApplication_Initialises_RebroadcastManager() { string currentSection = null; _View.Setup(v => v.ReportProgress(It.IsAny<string>())).Callback((string section) => { currentSection = section; }); _RebroadcastServerManager.Setup(r => r.Initialise()).Callback(() => { Assert.AreEqual(Strings.SplashScreenStartingRebroadcastServers, currentSection); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _RebroadcastServerManager.Verify(r => r.Initialise(), Times.Once()); Assert.AreEqual(true, _RebroadcastServerManager.Object.Online); } [TestMethod] public void SplashPresenter_StartApplication_Initialises_RebroadcastManager_After_Loading_Configuration() { _RebroadcastServerManager.Setup(m => m.Initialise()).Callback(() => { _ConfigurationStorage.Verify(c => c.Load(), Times.Once()); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _StandingDataManager.Verify(m => m.Load(), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Initialises_RebroadcastManager_After_Initialising_Listener() { _RebroadcastServerManager.Setup(m => m.Initialise()).Callback(() => { _AutoConfigListener.Verify(r => r.Initialise(), Times.Once()); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _AutoConfigListener.Verify(r => r.Initialise(), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Sets_Listener_On_RebroadcastManager_Before_Initialising() { _RebroadcastServerManager.Setup(m => m.Initialise()).Callback(() => { Assert.AreSame(_Listener.Object, _RebroadcastServerManager.Object.Listener); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _RebroadcastServerManager.Verify(r => r.Initialise(), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Hooks_RebroadcastManager_Background_Exception_Event() { _Presenter.BackgroundThreadExceptionHandler = _BackgroundExceptionEvent.Handler; _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); var exception = new InvalidOperationException(); _RebroadcastServerManager.Raise(b => b.ExceptionCaught += null, new EventArgs<Exception>(new InvalidOperationException())); Assert.AreEqual(1, _BackgroundExceptionEvent.CallCount); } #endregion #region UPnP Manager [TestMethod] public void SplashPresenter_StartApplication_Starts_UPnP_Manager() { string currentSection = null; _View.Setup(v => v.ReportProgress(It.IsAny<string>())).Callback((string section) => { currentSection = section; }); _UniversalPlugAndPlayManager.Setup(s => s.Initialise()).Callback(() => { Assert.AreEqual(Strings.SplashScreenInitialisingUPnPManager, currentSection); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _UniversalPlugAndPlayManager.Verify(s => s.Initialise(), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Starts_UPnP_Manager_After_Loading_Configuration() { _UniversalPlugAndPlayManager.Setup(s => s.Initialise()).Callback(() => { _ConfigurationStorage.Verify(c => c.Load(), Times.Once()); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); } [TestMethod] public void SplashPresenter_StartApplication_Sets_Properties_On_UPnP_Manager() { _UniversalPlugAndPlayManager.Setup(s => s.Initialise()).Callback(() => { Assert.AreSame(_WebServer.Object, _UniversalPlugAndPlayManager.Object.WebServer); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); } [TestMethod] public void SplashPresenter_StartApplication_Puts_Server_Onto_Internet_If_Configuration_Allows() { _Configuration.WebServerSettings.AutoStartUPnP = true; string currentSection = null; _View.Setup(v => v.ReportProgress(It.IsAny<string>())).Callback((string section) => { currentSection = section; }); _UniversalPlugAndPlayManager.Setup(s => s.PutServerOntoInternet()).Callback(() => { _UniversalPlugAndPlayManager.Verify(m => m.Initialise(), Times.Once()); Assert.AreEqual(Strings.SplashScreenStartingUPnP, currentSection); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _UniversalPlugAndPlayManager.Verify(s => s.PutServerOntoInternet(), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Does_Not_Put_Server_Onto_Internet_If_Configuration_Forbids() { _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _UniversalPlugAndPlayManager.Verify(s => s.PutServerOntoInternet(), Times.Never()); } [TestMethod] public void SplashPresenter_StartApplication_Copies_UPnP_Manager_To_View() { _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); Assert.AreEqual(_UniversalPlugAndPlayManager.Object, _View.Object.UPnpManager); } #endregion #region Plugins [TestMethod] public void SplashPresenter_StartApplication_Calls_Startup_On_All_Loaded_Plugins() { var plugin1 = new Mock<IPlugin>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); var plugin2 = new Mock<IPlugin>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); _PluginManager.Setup(p => p.LoadedPlugins).Returns(new IPlugin[] { plugin1.Object, plugin2.Object }); string currentSection = null; _View.Setup(v => v.ReportProgress(It.IsAny<string>())).Callback((string section) => { currentSection = section; }); plugin1.Setup(p => p.Startup(It.IsAny<PluginStartupParameters>())).Callback(() => { Assert.AreEqual(Strings.SplashScreenStartingPlugins, currentSection); }); plugin2.Setup(p => p.Startup(It.IsAny<PluginStartupParameters>())).Callback(() => { Assert.AreEqual(Strings.SplashScreenStartingPlugins, currentSection); }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); plugin1.Verify(p => p.Startup(It.IsAny<PluginStartupParameters>()), Times.Once()); plugin2.Verify(p => p.Startup(It.IsAny<PluginStartupParameters>()), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Reports_Problems_Starting_A_Plugin_To_User() { var plugin1 = new Mock<IPlugin>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); var plugin2 = new Mock<IPlugin>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); plugin1.Setup(p => p.Name).Returns("P1"); plugin2.Setup(p => p.Name).Returns("P2"); _PluginManager.Setup(p => p.LoadedPlugins).Returns(new IPlugin[] { plugin1.Object, plugin2.Object }); var exception = new InvalidOperationException(); plugin1.Setup(p => p.Startup(It.IsAny<PluginStartupParameters>())).Callback(() => { throw exception; }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); plugin1.Verify(p => p.Startup(It.IsAny<PluginStartupParameters>()), Times.Once()); plugin2.Verify(p => p.Startup(It.IsAny<PluginStartupParameters>()), Times.Once()); _View.Verify(v => v.ReportProblem(String.Format(Strings.PluginThrewExceptionFull, "P1", exception.Message), Strings.PluginThrewExceptionTitle, false), Times.Once()); _View.Verify(v => v.ReportProblem(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()), Times.Once()); _Log.Verify(g => g.WriteLine("Caught exception when starting {0}: {1}", new object[] { "P1", exception.ToString() }), Times.Once()); } [TestMethod] public void SplashPresenter_StartApplication_Sends_Correct_Parameters_To_Plugin_Startup() { var plugin = new Mock<IPlugin>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); _PluginManager.Setup(p => p.LoadedPlugins).Returns(new IPlugin[] { plugin.Object }); PluginStartupParameters parameters = null; // we can't just test within Startup.Callback because exceptions from there are caught by design, they won't stop the test plugin.Setup(p => p.Startup(It.IsAny<PluginStartupParameters>())).Callback((PluginStartupParameters p) => { parameters = p; }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); plugin.Verify(p => p.Startup(It.IsAny<PluginStartupParameters>()), Times.Once()); Assert.AreSame(_BaseStationAircraftList.Object, parameters.AircraftList); Assert.AreSame(_FlightSimulatorXAircraftList.Object, parameters.FlightSimulatorAircraftList); Assert.AreSame(_UniversalPlugAndPlayManager.Object, parameters.UPnpManager); Assert.AreSame(_WebSite.Object, parameters.WebSite); } [TestMethod] public void SplashPresenter_StartApplication_Hooks_ExceptionCaught_For_Plugins_That_Need_To_Raise_Background_Exceptions_On_GUI_Thread() { var plugin = new Mock<IPluginBackgroundThreadCatcher>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); _PluginManager.Setup(p => p.LoadedPlugins).Returns(new IPlugin[] { plugin.Object }); _Presenter.BackgroundThreadExceptionHandler += _BackgroundExceptionEvent.Handler; _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); var exception = new InvalidOperationException(); plugin.Raise(p => p.ExceptionCaught += null, new EventArgs<Exception>(exception)); Assert.AreEqual(1, _BackgroundExceptionEvent.CallCount); Assert.AreSame(exception, _BackgroundExceptionEvent.Args.Value); Assert.AreSame(plugin.Object, _BackgroundExceptionEvent.Sender); } #endregion #endregion } }
wiseman/virtual-radar-server
Test/Test.VirtualRadar.Library/Presenter/SplashPresenterTests.cs
C#
bsd-3-clause
51,096
<div class="row register"> <div class="col-lg-6 col-lg-offset-3 col-sm-6 col-sm-offset-3 col-xs-12 "> <? $form = \yii\bootstrap\ActiveForm::begin([ 'enableClientValidation' => false, 'enableAjaxValidation' => true, ]); ?> <? echo $form->field($model,'username'); ?> <? echo $form->field($model,'email'); ?> <? echo $form->field($model,'password')->passwordInput(); ?> <? echo $form->field($model,'repassword')->passwordInput(); ?> <? echo \yii\helpers\Html::submitButton('Register',['class' => 'btn btn-success']) ?> <? \yii\bootstrap\ActiveForm::end(); ?> </div> </div>
Ilya91/yii
frontend/modules/main/views/main/register.php
PHP
bsd-3-clause
783
function (doc) { function get_date(doc){ switch (doc.doc_type){ case "CommCareCase": case "CommCareCase-Deleted": return doc.opened_on; case "XFormInstance": case "XFormInstance-Deleted": case "XFormError": case "XFormDuplicate": case "XFormDeprecated": case "XFormArchived": case "SubmissionErrorLog": return doc.received_on; case "CommCareUser": case "WebUser": return doc.created_on; case "MessageLog": case "CallLog": case "SMSLog": return doc.date; case "EventLog": return doc.date; case "Application": case "Application-Deleted": case "RemoteApp": case "RemoteApp-Deleted": return doc.copy_of ? doc.built_on : null; default: return null; } } if (doc.domain) { emit([doc.domain, doc.doc_type, get_date(doc)], null); } }
qedsoftware/commcare-hq
corehq/couchapps/by_domain_doc_type_date/views/view/map.js
JavaScript
bsd-3-clause
1,119
/* * Copyright (c) 2009 University of Durham, England 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 name of 'SynergyNet' 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. */ package synergynetframework.appsystem.services.net.networkedcontentmanager.messages; import synergynetframework.appsystem.services.net.localpresence.TableIdentity; import synergynetframework.appsystem.services.net.tablecomms.messages.application.UnicastApplicationMessage; /** * The Class SwapTable. */ public class SwapTable extends UnicastApplicationMessage { /** The Constant serialVersionUID. */ private static final long serialVersionUID = -512349123864227474L; /** The table1. */ private TableIdentity table1; /** The table2. */ private TableIdentity table2; /** * Instantiates a new swap table. * * @param targetClass * the target class * @param table1 * the table1 * @param table2 * the table2 */ public SwapTable(Class<?> targetClass, TableIdentity table1, TableIdentity table2) { super(targetClass); this.table2 = table2; this.setRecipient(table1); } /** * Gets the table1. * * @return the table1 */ public TableIdentity getTable1() { return table1; } /** * Gets the table2. * * @return the table2 */ public TableIdentity getTable2() { return table2; } }
synergynet/synergynet2.5
synergynet2.5/src/main/java/synergynetframework/appsystem/services/net/networkedcontentmanager/messages/SwapTable.java
Java
bsd-3-clause
2,725
/* Copyright (c) 2009-2015, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ namespace El { namespace syrk { template<typename T> inline void LT ( T alpha, const ElementalMatrix<T>& APre, ElementalMatrix<T>& CPre, bool conjugate=false ) { DEBUG_ONLY( CSE cse("syrk::LT"); AssertSameGrids( APre, CPre ); if( APre.Width() != CPre.Height() || APre.Width() != CPre.Width() ) LogicError ("Nonconformal:\n",DimsString(APre,"A"),"\n",DimsString(CPre,"C")) ) const Int r = APre.Height(); const Int bsize = Blocksize(); const Grid& g = APre.Grid(); const Orientation orientation = ( conjugate ? ADJOINT : TRANSPOSE ); DistMatrixReadProxy<T,T,MC,MR> AProx( APre ); DistMatrixReadWriteProxy<T,T,MC,MR> CProx( CPre ); auto& A = AProx.GetLocked(); auto& C = CProx.Get(); // Temporary distributions DistMatrix<T,MR, STAR> A1Trans_MR_STAR(g); DistMatrix<T,STAR,VR > A1_STAR_VR(g); DistMatrix<T,STAR,MC > A1_STAR_MC(g); A1Trans_MR_STAR.AlignWith( C ); A1_STAR_MC.AlignWith( C ); for( Int k=0; k<r; k+=bsize ) { const Int nb = Min(bsize,r-k); auto A1 = A( IR(k,k+nb), ALL ); Transpose( A1, A1Trans_MR_STAR ); Transpose( A1Trans_MR_STAR, A1_STAR_VR ); A1_STAR_MC = A1_STAR_VR; LocalTrrk ( LOWER, orientation, TRANSPOSE, alpha, A1_STAR_MC, A1Trans_MR_STAR, T(1), C ); } } } // namespace syrk } // namespace El
mcopik/Elemental
src/blas_like/level3/Syrk/LT.hpp
C++
bsd-3-clause
1,685
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Main where import System.Remote.Monitoring import Web.Auth.OAuth2 import Web.Auth.Service import Web.Orion import Web.Scotty.Trans import Web.Template import Web.Template.Renderer import Web.Session import Database import Text.Blaze.Html import Text.Blaze.Html5 hiding (param, object, map, b) import qualified Data.Text.Lazy as LT import qualified Data.ByteString.Lazy.Char8 as LB import qualified Data.Map as Map main :: IO () main = do _ <- forkServer "localhost" 9989 orion $ do createUserDatabaseIfNeeded get "/" $ (blaze $ authdWrapper "Home" "Home") `ifAuthorizedOr` (blaze $ wrapper "Home" "Home") get "/authCheck" $ do mU <- readUserCookie blaze $ wrapper "Auth Check" $ do h3 "Auth Check" pre $ toHtml $ show mU get "/user" $ withAuthUser $ \u -> blaze $ authdWrapper "User" $ userTable u get "/error/:err" $ do err <- fmap errorMessage $ param "err" blaze $ wrapper "Error" err get "/login" $ do dest <- defaultParam "redirect" "" (blaze $ authdWrapper "Login" $ loginOptions $ Just dest) `ifAuthorizedOr` (blaze $ wrapper "Login" $ loginOptions $ Just dest) get "/logout" $ do expireUserCookie blaze $ wrapper "Logout" $ p "You have been logged out." get "/login/:service" $ do service <- param "service" let Just key = oauth2serviceKey service url <- prepareServiceLogin service key redirect url get "/login/:service/complete" $ do dest <- popRedirectDestination eUser <- oauthenticate case eUser of Left err -> blaze $ wrapper "OAuth Error" $ do h3 "Authentication Error" p $ toHtml $ LB.unpack err Right u -> do c <- futureCookieForUser u writeUserCookie c redirect dest --get "/link/:service" $ withAuthUser $ \u -> do -- service <- param "service" -- if service `elem` linkedServices u -- then blaze $ wrapper "Link Service" $ do -- h3 "Blarg" -- p "You've already linked that service." -- else do let key = serviceKey service -- baseUrl <- readCfg getCfgBaseUrl -- let call = concat [ baseUrl -- , "/link/" -- , serviceToString service -- , "/complete" -- ] -- call' = B.pack call -- key' = key{oauthCallback= Just call'} -- url <- prepareServiceLogin service key' -- redirect url --get "/link/:service/complete" $ withAuthUser $ \OrionUser{..} -> do -- dest <- popRedirectDestination -- service <- param "service" -- eUdat <- fetchRemoteUserData -- case eUdat of -- Left err -> blaze $ authdWrapper "Link Error" $ do -- h3 $ toHtml $ "Error linking " ++ serviceToString service -- p $ toHtml $ LB.unpack err -- Right udat -> do mUser <- addAccountToUser service _ouId udat -- case mUser of -- Nothing -> blaze $ authdWrapper "Link Error" $ do -- h3 $ toHtml $ "Error linking " ++ serviceToString service -- p $ "Failed to add account." -- Just _ -> redirect dest popRedirectDestination :: ActionOM LT.Text popRedirectDestination = do state <- param "state" states <- readAuthStates modifyAuthStates $ Map.delete state case Map.lookup state states of Nothing -> redirect "error/stateMismatch" Just dest -> return dest
schell/orion
src/Main.hs
Haskell
bsd-3-clause
4,457
#ifndef CMALLOC_CMALLOC_H #define CMALLOC_CMALLOC_H #include <unistd.h> void *cmalloc_aligned_alloc(size_t alignment, size_t size); void *cmalloc_calloc(size_t nmemb, size_t size); void cmalloc_free(void *ptr); void *cmalloc_malloc(size_t size); void *cmalloc_realloc(void *ptr, size_t size); void *cmalloc_memalign(size_t boundary, size_t size); int cmalloc_posix_memalign(void **memptr, size_t alignment, size_t size); void *cmalloc_valloc(size_t size); void *cmalloc_pvalloc(size_t size); /* * parameter_number: * - 0: to change the ratio of cold superblocks to liquid superblocks. 0: freeze most empty(cold) superblocks 100: dont freeze any empty(cold) superblocks less may save more memory * - 1: to change the ratio of frozen superblocks to liquid superblocks.\ 0: return most frozen superblosk to the global pool less may save more memory for more metadata reusing. */ int cmalloc_mallopt(int parameter_number, int parameter_value); void cmalloc_trace(void); #endif // end of CMALLOC_CMALLOC_H
maokelong/cmalloc
sources/includes/cmalloc.h
C
bsd-3-clause
1,048
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/test/simple_test_tick_clock.h" #include "media/cast/cast_defines.h" #include "media/cast/cast_environment.h" #include "media/cast/logging/simple_event_subscriber.h" #include "media/cast/test/fake_single_thread_task_runner.h" #include "media/cast/transport/pacing/mock_paced_packet_sender.h" #include "media/cast/video_receiver/video_receiver.h" #include "testing/gmock/include/gmock/gmock.h" static const int kPacketSize = 1500; static const int64 kStartMillisecond = GG_INT64_C(12345678900000); namespace media { namespace cast { using testing::_; namespace { // Was thread counted thread safe. class TestVideoReceiverCallback : public base::RefCountedThreadSafe<TestVideoReceiverCallback> { public: TestVideoReceiverCallback() : num_called_(0) {} // TODO(mikhal): Set and check expectations. void DecodeComplete(const scoped_refptr<media::VideoFrame>& video_frame, const base::TimeTicks& render_time) { ++num_called_; } void FrameToDecode(scoped_ptr<transport::EncodedVideoFrame> video_frame, const base::TimeTicks& render_time) { EXPECT_TRUE(video_frame->key_frame); EXPECT_EQ(transport::kVp8, video_frame->codec); ++num_called_; } int number_times_called() const { return num_called_; } protected: virtual ~TestVideoReceiverCallback() {} private: friend class base::RefCountedThreadSafe<TestVideoReceiverCallback>; int num_called_; DISALLOW_COPY_AND_ASSIGN(TestVideoReceiverCallback); }; } // namespace class PeerVideoReceiver : public VideoReceiver { public: PeerVideoReceiver(scoped_refptr<CastEnvironment> cast_environment, const VideoReceiverConfig& video_config, transport::PacedPacketSender* const packet_sender, const SetTargetDelayCallback& target_delay_cb) : VideoReceiver(cast_environment, video_config, packet_sender, target_delay_cb) {} using VideoReceiver::IncomingParsedRtpPacket; }; class VideoReceiverTest : public ::testing::Test { protected: VideoReceiverTest() { // Configure to use vp8 software implementation. config_.codec = transport::kVp8; config_.use_external_decoder = false; testing_clock_ = new base::SimpleTestTickClock(); task_runner_ = new test::FakeSingleThreadTaskRunner(testing_clock_); cast_environment_ = new CastEnvironment(scoped_ptr<base::TickClock>(testing_clock_).Pass(), task_runner_, task_runner_, task_runner_, task_runner_, task_runner_, task_runner_, GetLoggingConfigWithRawEventsAndStatsEnabled()); receiver_.reset(new PeerVideoReceiver( cast_environment_, config_, &mock_transport_, target_delay_cb_)); testing_clock_->Advance( base::TimeDelta::FromMilliseconds(kStartMillisecond)); video_receiver_callback_ = new TestVideoReceiverCallback(); payload_.assign(kPacketSize, 0); // Always start with a key frame. rtp_header_.is_key_frame = true; rtp_header_.frame_id = 1234; rtp_header_.packet_id = 0; rtp_header_.max_packet_id = 0; rtp_header_.is_reference = false; rtp_header_.reference_frame_id = 0; rtp_header_.webrtc.header.timestamp = 9000; } virtual ~VideoReceiverTest() {} transport::MockPacedPacketSender mock_transport_; VideoReceiverConfig config_; scoped_ptr<PeerVideoReceiver> receiver_; std::vector<uint8> payload_; RtpCastHeader rtp_header_; base::SimpleTestTickClock* testing_clock_; // Owned by CastEnvironment. scoped_refptr<test::FakeSingleThreadTaskRunner> task_runner_; scoped_refptr<CastEnvironment> cast_environment_; scoped_refptr<TestVideoReceiverCallback> video_receiver_callback_; SetTargetDelayCallback target_delay_cb_; DISALLOW_COPY_AND_ASSIGN(VideoReceiverTest); }; TEST_F(VideoReceiverTest, GetOnePacketEncodedframe) { EXPECT_CALL(mock_transport_, SendRtcpPacket(_)) .WillRepeatedly(testing::Return(true)); receiver_->IncomingParsedRtpPacket( payload_.data(), payload_.size(), rtp_header_); VideoFrameEncodedCallback frame_to_decode_callback = base::Bind( &TestVideoReceiverCallback::FrameToDecode, video_receiver_callback_); receiver_->GetEncodedVideoFrame(frame_to_decode_callback); task_runner_->RunTasks(); EXPECT_EQ(video_receiver_callback_->number_times_called(), 1); } TEST_F(VideoReceiverTest, MultiplePackets) { SimpleEventSubscriber event_subscriber; cast_environment_->Logging()->AddRawEventSubscriber(&event_subscriber); EXPECT_CALL(mock_transport_, SendRtcpPacket(_)) .WillRepeatedly(testing::Return(true)); rtp_header_.max_packet_id = 2; receiver_->IncomingParsedRtpPacket( payload_.data(), payload_.size(), rtp_header_); ++rtp_header_.packet_id; ++rtp_header_.webrtc.header.sequenceNumber; receiver_->IncomingParsedRtpPacket( payload_.data(), payload_.size(), rtp_header_); ++rtp_header_.packet_id; receiver_->IncomingParsedRtpPacket( payload_.data(), payload_.size(), rtp_header_); VideoFrameEncodedCallback frame_to_decode_callback = base::Bind( &TestVideoReceiverCallback::FrameToDecode, video_receiver_callback_); receiver_->GetEncodedVideoFrame(frame_to_decode_callback); task_runner_->RunTasks(); EXPECT_EQ(video_receiver_callback_->number_times_called(), 1); std::vector<FrameEvent> frame_events; event_subscriber.GetFrameEventsAndReset(&frame_events); ASSERT_TRUE(!frame_events.empty()); EXPECT_EQ(kVideoAckSent, frame_events.begin()->type); EXPECT_EQ(rtp_header_.frame_id, frame_events.begin()->frame_id); EXPECT_EQ(rtp_header_.webrtc.header.timestamp, frame_events.begin()->rtp_timestamp); cast_environment_->Logging()->RemoveRawEventSubscriber(&event_subscriber); } TEST_F(VideoReceiverTest, GetOnePacketRawframe) { EXPECT_CALL(mock_transport_, SendRtcpPacket(_)) .WillRepeatedly(testing::Return(true)); receiver_->IncomingParsedRtpPacket( payload_.data(), payload_.size(), rtp_header_); // Decode error - requires legal input. VideoFrameDecodedCallback frame_decoded_callback = base::Bind( &TestVideoReceiverCallback::DecodeComplete, video_receiver_callback_); receiver_->GetRawVideoFrame(frame_decoded_callback); task_runner_->RunTasks(); EXPECT_EQ(video_receiver_callback_->number_times_called(), 0); } // TODO(pwestin): add encoded frames. } // namespace cast } // namespace media
anirudhSK/chromium
media/cast/video_receiver/video_receiver_unittest.cc
C++
bsd-3-clause
6,897
<?php #AUTOGENERATED BY HYBRIDAUTH 2.2.2 INSTALLER - Friday 1st of August 2014 12:35:35 AM /** * HybridAuth * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html */ // ---------------------------------------------------------------------------------------- // HybridAuth Config file: http://hybridauth.sourceforge.net/userguide/Configuration.html // ---------------------------------------------------------------------------------------- return array(/* 'scn-social-auth' => array( "twitterConsumerKey" => "zZI8U5XsIHpgyzKAZNBQZP8NJ", "twitterConsumerSecret" => "jfiTIhTbVC78iQzEV9L0LoCiwG3ycOb3fTDslj4WEnjXmGtbzR", )*/ );
tineo/zendtest
config/autoload/hybridauth.global.php
PHP
bsd-3-clause
788
import pathlib from typing import Optional from cumulusci.core.exceptions import TaskOptionsError from cumulusci.core.utils import process_bool_arg, process_list_arg from cumulusci.salesforce_api.metadata import ApiDeploy from cumulusci.salesforce_api.package_zip import MetadataPackageZipBuilder from cumulusci.tasks.salesforce.BaseSalesforceMetadataApiTask import ( BaseSalesforceMetadataApiTask, ) class Deploy(BaseSalesforceMetadataApiTask): api_class = ApiDeploy task_options = { "path": { "description": "The path to the metadata source to be deployed", "required": True, }, "unmanaged": { "description": "If True, changes namespace_inject to replace tokens with a blank string" }, "namespace_inject": { "description": "If set, the namespace tokens in files and filenames are replaced with the namespace's prefix" }, "namespace_strip": { "description": "If set, all namespace prefixes for the namespace specified are stripped from files and filenames" }, "check_only": { "description": "If True, performs a test deployment (validation) of components without saving the components in the target org" }, "test_level": { "description": "Specifies which tests are run as part of a deployment. Valid values: NoTestRun, RunLocalTests, RunAllTestsInOrg, RunSpecifiedTests." }, "specified_tests": { "description": "Comma-separated list of test classes to run upon deployment. Applies only with test_level set to RunSpecifiedTests." }, "static_resource_path": { "description": "The path where decompressed static resources are stored. Any subdirectories found will be zipped and added to the staticresources directory of the build." }, "namespaced_org": { "description": "If True, the tokens %%%NAMESPACED_ORG%%% and ___NAMESPACED_ORG___ will get replaced with the namespace. The default is false causing those tokens to get stripped and replaced with an empty string. Set this if deploying to a namespaced scratch org or packaging org." }, "clean_meta_xml": { "description": "Defaults to True which strips the <packageVersions/> element from all meta.xml files. The packageVersion element gets added automatically by the target org and is set to whatever version is installed in the org. To disable this, set this option to False" }, } namespaces = {"sf": "http://soap.sforce.com/2006/04/metadata"} def _init_options(self, kwargs): super(Deploy, self)._init_options(kwargs) self.check_only = process_bool_arg(self.options.get("check_only", False)) self.test_level = self.options.get("test_level") if self.test_level and self.test_level not in [ "NoTestRun", "RunLocalTests", "RunAllTestsInOrg", "RunSpecifiedTests", ]: raise TaskOptionsError( f"Specified test run level {self.test_level} is not valid." ) self.specified_tests = process_list_arg(self.options.get("specified_tests", [])) if bool(self.specified_tests) != (self.test_level == "RunSpecifiedTests"): raise TaskOptionsError( "The specified_tests option and test_level RunSpecifiedTests must be used together." ) self.options["namespace_inject"] = ( self.options.get("namespace_inject") or self.project_config.project__package__namespace ) def _get_api(self, path=None): if not path: path = self.options.get("path") package_zip = self._get_package_zip(path) if package_zip is not None: self.logger.info("Payload size: {} bytes".format(len(package_zip))) else: self.logger.warning("Deployment package is empty; skipping deployment.") return return self.api_class( self, package_zip, purge_on_delete=False, check_only=self.check_only, test_level=self.test_level, run_tests=self.specified_tests, ) def _has_namespaced_package(self, ns: Optional[str]) -> bool: if "unmanaged" in self.options: return not process_bool_arg(self.options.get("unmanaged", True)) return bool(ns) and ns in self.org_config.installed_packages def _is_namespaced_org(self, ns: Optional[str]) -> bool: if "namespaced_org" in self.options: return process_bool_arg(self.options.get("namespaced_org", False)) return bool(ns) and ns == self.org_config.namespace def _get_package_zip(self, path): assert path, f"Path should be specified for {self.__class__.name}" if not pathlib.Path(path).exists(): self.logger.warning(f"{path} not found.") return namespace = self.options["namespace_inject"] options = { **self.options, "clean_meta_xml": process_bool_arg( self.options.get("clean_meta_xml", True) ), "namespace_inject": namespace, "unmanaged": not self._has_namespaced_package(namespace), "namespaced_org": self._is_namespaced_org(namespace), } package_zip = MetadataPackageZipBuilder( path=path, options=options, logger=self.logger ) if not package_zip.zf.namelist(): return return package_zip.as_base64() def freeze(self, step): steps = super(Deploy, self).freeze(step) for step in steps: if step["kind"] == "other": step["kind"] = "metadata" return steps
SalesforceFoundation/CumulusCI
cumulusci/tasks/salesforce/Deploy.py
Python
bsd-3-clause
5,848
var searchData= [ ['full_5fscreen',['FULL_SCREEN',['../namespace_comet_engine_1_1_client.html#a608d2e459fd95babca189e50f4182a65ae1a502139199d41bcd8f603a6d579b70',1,'CometEngine::Client']]], ['fullscreen',['FULLSCREEN',['../namespace_comet_engine.html#abdc5ec13bf1dfb1d26eb0bcc9da0ddada5f039f23ee85ddea038ca1ab88ca6755',1,'CometEngine']]] ];
DevSDK/CometEngine
docs/html/search/enumvalues_1.js
JavaScript
bsd-3-clause
345
require 'rubygems' require 'bud' #simple wrapper class for easier clock/msg access class LamportMsg attr_accessor :clock attr_accessor :msg def initialize(clock, msg) @clock = clock @msg = msg end def to_s [@clock, @msg].inspect end def ==(another_msg) self.clock == another_msg.clock && self.msg == another_msg.msg end end #implements handling of Lamport clocks for use in both send/recieve actions #note that even though one can access LamportMessage msg fields without #passing them to retrieve_msg, neglecting to register received messages with the #LamportClockManager will potentially result in incorrect Lamport clock stamps #getting applied to outgoing messages! module LamportInterface state do interface input, :to_stamp, [] => [:msg] interface output, :get_stamped, [:msg] => [:lamportmsg] interface input, :retrieve_msg, [:lamportmsg] => [] interface output, :msg_return, [:lamportmsg] => [:msg] end end module LamportClockManager include LamportInterface state do table :localclock, [] => [:clock] table :action_buf, [] => [:actiontype, :msg, :queuetime] scratch :next_stamp, to_stamp.schema scratch :next_retrieve, retrieve_msg.schema end bootstrap do localclock <= [[0]] end bloom do temp :relativestamp <= to_stamp.each_with_index get_stamped <= (relativestamp * localclock).pairs do |m, c| [m[0][0], LamportMsg.new(m[1]+c.clock, m[0][0])] end msg_return <= retrieve_msg { |r| [r.lamportmsg, r.lamportmsg.msg] } localclock <+- localclock { |c| if retrieve_msg.length > 0 [c.clock+ [to_stamp.length+retrieve_msg.length, (retrieve_msg.map { |m| m.lamportmsg.clock }).max+1].max] else [c.clock+to_stamp.length+retrieve_msg.length] end } end end
bloom-lang/bud-sandbox
ordering/lamport.rb
Ruby
bsd-3-clause
1,844
<?php namespace PlaygroundSocial\Cron\Service; use Zend\ServiceManager\ServiceManagerAwareInterface; use Zend\ServiceManager\ServiceManager; use ZfcBase\EventManager\EventProvider; use PlaygroundSocial\Cron\Cron as CronController; use DateTime; use Zend\Http\Client; use Zend\Http\Request; use Zend\Http\Client\Adapter\Curl; use Zend\Mail\Message as MailMessage; use PlaygroundSocial\Entity\Element as InstagramEntity; use PlaygroundSocial\Entity\Service as ServiceEntity; class Instagram extends EventProvider implements ServiceManagerAwareInterface { /** * @var ServiceManager */ protected $serviceManager; protected $mailTexte = ''; protected $maxId = 0; public function import() { $options = ""; $timeBegin = time(); $filters = array('type' => 'instagram', 'active' => ServiceEntity::SERVICE_ACTIVE); $filters['connectionType'] = ServiceEntity::SERVICE_CONNECTIONTYPE_HASHTAG; $services = $this->getServiceManager()->get('playgroundsocial_service_service')->getServiceMapper()->findBy($filters); $this->log('Imports instagram '.date('d/m/Y H:i:s'), CronController::SUCCESS); $this->mailTexte .= "Imports instagram ".date('d/m/Y H:i:s')." \n"; $nbTweets = 0; foreach ($services as $service) { $this->setService($service); $hashtag = $service->getHashtag(); $lastExecuteds = $this->getServiceManager() ->get('playgroundsocial_element_service') ->getElementMapper() ->findBy(array('service' => $service), array('socialId' => 'DESC')); if (count($lastExecuteds) > 0) { $lastExecuted = $lastExecuteds[0]; $options = "&min_tag_id=".$lastExecuted->getSocialId(); } $config = $this->getServiceManager()->get('Config'); $url = "https://api.instagram.com/v1/tags/".$hashtag."/media/recent?client_id=".$config['instagram_client_id'].$options; $nbTweets = $this->constructTwitterUrl($url, $nbTweets); if ($nbTweets > 0) { $this->log($hashtag.'-'.$service->getId().' : '.$nbTweets.' instagram imported' , CronController::SUCCESS); } else { $this->log($hashtag.'-'.$service->getId().' : '.$nbTweets.' instagram imported' , CronController::WARN); } } $time = time() - $timeBegin; $this->log("Execution time : ".($time).' seconds' , CronController::SUCCESS); $this->mailTexte .= "Execution time : ".($time).' seconds'."\n"; } public function constructTwitterUrl($url, $nbTweets) { $config = array( 'adapter' => 'Zend\Http\Client\Adapter\Curl', 'curloptions' => array(CURLOPT_FOLLOWLOCATION => true), ); $this->log($this->getService()->getHashtag().' new URL : '.$url, CronController::DEBUG); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_COOKIESESSION, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $return = curl_exec($curl); curl_close($curl); $tweets = json_decode($return, true); $nbTweets = $this->addTweet($tweets, $nbTweets); if (!empty($tweets['data']) && !empty($tweets['pagination']['next_url'])) { $nbTweets = $this->constructTwitterUrl($tweets['pagination']['next_url'], $nbTweets); } return $nbTweets; } public function addTweet($tweets, $nbTweets) { if (!empty($tweets['data'])) { foreach ($tweets['data'] as $tweet) { $tweetsExist = $this->getTweetMapper()->findBy(array('service'=>$this->getService(),'socialId' => $tweet['id'])); if (count($tweetsExist) > 0) { $this->log($this->getService()->getHashtag().' - instagram ID : '.$tweet['id'].' don\'t imported : duplicate instagram', CronController::WARN); if ($nbTweets > 0) { $this->log($this->getService()->getHashtag().'-'.$this->getService()->getId().' : '.$nbTweets.' instagram imported' , CronController::SUCCESS); } else { $this->log($this->getService()->getHashtag().'-'.$this->getService()->getId().' : '.$nbTweets.' instagram imported' , CronController::WARN); } exit; } $dateTime = DateTime::createFromFormat('U', $tweet['created_time']); $tweetEntity = new InstagramEntity(); $tweetEntity->setService($this->getService()); $tweetEntity->setSocialId($tweet['id']); $tweetEntity->setAuthor($tweet['user']['username']); $tweetEntity->setTimestamp($dateTime); if(!empty($tweet['images']['standard_resolution'])){ $imageName = $dateTime->format('YmdHis')."_".$tweet['id'].'_'.$tweet['caption']['from']['username'].'.jpg'; $image = file_get_contents($tweet['images']['standard_resolution']['url']); if (!is_dir(__DIR__.'/../../../../../../../public/instagram')) { mkdir(__DIR__.'/../../../../../../../public/instagram'); chmod(__DIR__.'/../../../../../../../public/instagram', 0777); } $path = __DIR__.'/../../../../../../../public/instagram/'.$imageName; file_put_contents($path, $image); chmod($path, 0755); $tweetEntity->setImage("/instagram/".$imageName); $tweetEntity->setSocialImage($tweet['images']['standard_resolution']['url']); } $tweetEntity->setText(utf8_encode($tweet['caption']['text'])); $tweetEntity->setStatus(1); if ($this->getService()->getModerationType() == ServiceEntity::SERVICE_MODERATION_PRIORI) { $tweetEntity->setStatus(0); } //$tweetEntity->setMaxId($tweets['pagination']['next_min_id']); $this->getTweetMapper()->insert($tweetEntity); $nbTweets ++; } } return $nbTweets; } public function getService() { return $this->service; } public function setService($service) { $this->service = $service; return $this; } public function getTweetMapper() { return $this->getServiceManager()->get('playgroundsocial_element_mapper'); } public function log($message, $level) { CronController::log($message, $level); } /** * Retrieve service manager instance * * @return ServiceManager */ public function getServiceManager() { return $this->serviceManager; } /** * Set service manager instance * * @param ServiceManager $serviceManager * @return User */ public function setServiceManager(ServiceManager $serviceManager) { $this->serviceManager = $serviceManager; return $this; } }
AdFabConnect/PlaygroundSocial
src/PlaygroundSocial/Cron/Service/Instagram.php
PHP
bsd-3-clause
7,474
/* ----------------------------------------------------------------- */ /* The Japanese TTS System "Open JTalk" */ /* developed by HTS Working Group */ /* http://open-jtalk.sourceforge.net/ */ /* ----------------------------------------------------------------- */ /* */ /* Copyright (c) 2008-2011 Nagoya Institute of Technology */ /* Department of Computer Science */ /* */ /* 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 name of the HTS working group 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. */ /* ----------------------------------------------------------------- */ #ifndef NJD2JPCOMMON_C #define NJD2JPCOMMON_C #ifdef __cplusplus #define NJD2JPCOMMON_C_START extern "C" { #define NJD2JPCOMMON_C_END } #else #define NJD2JPCOMMON_C_START #define NJD2JPCOMMON_C_END #endif /* __CPLUSPLUS */ NJD2JPCOMMON_C_START; #include <stdio.h> #include <stdlib.h> #include <string.h> #include "njd.h" #include "jpcommon.h" #if defined(CHARSET_EUC_JP) #include "njd2jpcommon_rule_euc_jp.h" #elif defined(CHARSET_SHIFT_JIS) #include "njd2jpcommon_rule_shift_jis.h" #elif defined(CHARSET_UTF_8) #include "njd2jpcommon_rule_utf_8.h" #else #error CHARSET is not specified #endif #define MAXBUFLEN 1024 static void convert_pos(char *buff, char *pos, char *pos_group1, char *pos_group2, char *pos_group3) { int i; for (i = 0; njd2jpcommon_pos_list[i] != NULL; i += 5) { if (strcmp(njd2jpcommon_pos_list[i], pos) == 0 && strcmp(njd2jpcommon_pos_list[i + 1], pos_group1) == 0 && strcmp(njd2jpcommon_pos_list[i + 2], pos_group2) == 0 && strcmp(njd2jpcommon_pos_list[i + 3], pos_group3) == 0) { strcpy(buff, njd2jpcommon_pos_list[i + 4]); return; } } fprintf(stderr, "WARING: convert_pos() in njd2jpcommon.c: %s %s %s %s are not appropriate POS.\n", pos, pos_group1, pos_group2, pos_group3); strcpy(buff, njd2jpcommon_pos_list[4]); } static void convert_ctype(char *buff, char *ctype) { int i; for (i = 0; njd2jpcommon_ctype_list[i] != NULL; i += 2) { if (strcmp(njd2jpcommon_ctype_list[i], ctype) == 0) { strcpy(buff, njd2jpcommon_ctype_list[i + 1]); return; } } fprintf(stderr, "WARING: convert_ctype() in njd2jpcommon.c: %s is not appropriate conjugation type.\n", ctype); strcpy(buff, njd2jpcommon_ctype_list[1]); } static void convert_cform(char *buff, char *cform) { int i; for (i = 0; njd2jpcommon_cform_list[i] != NULL; i += 2) { if (strcmp(njd2jpcommon_cform_list[i], cform) == 0) { strcpy(buff, njd2jpcommon_cform_list[i + 1]); return; } } fprintf(stderr, "WARING: convert_cform() in njd2jpcommon.c: %s is not appropriate conjugation form.\n", cform); strcpy(buff, njd2jpcommon_cform_list[1]); } void njd2jpcommon(JPCommon * jpcommon, NJD * njd) { char buff[MAXBUFLEN]; NJDNode *inode; JPCommonNode *jnode; for (inode = njd->head; inode != NULL; inode = inode->next) { jnode = (JPCommonNode *) calloc(1, sizeof(JPCommonNode)); JPCommonNode_initialize(jnode); JPCommonNode_set_pron(jnode, NJDNode_get_pron(inode)); convert_pos(buff, NJDNode_get_pos(inode), NJDNode_get_pos_group1(inode), NJDNode_get_pos_group2(inode), NJDNode_get_pos_group3(inode)); JPCommonNode_set_pos(jnode, buff); convert_ctype(buff, NJDNode_get_ctype(inode)); JPCommonNode_set_ctype(jnode, buff); convert_cform(buff, NJDNode_get_cform(inode)); JPCommonNode_set_cform(jnode, buff); JPCommonNode_set_acc(jnode, NJDNode_get_acc(inode)); JPCommonNode_set_chain_flag(jnode, NJDNode_get_chain_flag(inode)); JPCommon_push(jpcommon, jnode); } } NJD2JPCOMMON_C_END; #endif /* !NJD2JPCOMMON_C */
STRatANG/MMDAgentExperimentEnvironment
Library_Open_JTalk/src/njd2jpcommon/njd2jpcommon.c
C
bsd-3-clause
6,090
<?php namespace app\models; use Yii; use yii\base\Model; /** * LoginForm is the model behind the login form. */ class LoginForm extends Model { public $email; public $password; public $rememberMe = true; private $_user = false; /** * @return array the validation rules. */ public function rules() { return [ // username and password are both required [['email', 'password'], 'required'], // rememberMe must be a boolean value ['rememberMe', 'boolean'], // password is validated by validatePassword() ['password', 'validatePassword'], ['email', 'email'] ]; } /** * Validates the password. * This method serves as the inline validation for password. * * @param string $attribute the attribute currently being validated * @param array $params the additional name-value pairs given in the rule */ public function validatePassword($attribute, $params) { if (!$this->hasErrors()) { $user = $this->getUser(); if (!$user || !$user->validatePassword($this->password)) { $this->addError($attribute, 'Incorrect username or password.'); } } } /** * Logs in a user using the provided username and password. * @return boolean whether the user is logged in successfully */ public function login() { if ($this->validate()) { return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0); } return false; } /** * Finds user by [[username]] * * @return User|null */ public function getUser() { if ($this->_user === false) { $this->_user = Admin::findByUsername($this->email); } return $this->_user; } }
joalarm/backend_appmovil
models/LoginForm.php
PHP
bsd-3-clause
1,912
# Copyright the Karmabot authors and contributors. # All rights reserved. See AUTHORS. # # This file is part of 'karmabot' and is distributed under the BSD license. # See LICENSE for more details. from karmabot.core.facets import Facet from karmabot.core.commands import CommandSet, thing import random predictions = [ "As I see it, yes", "It is certain", "It is decidedly so", "Most likely", "Outlook good", "Signs point to yes", "Without a doubt", "Yes", "Yes - definitely", "You may rely on it", "Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful"] @thing.facet_classes.register class EightBallFacet(Facet): name = "eightball" commands = thing.add_child(CommandSet(name)) @classmethod def does_attach(cls, thing): return thing.name == "eightball" @commands.add("shake {thing}", help="shake the magic eightball") def shake(self, thing, context): context.reply(random.choice(predictions) + ".")
chromakode/karmabot
karmabot/extensions/eightball.py
Python
bsd-3-clause
1,155
<?php use yii\helpers\Html; use yii\helpers\Url; use kartik\widgets\ActiveForm; use kartik\switchinput\SwitchInput; use kartik\widgets\DatePicker; use kartik\select2\Select2; use yii\helpers\ArrayHelper; use kartik\widgets\FileInput; ?> <?php $form = kartik\widgets\ActiveForm::begin([ 'id' => 'form-horizontal', 'type' => ActiveForm::TYPE_HORIZONTAL, 'fullSpan' => 7, 'formConfig' => ['labelSpan' => 3, 'deviceSize' => ActiveForm::SIZE_MEDIUM], 'options' => ['enctype' => 'multipart/form-data'], ]); ?> <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'code')->textInput(['maxlength' => true]) ?> <div class="row" style="margin:20px;"> <div class="col-md-offset-3"> <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> </div> <?php ActiveForm::end(); ?>
bokko79/servicemapp
backend/views/languages/_form.php
PHP
bsd-3-clause
986
/** @file * * @ingroup dspSpatLib * * @brief Host a SpatLib object * * @details * * @authors Trond Lossius, Nils Peters, Timothy Place * * @copyright Copyright © 2011 by Trond Lossius, Nils Peters, and Timothy Place @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTSpat.h" #define thisTTClass TTSpat #define thisTTClassName "spat" #define thisTTClassTags "audio, spatialization" TT_AUDIO_CONSTRUCTOR, mSpatFunctionObject(NULL), mSourceCount(0), mDestinationCount(0) { //TTValue v; addAttributeWithSetter(SpatFunction, kTypeSymbol); addAttributeWithSetter(SourceCount, kTypeUInt16); addAttributeWithSetter(DestinationCount, kTypeUInt16); addAttributeWithGetterAndSetter(SourcePositions, kTypeFloat64); addAttributeWithGetterAndSetter(DestinationPositions, kTypeFloat64); addMessageWithArguments(getSpatFunctions); addMessageWithArguments(getFunctionParameters); addMessageWithArguments(getFunctionParameter); addMessageWithArguments(setFunctionParameter); //addUpdate(MaxNumChannels); setAttributeValue(TT("spatFunction"), TT("spat.thru")); setAttributeValue(TT("sourceCount"), 2); setAttributeValue(TT("destinationCount"), 8); setProcessMethod(process); } TTSpat::~TTSpat() { delete mSpatFunctionObject; } TTErr TTSpat::setSpatFunction(const TTValue& aSpatFunction) { TTErr err; TTSymbol spatFunctionName; TTAudioObjectPtr spatFunction = NULL; aSpatFunction.get(0, spatFunctionName); // if the function didn't change, then don't change the function if (spatFunctionName == mSpatFunction) return kTTErrNone; // TTObjectInstantiate will automatically free the object passed into it err = TTObjectInstantiate(spatFunctionName, &spatFunction, kTTValNONE); if (!err && spatFunction) { // Now set the state of the object to the state we have stored spatFunction->setAttributeValue(TT("sourceCount"), mSourceCount); spatFunction->setAttributeValue(TT("destinationCount"), mDestinationCount); spatFunction->setAttributeValue(TT("sourcePositions"), mSourcePositions); spatFunction->setAttributeValue(TT("destinationPositions"), mDestinationPositions); mSpatFunction = spatFunctionName; mSpatFunctionObject = spatFunction; // FIXME: This is not thread safe if the audio is running // We need to queue this switch to occur at a time when it is safe // (when audio is not processed by the old object any longer) // Redmine #994 // // ACTUALLY: it should be okay because of the locks in the TTObjectInstantiate spinlocking to wait // for any process calls. // However, maybe those need some improvements like using volatile or atomic types } else { // some problems have occurred, not yet sure how we should handle this... } return err; } TTErr TTSpat::getSpatFunctions(const TTValue&, TTValue& listOfSpatFunctionsToReturn) { TTValue v; v.setSize(2); v.set(0, TT("spatialization")); v.set(1, TT("processing")); // more efficent than append return TTGetRegisteredClassNamesForTags(listOfSpatFunctionsToReturn, v); } TTErr TTSpat::getFunctionParameters(const TTValue&, TTValue& aListOfParameterNamesToReturn) { mSpatFunctionObject->getAttributeNames(aListOfParameterNamesToReturn); return kTTErrNone; } TTErr TTSpat::getFunctionParameter(const TTValue& aParameterNameIn, TTValue& aValueOut) { TTSymbol parameterName; aParameterNameIn.get(0, parameterName); return mSpatFunctionObject->getAttributeValue(parameterName, aValueOut); } TTErr TTSpat::setFunctionParameter(const TTValue& aParameterNameAndValue, TTValue&) { TTSymbol parameterName; TTValue parameterValue; aParameterNameAndValue.get(0, parameterName); parameterValue.copyFrom(aParameterNameAndValue, 1); //TODO: maybe there are more arguments ? //aParameterNameAndValue.clear(); // only needed so that we don't return a value return mSpatFunctionObject->setAttributeValue(parameterName, parameterValue); } TTErr TTSpat::setSourceCount(const TTValue& aSourceCount) { mSourceCount = aSourceCount; return mSpatFunctionObject->setAttributeValue(TT("sourceCount"), (TTValue&)aSourceCount); } TTErr TTSpat::setDestinationCount(const TTValue& aDestinationCount) { mDestinationCount = aDestinationCount; return mSpatFunctionObject->setAttributeValue(TT("destinationCount"), (TTValue&)aDestinationCount); } TTErr TTSpat::setSourcePositions(const TTValue& newSourcePositions) { // newSourcePositions is an array of 3N values specified in x/y/z triplets mSourcePositions = newSourcePositions; return mSpatFunctionObject->setAttributeValue(TT("sourcePositions"), (TTValue&)newSourcePositions); } TTErr TTSpat::getSourcePositions(TTValue& returnedSourcePositions) { // newSourcePositions is an array of 3N values specified in x/y/z triplets returnedSourcePositions = mSourcePositions; return kTTErrNone; } TTErr TTSpat::setDestinationPositions(const TTValue& newDestinationPositions) { mDestinationPositions = newDestinationPositions; return mSpatFunctionObject->setAttributeValue(TT("destinationPositions"), (TTValue&)newDestinationPositions); } TTErr TTSpat::getDestinationPositions(TTValue& returnedDestinationPositions) { returnedDestinationPositions = mDestinationPositions; return kTTErrNone; } #if 0 #pragma mark - #pragma mark Process Routines #endif TTErr TTSpat::process(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs) { return mSpatFunctionObject->process(inputs, outputs); }
RWelsh/JamomaDSP
extensions/SpatLib/TTSpat.cpp
C++
bsd-3-clause
5,518
// // ActiveStarter.h // // $Id$ // // Library: Foundation // Package: Threading // Module: ActiveObjects // // Definition of the ActiveStarter class. // // Copyright (c) 2006-2007, Applied Informatics Software Engineering GmbH. // and Contributors. // // 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. // #ifndef Foundation_ActiveStarter_INCLUDED #define Foundation_ActiveStarter_INCLUDED #include "Poco/Foundation.h" #include "Poco/ThreadPool.h" #include "Poco/ActiveRunnable.h" namespace Poco { template <class OwnerType> class ActiveStarter /// The default implementation of the StarterType /// policy for ActiveMethod. It starts the method /// in its own thread, obtained from the default /// thread pool. { public: static void start(OwnerType* pOwner, ActiveRunnableBase::Ptr pRunnable) { ThreadPool::defaultPool().start(*pRunnable); pRunnable->duplicate(); // The runnable will release itself. } }; } // namespace Poco #endif // Foundation_ActiveStarter_INCLUDED
nocnokneo/MITK
Utilities/Poco/Foundation/include/Poco/ActiveStarter.h
C
bsd-3-clause
2,288
/********************************************************** Date: OCT 28th, 2006 Project : NET4900 Project: tftpd.c TFTP Server Programers: Craig Holmes Reza Rahmanian File: TFTP Server (main) Purpose: A TFTP server that will accept a connections from a client and transefet files. Notes: Here we are using the sendto and recvfrom functions so the server and client can exchange data. In order to execute correctly this source code you may have to run as sudo. ***********************************************************************/ /* Include our header which contains libaries and defines */ #include "tftp.h" /* Function prototypes */ void tsend (char *, struct sockaddr_in, char *, int); void tget (char *, struct sockaddr_in, char *, int); int isnotvaliddir (char *); void usage (void); /* default values which can be controlled by command line */ int debug = 0; char path[70] = "/tmp/"; int port = 69; unsigned short int ackfreq = 1; int datasize = 512; int main (int argc, char **argv) { /*local variables */ extern char *optarg; int sock, n, client_len, pid, status, opt, tid; char opcode, *bufindex, filename[200], mode[12]; struct sockaddr_in server, client; /*the address structure for both the server and client */ /* All of the following deals with command line switches */ while ((opt = getopt (argc, argv, "dh:p:P:a:s:")) != -1) /* this function is handy */ { switch (opt) { case 'p': /* path (opt required) */ if (!isnotvaliddir (optarg)) { printf ("Sorry, you specified an invalid/non-existant directory. Make sure the directory exists.\n"); return 0; } strncpy (path, optarg, sizeof (path) - 1); break; case 'd': /* debug mode (no opts) */ debug = 1; break; case 'P': /* Port (opt required) */ port = atoi (optarg); break; case 'a': /* ack frequency (opt required) */ ackfreq = atoi (optarg); if (ackfreq > MAXACKFREQ) { printf ("Sorry, you specified an ack frequency higher than the maximum allowed (Requested: %d Max: %d)\n", ackfreq, MAXACKFREQ); return 0; } else if (ackfreq == 0) { printf ("Sorry, you have to ack sometime.\n"); return 0; } break; case 's': /* File chunk size (opt required) */ datasize = atoi (optarg); if (datasize > MAXDATASIZE) { printf ("Sorry, you specified a data size higher than the maximum allowed (Requested: %d Max: %d)\n", datasize, MAXDATASIZE); return 0; } break; case 'h': /* Help (no opts) */ usage (); return (0); break; default: /* everything else */ usage (); return (0); break; } } /* Done dealing with switches */ /*Create the socket, a -1 will show us an error */ if ((sock = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { printf ("Server Socket could not be created"); return 0; } /*set the address values for the server */ server.sin_family = AF_INET; /*address family for TCP and UDP */ server.sin_addr.s_addr = inet_addr ("192.168.3.24"); /*use any address */ server.sin_port = htons (port); /*pick a free port */ /*Bind the socket */ if (bind (sock, (struct sockaddr *) &server, sizeof (server)) < 0) { printf ("Server bind failed. Server already running? Proper permissions?\n"); return (2); } if (!debug) { pid = fork (); if (pid != 0) /* if pid != 0 then we are the parent */ { if (pid == -1) { printf ("Error: Fork failed!\n"); return 0; } else { printf ("Daemon Successfully forked (pid: %d)\n", pid); return 1; } } } else { printf ("tftpd server is running in debug mode and will not fork. \nMulti-threaded mode disabled.\nServer is bound to port %d and awaiting connections\nfile path: %s\n", ntohs (server.sin_port), path); } /*endless loop to get connections from the client */ while (1) { client_len = sizeof (client); /*get the length of the client */ memset (buf, 0, BUFSIZ); /*clear the buffer */ /*the fs message */ n = 0; while (errno == EAGAIN || n == 0) /* This loop is required because on linux we have to acknowledge complete children with waitpid. Ugh. */ { waitpid (-1, &status, WNOHANG); n = recvfrom (sock, buf, BUFSIZ, MSG_DONTWAIT, (struct sockaddr *) &client, (socklen_t *) & client_len); if (n < 0 && errno != EAGAIN) { printf ("The server could not receive from the client"); return 0; } usleep (1000); } if (debug) printf ("Connection from %s, port %d\n", inet_ntoa (client.sin_addr), ntohs (client.sin_port)); bufindex = buf; //start our pointer going if (bufindex++[0] != 0x00) { //first TFTP packet byte needs to be null. Once the value is taken increment it. if (debug) printf ("Malformed tftp packet.\n"); return 0; } tid = ntohs (client.sin_port); /* record the tid */ opcode = *bufindex++; //opcode is in the second byte. if (opcode == 1 || opcode == 2) // RRQ or WRQ. The only two really valid packets on port 69 { strncpy (filename, bufindex, sizeof (filename) - 1); /* Our pointer has been nudged along the recieved string so the first char is the beginning of the filename. This filename is null deliimited so we can use the str family of functions */ bufindex += strlen (filename) + 1; /* move the pointer to after the filename + null byte in the string */ strncpy (mode, bufindex, sizeof (mode) - 1); /* like the filename, we are at the beginning of the null delimited mode */ bufindex += strlen (mode) + 1; /* move pointer... */ if (debug) printf ("opcode: %x filename: %s packet size: %d mode: %s\n", opcode, filename, n, mode); /*show the message to the server */ } else { if (debug) printf ("opcode: %x size: %d \n", opcode, sizeof (n)); /*show the message to the server */ } switch (opcode) /* case one and two are valid on port 69 or server port... no other codes are */ { case 1: if (debug) { printf ("Opcode indicates file read request\n"); tsend (filename, client, mode, tid); } else { pid = fork (); if (pid == 0) { /* if we are pid != 0 then we are the parent */ tsend (filename, client, mode, tid); exit (1); } } break; case 2: if (debug) { printf ("Opcode indicates file write request\n"); tget (filename, client, mode, tid); } else { pid = fork (); if (pid == 0) /* if we are pid != 0 then we are the parent */ { tget (filename, client, mode, tid); exit (1); } } break; default: if (debug) printf ("Invalid opcode detected. Ignoring packet."); break; } //end of while } } void tget (char *pFilename, struct sockaddr_in client, char *pMode, int tid) { /* local variables */ int sock, len, client_len, opcode, i, j, n, flag = 1; unsigned short int count = 0, rcount = 0; unsigned char filebuf[MAXDATASIZE + 1]; unsigned char packetbuf[MAXDATASIZE + 12]; extern int errno; char filename[128], mode[12], fullpath[200], *bufindex, ackbuf[512], filename_bulk[128]; struct sockaddr_in data; FILE *fp; /* pointer to the file we will be getting */ strcpy (filename, pFilename); //copy the pointer to the filename into a real array strcpy (mode, pMode); //same as above if (debug) printf ("branched to file receive function\n"); if ((sock = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) //startup a socket { printf ("Server reconnect for getting did not work correctly\n"); return; } if (!strncasecmp (mode, "octet", 5) && !strncasecmp (mode, "netascii", 8)) /* these two are the only modes we accept */ { if (!strncasecmp (mode, "mail", 4)) len = sprintf ((char *) packetbuf, "%c%c%c%cThis tftp server will not operate as a mail relay%c", 0x00, 0x05, 0x00, 0x04, 0x00); else len = sprintf ((char *) packetbuf, "%c%c%c%cUnrecognized mode (%s)%c", 0x00, 0x05, 0x00, 0x04, mode, 0x00); if (sendto (sock, packetbuf, len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */ { printf ("Mismatch in number of sent bytes while trying to send mode error packet\n"); } return; } if(filename[0]=='/') { //Il nuovo file name sarà uguale a quello vecchio eccetto il carattere backslash iniziale. strncpy(filename, filename +1,127); printf("new name file: %s\n",filename); } if (strchr (filename, 0x5C) || strchr (filename, 0x2F)) //look for illegal characters in the filename string these are \ and / { if (debug) printf ("Client requested to upload bad file: forbidden name\n"); len = sprintf ((char *) packetbuf, "%c%c%c%cIllegal filename.(%s) You may not attempt to descend or ascend directories.%c", 0x00, 0x05, 0x00, 0x00, filename, 0x00); if (sendto (sock, packetbuf, len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */ { printf ("Mismatch in number of sent bytes while trying to send error packet\n"); } return; } strcpy (fullpath, path); printf("Size of full path is %d\n",strlen(fullpath)); if(debug){ printf("AAAAAAAAAAAAAAAA Full Path plus filename is %s\n",fullpath); } strncat (fullpath, filename, sizeof (fullpath) - 1); //build the full file path by appending filename to path if(debug){ printf("BBBBBBBBBBBBBB Full Path plus filename is %s\n",fullpath); } fp = fopen (fullpath, "w"); /* open the file for writing */ if (fp == NULL) { //if the pointer is null then the file can't be opened - Bad perms if (debug) printf ("Server requested bad file: cannot open for writing (%s)\n", fullpath); len = sprintf ((char *) packetbuf, "%c%c%c%cFile cannot be opened for writing (%s)%c", 0x00, 0x05, 0x00, 0x02, fullpath, 0x00); if (sendto (sock, packetbuf, len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */ { printf ("Mismatch in number of sent bytes while trying to send error packet\n"); } return; } else /* everything worked fine */ { if (debug) printf ("Getting file... (destination: %s) \n", fullpath); } /* zero the buffer before we begin */ memset (filebuf, 0, sizeof (filebuf)); n = datasize + 4; do { /* zero buffers so if there are any errors only NULLs will be exposed */ memset (packetbuf, 0, sizeof (packetbuf)); memset (ackbuf, 0, sizeof (ackbuf)); if (debug) printf ("== just entered do-while count: %d n: %d\n", count, n); if (count == 0 || (count % ackfreq) == 0 || n != (datasize + 4)) /* ack the first packet, count % ackfreq will make it so we only ACK everyone ackfreq ACKs, ack the last packet */ { len = sprintf (ackbuf, "%c%c%c%c", 0x00, 0x04, 0x00, 0x00); ackbuf[2] = (count & 0xFF00) >> 8; //fill in the count (top number first) ackbuf[3] = (count & 0x00FF); //fill in the lower part of the count if (debug) printf ("Sending ack # %04d (length: %d)\n", count, len); if (sendto (sock, ackbuf, len, 0, (struct sockaddr *) &client, sizeof (client)) != len) { if (debug) printf ("Mismatch in number of sent bytes\n"); return; } } else if (debug) { printf ("No ack required on packet count %d\n", count); } if (n != (datasize + 4)) /* remember if our datasize is less than a full packet this was the last packet to be received */ { if (debug) printf ("Last chunk detected (file chunk size: %d). exiting while loop\n", n - 4); goto done; /* gotos are not optimal, but a good solution when exiting a multi-layer loop */ } memset (filebuf, 0, sizeof (filebuf)); count++; for (j = 0; j < RETRIES; j++) /* this allows us to loop until we either break out by getting the correct ack OR time out because we've looped more than RETRIES times */ { client_len = sizeof (data); errno = EAGAIN; /* this allows us to enter the loop */ n = -1; for (i = 0; errno == EAGAIN && i <= TIMEOUT && n < 0; i++) /* this for loop will just keep checking the non-blocking socket until timeout */ { n = recvfrom (sock, packetbuf, sizeof (packetbuf) - 1, MSG_DONTWAIT, (struct sockaddr *) &data, (socklen_t *) & client_len); /*if (debug) printf ("The value recieved is n: %d\n",n); */ usleep (1000); } if (n < 0 && errno != EAGAIN) /* this will be true when there is an error that isn't the WOULD BLOCK error */ { if (debug) printf ("The server could not receive from the client (errno: %d n: %d)\n", errno, n); //resend packet } else if (n < 0 && errno == EAGAIN) /* this is true when the error IS would block. This means we timed out */ { if (debug) printf ("Timeout waiting for data (errno: %d == %d n: %d)\n", errno, EAGAIN, n); //resend packet } else { if (client.sin_addr.s_addr != data.sin_addr.s_addr) /* checks to ensure get from ip is same from ACK IP */ { if (debug) printf ("Error recieving file (data from invalid address)\n"); j--; continue; /* we aren't going to let another connection spoil our first connection */ } if (tid != ntohs (client.sin_port)) /* checks to ensure get from the correct TID */ { if (debug) printf ("Error recieving file (data from invalid tid)\n"); len = sprintf ((char *) packetbuf, "%c%c%c%cBad/Unknown TID%c", 0x00, 0x05, 0x00, 0x05, 0x00); if (sendto (sock, packetbuf, len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */ { printf ("Mismatch in number of sent bytes while trying to send mode error packet\n"); } j--; continue; /* we aren't going to let another connection spoil our first connection */ } /* this formatting code is just like the code in the main function */ bufindex = (char *) packetbuf; //start our pointer going if (bufindex++[0] != 0x00) printf ("bad first nullbyte!\n"); opcode = *bufindex++; rcount = *bufindex++ << 8; rcount &= 0xff00; rcount += (*bufindex++ & 0x00ff); memcpy ((char *) filebuf, bufindex, n - 4); /* copy the rest of the packet (data portion) into our data array */ if (debug) printf ("Remote host sent data packet #%d (Opcode: %d packetsize: %d filechunksize: %d)\n", rcount, opcode, n, n - 4); if (flag) { if (n > 516) datasize = n - 4; flag = 0; } if (opcode != 3 || rcount != count) /* ack packet should have code 3 (data) and should be ack+1 the packet we just sent */ { if (debug) printf ("Badly ordered/invalid data packet (Got OP: %d Block: %d) (Wanted Op: 3 Block: %d)\n", opcode, rcount, count); /* sending error message */ if (opcode > 5) { len = sprintf ((char *) packetbuf, "%c%c%c%cIllegal operation%c", 0x00, 0x05, 0x00, 0x04, 0x00); if (sendto (sock, packetbuf, len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */ { printf ("Mismatch in number of sent bytes while trying to send mode error packet\n"); } } } else { break; } } if (sendto (sock, ackbuf, len, 0, (struct sockaddr *) &client, sizeof (client)) != len) { if (debug) printf ("Mismatch in number of sent bytes\n"); return; } } if (j == RETRIES) { if (debug) printf ("Data recieve Timeout. Aborting transfer\n"); fclose (fp); return; } } while (fwrite (filebuf, 1, n - 4, fp) == n - 4); /* if it doesn't write the file the length of the packet received less 4 then it didn't work */ fclose (fp); sync (); if (debug) printf ("fclose and sync successful. File failed to recieve properly\n"); return; done: fclose (fp); sync (); if (debug) printf ("fclose and sync successful. File received successfully\n"); return; } void tsend (char *pFilename, struct sockaddr_in client, char *pMode, int tid) { int sock, len, client_len, opcode, ssize = 0, n, i, j, bcount = 0; unsigned short int count = 0, rcount = 0, acked = 0; unsigned char filebuf[MAXDATASIZE + 1]; unsigned char packetbuf[MAXACKFREQ][MAXDATASIZE + 12], recvbuf[MAXDATASIZE + 12]; char filename[128], mode[12], fullpath[200], *bufindex; struct sockaddr_in ack; FILE *fp; /* pointer to the file we will be sending */ strcpy (filename, pFilename); //copy the pointer to the filename into a real array strcpy (mode, pMode); //same as above if (debug) printf ("branched to file send function\n"); if ((sock = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) //startup a socket { printf ("Server reconnect for sending did not work correctly\n"); return; } if (!strncasecmp (mode, "octet", 5) && !strncasecmp (mode, "netascii", 8)) /* these two are the only modes we accept */ { if (!strncasecmp (mode, "mail", 4)) len = sprintf ((char *) packetbuf[0], "%c%c%c%cThis tftp server will not operate as a mail relay%c", 0x00, 0x05, 0x00, 0x04, 0x00); else len = sprintf ((char *) packetbuf[0], "%c%c%c%cUnrecognized mode (%s)%c", 0x00, 0x05, 0x00, 0x04, mode, 0x00); if (sendto (sock, packetbuf[0], len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */ { printf ("Mismatch in number of sent bytes while trying to send mode error packet\n"); } return; } if (strchr (filename, 0x5C) || strchr (filename, 0x2F)) //look for illegal characters in the filename string these are \ and / { if (debug) printf ("Server requested bad file: forbidden name\n"); len = sprintf ((char *) packetbuf[0], "%c%c%c%cIllegal filename.(%s) You may not attempt to descend or ascend directories.%c", 0x00, 0x05, 0x00, 0x00, filename, 0x00); if (sendto (sock, packetbuf[0], len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */ { printf ("Mismatch in number of sent bytes while trying to send error packet\n"); } return; } strcpy (fullpath, path); strncat (fullpath, filename, sizeof (fullpath) - 1); //build the full file path by appending filename to path fp = fopen (fullpath, "r"); if (fp == NULL) { //if the pointer is null then the file can't be opened - Bad perms OR no such file if (debug) printf ("Server requested bad file: file not found (%s)\n", fullpath); len = sprintf ((char *) packetbuf[0], "%c%c%c%cFile not found (%s)%c", 0x00, 0x05, 0x00, 0x01, fullpath, 0x00); if (sendto (sock, packetbuf[0], len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */ { printf ("Mismatch in number of sent bytes while trying to send error packet\n"); } return; } else { if (debug) printf ("Sending file... (source: %s)\n", fullpath); } memset (filebuf, 0, sizeof (filebuf)); while (1) /* our break statement will escape us when we are done */ { acked = 0; ssize = fread (filebuf, 1, datasize, fp); count++; /* count number of datasize byte portions we read from the file */ if (count == 1) /* we always look for an ack on the FIRST packet */ bcount = 0; else if (count == 2) /* The second packet will always start our counter at zreo. This special case needs to exist to avoid a DBZ when count = 2 - 2 = 0 */ bcount = 0; else bcount = (count - 2) % ackfreq; sprintf ((char *) packetbuf[bcount], "%c%c%c%c", 0x00, 0x03, 0x00, 0x00); /* build data packet but write out the count as zero */ memcpy ((char *) packetbuf[bcount] + 4, filebuf, ssize); len = 4 + ssize; packetbuf[bcount][2] = (count & 0xFF00) >> 8; //fill in the count (top number first) packetbuf[bcount][3] = (count & 0x00FF); //fill in the lower part of the count if (debug) printf ("Sending packet # %04d (length: %d file chunk: %d)\n", count, len, ssize); if (sendto (sock, packetbuf[bcount], len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */ { if (debug) printf ("Mismatch in number of sent bytes\n"); return; } if ((count - 1) == 0 || ((count - 1) % ackfreq) == 0 || ssize != datasize) { /* The following 'for' loop is used to recieve/timeout ACKs */ for (j = 0; j < RETRIES; j++) { client_len = sizeof (ack); errno = EAGAIN; n = -1; for (i = 0; errno == EAGAIN && i <= TIMEOUT && n < 0; i++) { n = recvfrom (sock, recvbuf, sizeof (recvbuf), MSG_DONTWAIT, (struct sockaddr *) &ack, (socklen_t *) & client_len); usleep (1000); } if (n < 0 && errno != EAGAIN) { if (debug) printf ("The server could not receive from the client (errno: %d n: %d)\n", errno, n); //resend packet } else if (n < 0 && errno == EAGAIN) { if (debug) printf ("Timeout waiting for ack (errno: %d n: %d)\n", errno, n); //resend packet } else { if (client.sin_addr.s_addr != ack.sin_addr.s_addr) /* checks to ensure send to ip is same from ACK IP */ { if (debug) printf ("Error recieving ACK (ACK from invalid address)\n"); j--; /* in this case someone else connected to our port. Ignore this fact and retry getting the ack */ continue; } if (tid != ntohs (client.sin_port)) /* checks to ensure get from the correct TID */ { if (debug) printf ("Error recieving file (data from invalid tid)\n"); len = sprintf ((char *) recvbuf, "%c%c%c%cBad/Unknown TID%c", 0x00, 0x05, 0x00, 0x05, 0x00); if (sendto (sock, recvbuf, len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */ { printf ("Mismatch in number of sent bytes while trying to send mode error packet\n"); } j--; continue; /* we aren't going to let another connection spoil our first connection */ } /* this formatting code is just like the code in the main function */ bufindex = (char *) recvbuf; //start our pointer going if (bufindex++[0] != 0x00) printf ("bad first nullbyte!\n"); opcode = *bufindex++; rcount = *bufindex++ << 8; rcount &= 0xff00; rcount += (*bufindex++ & 0x00ff); if (opcode != 4 || rcount != count) /* ack packet should have code 4 (ack) and should be acking the packet we just sent */ { if (debug) printf ("Remote host failed to ACK proper data packet # %d (got OP: %d Block: %d)\n", count, opcode, rcount); /* sending error message */ if (opcode > 5) { len = sprintf ((char *) recvbuf, "%c%c%c%cIllegal operation%c", 0x00, 0x05, 0x00, 0x04, 0x00); if (sendto (sock, recvbuf, len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* send the data packet */ { printf ("Mismatch in number of sent bytes while trying to send mode error packet\n"); } } /* from here we will loop back and resend */ } else { if (debug) printf ("Remote host successfully ACK'd (#%d)\n", rcount); break; } } for (i = 0; i <= bcount; i++) { if (sendto (sock, packetbuf[i], len, 0, (struct sockaddr *) &client, sizeof (client)) != len) /* resend the data packet */ { if (debug) printf ("Mismatch in number of sent bytes\n"); return; } if (debug) printf ("Ack(s) lost. Resending: %d\n", count - bcount + i); } if (debug) printf ("Ack(s) lost. Resending complete.\n"); } /* The ack sending 'for' loop ends here */ } else if (debug) { printf ("Not attempting to recieve ack. Not required. count: %d\n", count); n = recvfrom (sock, recvbuf, sizeof (recvbuf), MSG_DONTWAIT, (struct sockaddr *) &ack, (socklen_t *) & client_len); /* just do a quick check incase the remote host is trying with ackfreq = 1 */ } if (j == RETRIES) { if (debug) printf ("Ack Timeout. Aborting transfer\n"); fclose (fp); return; } if (ssize != datasize) break; memset (filebuf, 0, sizeof (filebuf)); /* fill the filebuf with zeros so that when the fread fills it, it is a null terminated string */ } fclose (fp); if (debug) printf ("File sent successfully\n"); return; } int isnotvaliddir (char *pPath) /* this function just makes sure that the directory passed to the server is valid and adds a trailing slash if not present */ { DIR *dp; int len; dp = opendir (pPath); if (dp == NULL) { return (0); } else { len = strlen (pPath); closedir (dp); if (pPath[len - 1] != '/') { pPath[len] = '/'; pPath[len + 1] = 0; } return (1); } } void usage (void) /* prints program usage */ { printf ("Usage: tftpd [options] [path]\nOptions:\n-d (debug mode)\n-h (help; this message)\n-P <port>\n-a <ack freqency. Default 1>\n-s <data chunk size in bytes. Default 512>\n"); return; }
PP90/ANAWS-project-on-Traffic-Engineering
Old_project/tftp-1.0/tftpd.c
C
bsd-3-clause
25,542
/*- * Copyright (C) 2012-2013 Intel Corporation * All rights reserved. * * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 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. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: releng/9.3/sys/dev/nvme/nvme_test.c 257588 2013-11-03 20:52:13Z jimharris $"); #include <sys/param.h> #include <sys/bio.h> #include <sys/conf.h> #include <sys/fcntl.h> #include <sys/kthread.h> #include <sys/module.h> #include <sys/proc.h> #include <sys/syscallsubr.h> #include <sys/sysctl.h> #include <sys/sysproto.h> #include <sys/systm.h> #include <sys/unistd.h> #include <geom/geom.h> #include "nvme_private.h" struct nvme_io_test_thread { uint32_t idx; struct nvme_namespace *ns; enum nvme_nvm_opcode opc; struct timeval start; void *buf; uint32_t size; uint32_t time; uint64_t io_completed; }; struct nvme_io_test_internal { struct nvme_namespace *ns; enum nvme_nvm_opcode opc; struct timeval start; uint32_t time; uint32_t size; uint32_t td_active; uint32_t td_idx; uint32_t flags; uint64_t io_completed[NVME_TEST_MAX_THREADS]; }; static void nvme_ns_bio_test_cb(struct bio *bio) { struct mtx *mtx; mtx = mtx_pool_find(mtxpool_sleep, bio); mtx_lock(mtx); wakeup(bio); mtx_unlock(mtx); } static void nvme_ns_bio_test(void *arg) { struct nvme_io_test_internal *io_test = arg; struct cdevsw *csw; struct mtx *mtx; struct bio *bio; struct cdev *dev; void *buf; struct timeval t; uint64_t io_completed = 0, offset; uint32_t idx; #if __FreeBSD_version >= 900017 int ref; #endif buf = malloc(io_test->size, M_NVME, M_WAITOK); idx = atomic_fetchadd_int(&io_test->td_idx, 1); dev = io_test->ns->cdev; offset = idx * 2048 * nvme_ns_get_sector_size(io_test->ns); while (1) { bio = g_alloc_bio(); memset(bio, 0, sizeof(*bio)); bio->bio_cmd = (io_test->opc == NVME_OPC_READ) ? BIO_READ : BIO_WRITE; bio->bio_done = nvme_ns_bio_test_cb; bio->bio_dev = dev; bio->bio_offset = offset; bio->bio_data = buf; bio->bio_bcount = io_test->size; if (io_test->flags & NVME_TEST_FLAG_REFTHREAD) { #if __FreeBSD_version >= 900017 csw = dev_refthread(dev, &ref); #else csw = dev_refthread(dev); #endif } else csw = dev->si_devsw; mtx = mtx_pool_find(mtxpool_sleep, bio); mtx_lock(mtx); (*csw->d_strategy)(bio); msleep(bio, mtx, PRIBIO, "biotestwait", 0); mtx_unlock(mtx); if (io_test->flags & NVME_TEST_FLAG_REFTHREAD) { #if __FreeBSD_version >= 900017 dev_relthread(dev, ref); #else dev_relthread(dev); #endif } if ((bio->bio_flags & BIO_ERROR) || (bio->bio_resid > 0)) break; g_destroy_bio(bio); io_completed++; getmicrouptime(&t); timevalsub(&t, &io_test->start); if (t.tv_sec >= io_test->time) break; offset += io_test->size; if ((offset + io_test->size) > nvme_ns_get_size(io_test->ns)) offset = 0; } io_test->io_completed[idx] = io_completed; wakeup_one(io_test); free(buf, M_NVME); atomic_subtract_int(&io_test->td_active, 1); mb(); #if __FreeBSD_version >= 800000 kthread_exit(); #else kthread_exit(0); #endif } static void nvme_ns_io_test_cb(void *arg, const struct nvme_completion *cpl) { struct nvme_io_test_thread *tth = arg; struct timeval t; tth->io_completed++; if (nvme_completion_is_error(cpl)) { printf("%s: error occurred\n", __func__); wakeup_one(tth); return; } getmicrouptime(&t); timevalsub(&t, &tth->start); if (t.tv_sec >= tth->time) { wakeup_one(tth); return; } switch (tth->opc) { case NVME_OPC_WRITE: nvme_ns_cmd_write(tth->ns, tth->buf, tth->idx * 2048, tth->size/nvme_ns_get_sector_size(tth->ns), nvme_ns_io_test_cb, tth); break; case NVME_OPC_READ: nvme_ns_cmd_read(tth->ns, tth->buf, tth->idx * 2048, tth->size/nvme_ns_get_sector_size(tth->ns), nvme_ns_io_test_cb, tth); break; default: break; } } static void nvme_ns_io_test(void *arg) { struct nvme_io_test_internal *io_test = arg; struct nvme_io_test_thread *tth; struct nvme_completion cpl; int error; tth = malloc(sizeof(*tth), M_NVME, M_WAITOK | M_ZERO); tth->ns = io_test->ns; tth->opc = io_test->opc; memcpy(&tth->start, &io_test->start, sizeof(tth->start)); tth->buf = malloc(io_test->size, M_NVME, M_WAITOK); tth->size = io_test->size; tth->time = io_test->time; tth->idx = atomic_fetchadd_int(&io_test->td_idx, 1); memset(&cpl, 0, sizeof(cpl)); nvme_ns_io_test_cb(tth, &cpl); error = tsleep(tth, 0, "test_wait", tth->time*hz*2); if (error) printf("%s: error = %d\n", __func__, error); io_test->io_completed[tth->idx] = tth->io_completed; wakeup_one(io_test); free(tth->buf, M_NVME); free(tth, M_NVME); atomic_subtract_int(&io_test->td_active, 1); mb(); #if __FreeBSD_version >= 800004 kthread_exit(); #else kthread_exit(0); #endif } void nvme_ns_test(struct nvme_namespace *ns, u_long cmd, caddr_t arg) { struct nvme_io_test *io_test; struct nvme_io_test_internal *io_test_internal; void (*fn)(void *); int i; io_test = (struct nvme_io_test *)arg; if ((io_test->opc != NVME_OPC_READ) && (io_test->opc != NVME_OPC_WRITE)) return; if (io_test->size % nvme_ns_get_sector_size(ns)) return; io_test_internal = malloc(sizeof(*io_test_internal), M_NVME, M_WAITOK | M_ZERO); io_test_internal->opc = io_test->opc; io_test_internal->ns = ns; io_test_internal->td_active = io_test->num_threads; io_test_internal->time = io_test->time; io_test_internal->size = io_test->size; io_test_internal->flags = io_test->flags; if (cmd == NVME_IO_TEST) fn = nvme_ns_io_test; else fn = nvme_ns_bio_test; getmicrouptime(&io_test_internal->start); for (i = 0; i < io_test->num_threads; i++) #if __FreeBSD_version >= 800004 kthread_add(fn, io_test_internal, NULL, NULL, 0, 0, "nvme_io_test[%d]", i); #else kthread_create(fn, io_test_internal, NULL, 0, 0, "nvme_io_test[%d]", i); #endif tsleep(io_test_internal, 0, "nvme_test", io_test->time * 2 * hz); while (io_test_internal->td_active > 0) DELAY(10); memcpy(io_test->io_completed, io_test_internal->io_completed, sizeof(io_test->io_completed)); free(io_test_internal, M_NVME); }
dcui/FreeBSD-9.3_kernel
sys/dev/nvme/nvme_test.c
C
bsd-3-clause
7,360
#! /usr/bin/env python """ # control_get_firmware.py: get firmware version of Gemalto readers # Copyright (C) 2009-2012 Ludovic Rousseau """ # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, see <http://www.gnu.org/licenses/>. from smartcard.System import readers from smartcard.pcsc.PCSCPart10 import (SCARD_SHARE_DIRECT, SCARD_LEAVE_CARD, SCARD_CTL_CODE, getTlvProperties) for reader in readers(): cardConnection = reader.createConnection() cardConnection.connect(mode=SCARD_SHARE_DIRECT, disposition=SCARD_LEAVE_CARD) print "Reader:", reader # properties returned by IOCTL_FEATURE_GET_TLV_PROPERTIES properties = getTlvProperties(cardConnection) # Gemalto devices supports a control code to get firmware if properties['PCSCv2_PART10_PROPERTY_wIdVendor'] == 0x08E6: get_firmware = [0x02] IOCTL_SMARTCARD_VENDOR_IFD_EXCHANGE = SCARD_CTL_CODE(1) res = cardConnection.control(IOCTL_SMARTCARD_VENDOR_IFD_EXCHANGE, get_firmware) print " Firmware:", "".join([chr(x) for x in res]) else: print " Not a Gemalto reader" try: res = properties['PCSCv2_PART10_PROPERTY_sFirmwareID'] print " Firmware:", frimware except KeyError: print " PCSCv2_PART10_PROPERTY_sFirmwareID not supported"
vicamo/pcsc-lite-android
UnitaryTests/control_get_firmware.py
Python
bsd-3-clause
1,904
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model common\models\Holidays */ $this->title = Yii::t('app', 'Update {modelClass}: ', [ 'modelClass' => '', ]) . ' ' . $model->name_holiday; $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Holidays'), 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => $model->name_holiday, 'url' => ['view', 'id' => $model->id]]; $this->params['breadcrumbs'][] = Yii::t('app', 'Update'); ?> <div class="holidays-update"> <h1><?= Html::encode($this->title) ?></h1> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
polumerk/sr-test
backend/views/holidays/update.php
PHP
bsd-3-clause
633
#pragma once #include "chockNgt.h" #include "Audio.h" class Cafe { public: Cafe(); ~Cafe(); void ToBeginning(void); int Draw(float time); void UpdateTime(float time) { last_call_time_ = time; } void StartScene(int nothing) { nothing = nothing; has_white_fade_ = false; to_white_ = 1.0f; } void EndScene(void) { char error_string[MAX_ERROR_LENGTH+1]; audio_.StopSound(0, 36.0f, error_string); has_white_fade_ = true; } void StartVideo(void) { draw_video_ = true; video_start_time_ = last_call_time_; char error_string[MAX_ERROR_LENGTH+1]; audio_.PlaySound("Sawa_5.wav", 0, false, -1, error_string); subtitle_start_time_ = last_call_time_; subtitle_delay_ = 8.0f; subtitle_script_ = "Sawa_5.txt"; } void EndVideo(void) { draw_video_ = false; char error_string[MAX_ERROR_LENGTH+1]; audio_.StopSound(0, 36.0f, error_string); } private: // State machine (initialized incorrectly to test toBeginning() float last_call_time_ = 0.0f; float to_white_ = 3.0f; // fade to white bool draw_video_ = true; float video_start_time_ = 0.0f; bool has_white_fade_ = true; };
chock-mostlyharmless/mostlyharmless
hot_particle_japan/executable/chockNgt/Cafe.h
C
bsd-3-clause
1,268
package net.fortuna.ical4j.validate; import java.util.ServiceLoader; /** * Created by fortuna on 13/09/15. */ public abstract class AbstractCalendarValidatorFactory { private static CalendarValidatorFactory instance; static { instance = ServiceLoader.load(CalendarValidatorFactory.class, DefaultCalendarValidatorFactory.class.getClassLoader()).iterator().next(); } public static CalendarValidatorFactory getInstance() { return instance; } }
ariordan/ical4j
src/main/java/net/fortuna/ical4j/validate/AbstractCalendarValidatorFactory.java
Java
bsd-3-clause
483
<?php use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $model app\models\EmailAddress */ $this->title = $model->id; $this->params['breadcrumbs'][] = ['label' => 'Email Addresses', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="email-address-view"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?> <?= Html::a('Delete', ['delete', 'id' => $model->id], [ 'class' => 'btn btn-danger', 'data' => [ 'confirm' => 'Are you sure you want to delete this item?', 'method' => 'post', ], ]) ?> </p> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'id', 'person_id', 'live', 'type', 'email:email', 'note:ntext', 'user_id_created', 'date_entered', 'date_updated', 'ip_created', 'ip_updated', ], ]) ?> </div>
elminero/contact_v3
views/email-address/view.php
PHP
bsd-3-clause
1,145
/* * H.26L/H.264/AVC/JVT/14496-10/... decoder * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * H.264 / AVC / MPEG4 part10 codec. * @author Michael Niedermayer <michaelni@gmx.at> */ #include "libavutil/avassert.h" #include "libavutil/imgutils.h" #include "libavutil/timer.h" #include "internal.h" #include "cabac.h" #include "cabac_functions.h" #include "error_resilience.h" #include "avcodec.h" #include "h264.h" #include "h264data.h" #include "h264chroma.h" #include "h264_mvpred.h" #include "golomb.h" #include "mathops.h" #include "mpegutils.h" #include "rectangle.h" #include "thread.h" static const uint8_t rem6[QP_MAX_NUM + 1] = { 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, }; static const uint8_t div6[QP_MAX_NUM + 1] = { 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10,10,10,11,11,11,11,11,11,12,12,12,12,12,12,13,13,13, 13, 13, 13, 14,14,14,14, }; static const uint8_t field_scan[16+1] = { 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4, 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4, 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4, 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4, }; static const uint8_t field_scan8x8[64+1] = { 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8, 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8, 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8, 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8, 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8, 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8, 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8, 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8, 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8, 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8, 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8, 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8, 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8, 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8, 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8, 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8, }; static const uint8_t field_scan8x8_cavlc[64+1] = { 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8, 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8, 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8, 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8, 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8, 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8, 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8, 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8, 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8, 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8, 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8, 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8, 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8, 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8, 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8, 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8, }; // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)] static const uint8_t zigzag_scan8x8_cavlc[64+1] = { 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8, 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8, 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8, 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8, 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8, 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8, 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8, 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8, 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8, 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8, 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8, 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8, 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8, 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8, 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8, 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8, }; static const uint8_t dequant4_coeff_init[6][3] = { { 10, 13, 16 }, { 11, 14, 18 }, { 13, 16, 20 }, { 14, 18, 23 }, { 16, 20, 25 }, { 18, 23, 29 }, }; static const uint8_t dequant8_coeff_init_scan[16] = { 0, 3, 4, 3, 3, 1, 5, 1, 4, 5, 2, 5, 3, 1, 5, 1 }; static const uint8_t dequant8_coeff_init[6][6] = { { 20, 18, 32, 19, 25, 24 }, { 22, 19, 35, 21, 28, 26 }, { 26, 23, 42, 24, 33, 31 }, { 28, 25, 45, 26, 35, 33 }, { 32, 28, 51, 30, 40, 38 }, { 36, 32, 58, 34, 46, 43 }, }; static const enum AVPixelFormat h264_hwaccel_pixfmt_list_420[] = { #if CONFIG_H264_DXVA2_HWACCEL AV_PIX_FMT_DXVA2_VLD, #endif #if CONFIG_H264_VAAPI_HWACCEL AV_PIX_FMT_VAAPI_VLD, #endif #if CONFIG_H264_VDA_HWACCEL AV_PIX_FMT_VDA_VLD, AV_PIX_FMT_VDA, #endif #if CONFIG_H264_VDPAU_HWACCEL AV_PIX_FMT_VDPAU, #endif AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE }; static const enum AVPixelFormat h264_hwaccel_pixfmt_list_jpeg_420[] = { #if CONFIG_H264_DXVA2_HWACCEL AV_PIX_FMT_DXVA2_VLD, #endif #if CONFIG_H264_VAAPI_HWACCEL AV_PIX_FMT_VAAPI_VLD, #endif #if CONFIG_H264_VDA_HWACCEL AV_PIX_FMT_VDA_VLD, AV_PIX_FMT_VDA, #endif #if CONFIG_H264_VDPAU_HWACCEL AV_PIX_FMT_VDPAU, #endif AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_NONE }; static void release_unused_pictures(H264Context *h, int remove_current) { int i; /* release non reference frames */ for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) { if (h->DPB[i].f.buf[0] && !h->DPB[i].reference && (remove_current || &h->DPB[i] != h->cur_pic_ptr)) { ff_h264_unref_picture(h, &h->DPB[i]); } } } static int alloc_scratch_buffers(H264Context *h, int linesize) { int alloc_size = FFALIGN(FFABS(linesize) + 32, 32); if (h->bipred_scratchpad) return 0; h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size); // edge emu needs blocksize + filter length - 1 // (= 21x21 for h264) h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21); if (!h->bipred_scratchpad || !h->edge_emu_buffer) { av_freep(&h->bipred_scratchpad); av_freep(&h->edge_emu_buffer); return AVERROR(ENOMEM); } return 0; } static int init_table_pools(H264Context *h) { const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1; const int mb_array_size = h->mb_stride * h->mb_height; const int b4_stride = h->mb_width * 4 + 1; const int b4_array_size = b4_stride * h->mb_height * 4; h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride, av_buffer_allocz); h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) * sizeof(uint32_t), av_buffer_allocz); h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) * sizeof(int16_t), av_buffer_allocz); h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz); if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool || !h->ref_index_pool) { av_buffer_pool_uninit(&h->qscale_table_pool); av_buffer_pool_uninit(&h->mb_type_pool); av_buffer_pool_uninit(&h->motion_val_pool); av_buffer_pool_uninit(&h->ref_index_pool); return AVERROR(ENOMEM); } return 0; } static int alloc_picture(H264Context *h, H264Picture *pic) { int i, ret = 0; av_assert0(!pic->f.data[0]); pic->tf.f = &pic->f; ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ? AV_GET_BUFFER_FLAG_REF : 0); if (ret < 0) goto fail; h->linesize = pic->f.linesize[0]; h->uvlinesize = pic->f.linesize[1]; pic->crop = h->sps.crop; pic->crop_top = h->sps.crop_top; pic->crop_left= h->sps.crop_left; if (h->avctx->hwaccel) { const AVHWAccel *hwaccel = h->avctx->hwaccel; av_assert0(!pic->hwaccel_picture_private); if (hwaccel->frame_priv_data_size) { pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->frame_priv_data_size); if (!pic->hwaccel_priv_buf) return AVERROR(ENOMEM); pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data; } } if (!h->avctx->hwaccel && CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY && pic->f.data[2]) { int h_chroma_shift, v_chroma_shift; av_pix_fmt_get_chroma_sub_sample(pic->f.format, &h_chroma_shift, &v_chroma_shift); for(i=0; i<FF_CEIL_RSHIFT(h->avctx->height, v_chroma_shift); i++) { memset(pic->f.data[1] + pic->f.linesize[1]*i, 0x80, FF_CEIL_RSHIFT(h->avctx->width, h_chroma_shift)); memset(pic->f.data[2] + pic->f.linesize[2]*i, 0x80, FF_CEIL_RSHIFT(h->avctx->width, h_chroma_shift)); } } if (!h->qscale_table_pool) { ret = init_table_pools(h); if (ret < 0) goto fail; } pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool); pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool); if (!pic->qscale_table_buf || !pic->mb_type_buf) goto fail; pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1; pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1; for (i = 0; i < 2; i++) { pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool); pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool); if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i]) goto fail; pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4; pic->ref_index[i] = pic->ref_index_buf[i]->data; } return 0; fail: ff_h264_unref_picture(h, pic); return (ret < 0) ? ret : AVERROR(ENOMEM); } static inline int pic_is_unused(H264Context *h, H264Picture *pic) { if (!pic->f.buf[0]) return 1; if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF)) return 1; return 0; } static int find_unused_picture(H264Context *h) { int i; for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) { if (pic_is_unused(h, &h->DPB[i])) break; } if (i == H264_MAX_PICTURE_COUNT) return AVERROR_INVALIDDATA; if (h->DPB[i].needs_realloc) { h->DPB[i].needs_realloc = 0; ff_h264_unref_picture(h, &h->DPB[i]); } return i; } static void init_dequant8_coeff_table(H264Context *h) { int i, j, q, x; const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8); for (i = 0; i < 6; i++) { h->dequant8_coeff[i] = h->dequant8_buffer[i]; for (j = 0; j < i; j++) if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i], 64 * sizeof(uint8_t))) { h->dequant8_coeff[i] = h->dequant8_buffer[j]; break; } if (j < i) continue; for (q = 0; q < max_qp + 1; q++) { int shift = div6[q]; int idx = rem6[q]; for (x = 0; x < 64; x++) h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] = ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] * h->pps.scaling_matrix8[i][x]) << shift; } } } static void init_dequant4_coeff_table(H264Context *h) { int i, j, q, x; const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8); for (i = 0; i < 6; i++) { h->dequant4_coeff[i] = h->dequant4_buffer[i]; for (j = 0; j < i; j++) if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i], 16 * sizeof(uint8_t))) { h->dequant4_coeff[i] = h->dequant4_buffer[j]; break; } if (j < i) continue; for (q = 0; q < max_qp + 1; q++) { int shift = div6[q] + 2; int idx = rem6[q]; for (x = 0; x < 16; x++) h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] = ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] * h->pps.scaling_matrix4[i][x]) << shift; } } } void h264_init_dequant_tables(H264Context *h) { int i, x; init_dequant4_coeff_table(h); memset(h->dequant8_coeff, 0, sizeof(h->dequant8_coeff)); if (h->pps.transform_8x8_mode) init_dequant8_coeff_table(h); if (h->sps.transform_bypass) { for (i = 0; i < 6; i++) for (x = 0; x < 16; x++) h->dequant4_coeff[i][0][x] = 1 << 6; if (h->pps.transform_8x8_mode) for (i = 0; i < 6; i++) for (x = 0; x < 64; x++) h->dequant8_coeff[i][0][x] = 1 << 6; } } /** * Mimic alloc_tables(), but for every context thread. */ static void clone_tables(H264Context *dst, H264Context *src, int i) { dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride; dst->non_zero_count = src->non_zero_count; dst->slice_table = src->slice_table; dst->cbp_table = src->cbp_table; dst->mb2b_xy = src->mb2b_xy; dst->mb2br_xy = src->mb2br_xy; dst->chroma_pred_mode_table = src->chroma_pred_mode_table; dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride; dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride; dst->direct_table = src->direct_table; dst->list_counts = src->list_counts; dst->DPB = src->DPB; dst->cur_pic_ptr = src->cur_pic_ptr; dst->cur_pic = src->cur_pic; dst->bipred_scratchpad = NULL; dst->edge_emu_buffer = NULL; ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma, src->sps.chroma_format_idc); } #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size)))) #undef REBASE_PICTURE #define REBASE_PICTURE(pic, new_ctx, old_ctx) \ (((pic) && (pic) >= (old_ctx)->DPB && \ (pic) < (old_ctx)->DPB + H264_MAX_PICTURE_COUNT) ? \ &(new_ctx)->DPB[(pic) - (old_ctx)->DPB] : NULL) static void copy_picture_range(H264Picture **to, H264Picture **from, int count, H264Context *new_base, H264Context *old_base) { int i; for (i = 0; i < count; i++) { assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) || IN_RANGE(from[i], old_base->DPB, sizeof(H264Picture) * H264_MAX_PICTURE_COUNT) || !from[i])); to[i] = REBASE_PICTURE(from[i], new_base, old_base); } } static int copy_parameter_set(void **to, void **from, int count, int size) { int i; for (i = 0; i < count; i++) { if (to[i] && !from[i]) { av_freep(&to[i]); } else if (from[i] && !to[i]) { to[i] = av_malloc(size); if (!to[i]) return AVERROR(ENOMEM); } if (from[i]) memcpy(to[i], from[i], size); } return 0; } #define copy_fields(to, from, start_field, end_field) \ memcpy(&(to)->start_field, &(from)->start_field, \ (char *)&(to)->end_field - (char *)&(to)->start_field) static int h264_slice_header_init(H264Context *h, int reinit); int ff_h264_update_thread_context(AVCodecContext *dst, const AVCodecContext *src) { H264Context *h = dst->priv_data, *h1 = src->priv_data; int inited = h->context_initialized, err = 0; int context_reinitialized = 0; int i, ret; if (dst == src) return 0; if (inited && (h->width != h1->width || h->height != h1->height || h->mb_width != h1->mb_width || h->mb_height != h1->mb_height || h->sps.bit_depth_luma != h1->sps.bit_depth_luma || h->sps.chroma_format_idc != h1->sps.chroma_format_idc || h->sps.colorspace != h1->sps.colorspace)) { /* set bits_per_raw_sample to the previous value. the check for changed * bit depth in h264_set_parameter_from_sps() uses it and sets it to * the current value */ h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma; av_freep(&h->bipred_scratchpad); h->width = h1->width; h->height = h1->height; h->mb_height = h1->mb_height; h->mb_width = h1->mb_width; h->mb_num = h1->mb_num; h->mb_stride = h1->mb_stride; h->b_stride = h1->b_stride; // SPS/PPS if ((ret = copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers, MAX_SPS_COUNT, sizeof(SPS))) < 0) return ret; h->sps = h1->sps; if ((ret = copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers, MAX_PPS_COUNT, sizeof(PPS))) < 0) return ret; h->pps = h1->pps; if ((err = h264_slice_header_init(h, 1)) < 0) { av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed\n"); return err; } context_reinitialized = 1; #if 0 h264_set_parameter_from_sps(h); //Note we set context_reinitialized which will cause h264_set_parameter_from_sps to be reexecuted h->cur_chroma_format_idc = h1->cur_chroma_format_idc; #endif } /* update linesize on resize for h264. The h264 decoder doesn't * necessarily call ff_mpv_frame_start in the new thread */ h->linesize = h1->linesize; h->uvlinesize = h1->uvlinesize; /* copy block_offset since frame_start may not be called */ memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset)); if (!inited) { for (i = 0; i < MAX_SPS_COUNT; i++) av_freep(h->sps_buffers + i); for (i = 0; i < MAX_PPS_COUNT; i++) av_freep(h->pps_buffers + i); av_freep(&h->rbsp_buffer[0]); av_freep(&h->rbsp_buffer[1]); memcpy(h, h1, offsetof(H264Context, intra_pcm_ptr)); memcpy(&h->cabac, &h1->cabac, sizeof(H264Context) - offsetof(H264Context, cabac)); av_assert0((void*)&h->cabac == &h->mb_padding + 1); memset(h->sps_buffers, 0, sizeof(h->sps_buffers)); memset(h->pps_buffers, 0, sizeof(h->pps_buffers)); memset(&h->er, 0, sizeof(h->er)); memset(&h->mb, 0, sizeof(h->mb)); memset(&h->mb_luma_dc, 0, sizeof(h->mb_luma_dc)); memset(&h->mb_padding, 0, sizeof(h->mb_padding)); memset(&h->cur_pic, 0, sizeof(h->cur_pic)); h->avctx = dst; h->DPB = NULL; h->qscale_table_pool = NULL; h->mb_type_pool = NULL; h->ref_index_pool = NULL; h->motion_val_pool = NULL; h->intra4x4_pred_mode= NULL; h->non_zero_count = NULL; h->slice_table_base = NULL; h->slice_table = NULL; h->cbp_table = NULL; h->chroma_pred_mode_table = NULL; memset(h->mvd_table, 0, sizeof(h->mvd_table)); h->direct_table = NULL; h->list_counts = NULL; h->mb2b_xy = NULL; h->mb2br_xy = NULL; for (i = 0; i < 2; i++) { h->rbsp_buffer[i] = NULL; h->rbsp_buffer_size[i] = 0; } if (h1->context_initialized) { h->context_initialized = 0; memset(&h->cur_pic, 0, sizeof(h->cur_pic)); av_frame_unref(&h->cur_pic.f); h->cur_pic.tf.f = &h->cur_pic.f; ret = ff_h264_alloc_tables(h); if (ret < 0) { av_log(dst, AV_LOG_ERROR, "Could not allocate memory\n"); return ret; } ret = ff_h264_context_init(h); if (ret < 0) { av_log(dst, AV_LOG_ERROR, "context_init() failed.\n"); return ret; } } h->bipred_scratchpad = NULL; h->edge_emu_buffer = NULL; h->thread_context[0] = h; h->context_initialized = h1->context_initialized; } h->avctx->coded_height = h1->avctx->coded_height; h->avctx->coded_width = h1->avctx->coded_width; h->avctx->width = h1->avctx->width; h->avctx->height = h1->avctx->height; h->coded_picture_number = h1->coded_picture_number; h->first_field = h1->first_field; h->picture_structure = h1->picture_structure; h->qscale = h1->qscale; h->droppable = h1->droppable; h->low_delay = h1->low_delay; for (i = 0; h->DPB && i < H264_MAX_PICTURE_COUNT; i++) { ff_h264_unref_picture(h, &h->DPB[i]); if (h1->DPB && h1->DPB[i].f.buf[0] && (ret = ff_h264_ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0) return ret; } h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1); ff_h264_unref_picture(h, &h->cur_pic); if (h1->cur_pic.f.buf[0] && (ret = ff_h264_ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0) return ret; h->workaround_bugs = h1->workaround_bugs; h->low_delay = h1->low_delay; h->droppable = h1->droppable; // extradata/NAL handling h->is_avc = h1->is_avc; // SPS/PPS if ((ret = copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers, MAX_SPS_COUNT, sizeof(SPS))) < 0) return ret; h->sps = h1->sps; if ((ret = copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers, MAX_PPS_COUNT, sizeof(PPS))) < 0) return ret; h->pps = h1->pps; // Dequantization matrices // FIXME these are big - can they be only copied when PPS changes? copy_fields(h, h1, dequant4_buffer, dequant4_coeff); for (i = 0; i < 6; i++) h->dequant4_coeff[i] = h->dequant4_buffer[0] + (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]); for (i = 0; i < 6; i++) h->dequant8_coeff[i] = h->dequant8_buffer[0] + (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]); h->dequant_coeff_pps = h1->dequant_coeff_pps; // POC timing copy_fields(h, h1, poc_lsb, redundant_pic_count); // reference lists copy_fields(h, h1, short_ref, cabac_init_idc); copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1); copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1); copy_picture_range(h->delayed_pic, h1->delayed_pic, MAX_DELAYED_PIC_COUNT + 2, h, h1); h->frame_recovered = h1->frame_recovered; if (context_reinitialized) ff_h264_set_parameter_from_sps(h); if (!h->cur_pic_ptr) return 0; if (!h->droppable) { err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index); h->prev_poc_msb = h->poc_msb; h->prev_poc_lsb = h->poc_lsb; } h->prev_frame_num_offset = h->frame_num_offset; h->prev_frame_num = h->frame_num; h->outputed_poc = h->next_outputed_poc; h->recovery_frame = h1->recovery_frame; return err; } static int h264_frame_start(H264Context *h) { H264Picture *pic; int i, ret; const int pixel_shift = h->pixel_shift; int c[4] = { 1<<(h->sps.bit_depth_luma-1), 1<<(h->sps.bit_depth_chroma-1), 1<<(h->sps.bit_depth_chroma-1), -1 }; if (!ff_thread_can_start_frame(h->avctx)) { av_log(h->avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n"); return -1; } release_unused_pictures(h, 1); h->cur_pic_ptr = NULL; i = find_unused_picture(h); if (i < 0) { av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n"); return i; } pic = &h->DPB[i]; pic->reference = h->droppable ? 0 : h->picture_structure; pic->f.coded_picture_number = h->coded_picture_number++; pic->field_picture = h->picture_structure != PICT_FRAME; /* * Zero key_frame here; IDR markings per slice in frame or fields are ORed * in later. * See decode_nal_units(). */ pic->f.key_frame = 0; pic->mmco_reset = 0; pic->recovered = 0; pic->invalid_gap = 0; pic->sei_recovery_frame_cnt = h->sei_recovery_frame_cnt; if ((ret = alloc_picture(h, pic)) < 0) return ret; if(!h->frame_recovered && !h->avctx->hwaccel && !(h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)) avpriv_color_frame(&pic->f, c); h->cur_pic_ptr = pic; ff_h264_unref_picture(h, &h->cur_pic); if (CONFIG_ERROR_RESILIENCE) { ff_h264_set_erpic(&h->er.cur_pic, NULL); } if ((ret = ff_h264_ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0) return ret; if (CONFIG_ERROR_RESILIENCE) { ff_er_frame_start(&h->er); ff_h264_set_erpic(&h->er.last_pic, NULL); ff_h264_set_erpic(&h->er.next_pic, NULL); } assert(h->linesize && h->uvlinesize); for (i = 0; i < 16; i++) { h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3); h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3); } for (i = 0; i < 16; i++) { h->block_offset[16 + i] = h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3); h->block_offset[48 + 16 + i] = h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3); } /* We mark the current picture as non-reference after allocating it, so * that if we break out due to an error it can be released automatically * in the next ff_mpv_frame_start(). */ h->cur_pic_ptr->reference = 0; h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX; h->next_output_pic = NULL; assert(h->cur_pic_ptr->long_ref == 0); return 0; } static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int simple) { uint8_t *top_border; int top_idx = 1; const int pixel_shift = h->pixel_shift; int chroma444 = CHROMA444(h); int chroma422 = CHROMA422(h); src_y -= linesize; src_cb -= uvlinesize; src_cr -= uvlinesize; if (!simple && FRAME_MBAFF(h)) { if (h->mb_y & 1) { if (!MB_MBAFF(h)) { top_border = h->top_borders[0][h->mb_x]; AV_COPY128(top_border, src_y + 15 * linesize); if (pixel_shift) AV_COPY128(top_border + 16, src_y + 15 * linesize + 16); if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) { if (chroma444) { if (pixel_shift) { AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize); AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16); AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize); AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16); } else { AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize); AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize); } } else if (chroma422) { if (pixel_shift) { AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize); AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize); } else { AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize); AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize); } } else { if (pixel_shift) { AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize); AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize); } else { AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize); AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize); } } } } } else if (MB_MBAFF(h)) { top_idx = 0; } else return; } top_border = h->top_borders[top_idx][h->mb_x]; /* There are two lines saved, the line above the top macroblock * of a pair, and the line above the bottom macroblock. */ AV_COPY128(top_border, src_y + 16 * linesize); if (pixel_shift) AV_COPY128(top_border + 16, src_y + 16 * linesize + 16); if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) { if (chroma444) { if (pixel_shift) { AV_COPY128(top_border + 32, src_cb + 16 * linesize); AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16); AV_COPY128(top_border + 64, src_cr + 16 * linesize); AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16); } else { AV_COPY128(top_border + 16, src_cb + 16 * linesize); AV_COPY128(top_border + 32, src_cr + 16 * linesize); } } else if (chroma422) { if (pixel_shift) { AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize); AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize); } else { AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize); AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize); } } else { if (pixel_shift) { AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize); AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize); } else { AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize); AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize); } } } } /** * Initialize implicit_weight table. * @param field 0/1 initialize the weight for interlaced MBAFF * -1 initializes the rest */ static void implicit_weight_table(H264Context *h, int field) { int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1; for (i = 0; i < 2; i++) { h->luma_weight_flag[i] = 0; h->chroma_weight_flag[i] = 0; } if (field < 0) { if (h->picture_structure == PICT_FRAME) { cur_poc = h->cur_pic_ptr->poc; } else { cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1]; } if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF(h) && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) { h->use_weight = 0; h->use_weight_chroma = 0; return; } ref_start = 0; ref_count0 = h->ref_count[0]; ref_count1 = h->ref_count[1]; } else { cur_poc = h->cur_pic_ptr->field_poc[field]; ref_start = 16; ref_count0 = 16 + 2 * h->ref_count[0]; ref_count1 = 16 + 2 * h->ref_count[1]; } h->use_weight = 2; h->use_weight_chroma = 2; h->luma_log2_weight_denom = 5; h->chroma_log2_weight_denom = 5; for (ref0 = ref_start; ref0 < ref_count0; ref0++) { int poc0 = h->ref_list[0][ref0].poc; for (ref1 = ref_start; ref1 < ref_count1; ref1++) { int w = 32; if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) { int poc1 = h->ref_list[1][ref1].poc; int td = av_clip(poc1 - poc0, -128, 127); if (td) { int tb = av_clip(cur_poc - poc0, -128, 127); int tx = (16384 + (FFABS(td) >> 1)) / td; int dist_scale_factor = (tb * tx + 32) >> 8; if (dist_scale_factor >= -64 && dist_scale_factor <= 128) w = 64 - dist_scale_factor; } } if (field < 0) { h->implicit_weight[ref0][ref1][0] = h->implicit_weight[ref0][ref1][1] = w; } else { h->implicit_weight[ref0][ref1][field] = w; } } } } /** * initialize scan tables */ static void init_scan_tables(H264Context *h) { int i; for (i = 0; i < 16; i++) { #define TRANSPOSE(x) ((x) >> 2) | (((x) << 2) & 0xF) h->zigzag_scan[i] = TRANSPOSE(zigzag_scan[i]); h->field_scan[i] = TRANSPOSE(field_scan[i]); #undef TRANSPOSE } for (i = 0; i < 64; i++) { #define TRANSPOSE(x) ((x) >> 3) | (((x) & 7) << 3) h->zigzag_scan8x8[i] = TRANSPOSE(ff_zigzag_direct[i]); h->zigzag_scan8x8_cavlc[i] = TRANSPOSE(zigzag_scan8x8_cavlc[i]); h->field_scan8x8[i] = TRANSPOSE(field_scan8x8[i]); h->field_scan8x8_cavlc[i] = TRANSPOSE(field_scan8x8_cavlc[i]); #undef TRANSPOSE } if (h->sps.transform_bypass) { // FIXME same ugly memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 )); memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 )); memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0)); memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 )); memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 )); memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 )); } else { memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 )); memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 )); memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0)); memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 )); memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 )); memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 )); } } /** * Replicate H264 "master" context to thread contexts. */ static int clone_slice(H264Context *dst, H264Context *src) { memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset)); dst->cur_pic_ptr = src->cur_pic_ptr; dst->cur_pic = src->cur_pic; dst->linesize = src->linesize; dst->uvlinesize = src->uvlinesize; dst->first_field = src->first_field; dst->prev_poc_msb = src->prev_poc_msb; dst->prev_poc_lsb = src->prev_poc_lsb; dst->prev_frame_num_offset = src->prev_frame_num_offset; dst->prev_frame_num = src->prev_frame_num; dst->short_ref_count = src->short_ref_count; memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref)); memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref)); memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list)); memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff)); memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff)); return 0; } static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback) { enum AVPixelFormat pix_fmts[2]; const enum AVPixelFormat *choices = pix_fmts; int i; pix_fmts[1] = AV_PIX_FMT_NONE; switch (h->sps.bit_depth_luma) { case 9: if (CHROMA444(h)) { if (h->avctx->colorspace == AVCOL_SPC_RGB) { pix_fmts[0] = AV_PIX_FMT_GBRP9; } else pix_fmts[0] = AV_PIX_FMT_YUV444P9; } else if (CHROMA422(h)) pix_fmts[0] = AV_PIX_FMT_YUV422P9; else pix_fmts[0] = AV_PIX_FMT_YUV420P9; break; case 10: if (CHROMA444(h)) { if (h->avctx->colorspace == AVCOL_SPC_RGB) { pix_fmts[0] = AV_PIX_FMT_GBRP10; } else pix_fmts[0] = AV_PIX_FMT_YUV444P10; } else if (CHROMA422(h)) pix_fmts[0] = AV_PIX_FMT_YUV422P10; else pix_fmts[0] = AV_PIX_FMT_YUV420P10; break; case 12: if (CHROMA444(h)) { if (h->avctx->colorspace == AVCOL_SPC_RGB) { pix_fmts[0] = AV_PIX_FMT_GBRP12; } else pix_fmts[0] = AV_PIX_FMT_YUV444P12; } else if (CHROMA422(h)) pix_fmts[0] = AV_PIX_FMT_YUV422P12; else pix_fmts[0] = AV_PIX_FMT_YUV420P12; break; case 14: if (CHROMA444(h)) { if (h->avctx->colorspace == AVCOL_SPC_RGB) { pix_fmts[0] = AV_PIX_FMT_GBRP14; } else pix_fmts[0] = AV_PIX_FMT_YUV444P14; } else if (CHROMA422(h)) pix_fmts[0] = AV_PIX_FMT_YUV422P14; else pix_fmts[0] = AV_PIX_FMT_YUV420P14; break; case 8: if (CHROMA444(h)) { if (h->avctx->colorspace == AVCOL_SPC_YCGCO) av_log(h->avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n"); if (h->avctx->colorspace == AVCOL_SPC_RGB) pix_fmts[0] = AV_PIX_FMT_GBRP; else if (h->avctx->color_range == AVCOL_RANGE_JPEG) pix_fmts[0] = AV_PIX_FMT_YUVJ444P; else pix_fmts[0] = AV_PIX_FMT_YUV444P; } else if (CHROMA422(h)) { if (h->avctx->color_range == AVCOL_RANGE_JPEG) pix_fmts[0] = AV_PIX_FMT_YUVJ422P; else pix_fmts[0] = AV_PIX_FMT_YUV422P; } else { if (h->avctx->codec->pix_fmts) choices = h->avctx->codec->pix_fmts; else if (h->avctx->color_range == AVCOL_RANGE_JPEG) choices = h264_hwaccel_pixfmt_list_jpeg_420; else choices = h264_hwaccel_pixfmt_list_420; } break; default: av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n", h->sps.bit_depth_luma); return AVERROR_INVALIDDATA; } for (i=0; choices[i] != AV_PIX_FMT_NONE; i++) if (choices[i] == h->avctx->pix_fmt && !force_callback) return choices[i]; return ff_thread_get_format(h->avctx, choices); } /* export coded and cropped frame dimensions to AVCodecContext */ static int init_dimensions(H264Context *h) { int width = h->width - (h->sps.crop_right + h->sps.crop_left); int height = h->height - (h->sps.crop_top + h->sps.crop_bottom); int crop_present = h->sps.crop_left || h->sps.crop_top || h->sps.crop_right || h->sps.crop_bottom; av_assert0(h->sps.crop_right + h->sps.crop_left < (unsigned)h->width); av_assert0(h->sps.crop_top + h->sps.crop_bottom < (unsigned)h->height); /* handle container cropping */ if (!crop_present && FFALIGN(h->avctx->width, 16) == h->width && FFALIGN(h->avctx->height, 16) == h->height) { width = h->avctx->width; height = h->avctx->height; } if (width <= 0 || height <= 0) { av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n", width, height); if (h->avctx->err_recognition & AV_EF_EXPLODE) return AVERROR_INVALIDDATA; av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n"); h->sps.crop_bottom = h->sps.crop_top = h->sps.crop_right = h->sps.crop_left = h->sps.crop = 0; width = h->width; height = h->height; } h->avctx->coded_width = h->width; h->avctx->coded_height = h->height; h->avctx->width = width; h->avctx->height = height; return 0; } static int h264_slice_header_init(H264Context *h, int reinit) { int nb_slices = (HAVE_THREADS && h->avctx->active_thread_type & FF_THREAD_SLICE) ? h->avctx->thread_count : 1; int i, ret; ff_set_sar(h->avctx, h->sps.sar); av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt, &h->chroma_x_shift, &h->chroma_y_shift); if (h->sps.timing_info_present_flag) { int64_t den = h->sps.time_scale; if (h->x264_build < 44U) den *= 2; av_reduce(&h->avctx->framerate.den, &h->avctx->framerate.num, h->sps.num_units_in_tick * h->avctx->ticks_per_frame, den, 1 << 30); } if (reinit) ff_h264_free_tables(h, 0); h->first_field = 0; h->prev_interlaced_frame = 1; init_scan_tables(h); ret = ff_h264_alloc_tables(h); if (ret < 0) { av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n"); goto fail; } if (nb_slices > H264_MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) { int max_slices; if (h->mb_height) max_slices = FFMIN(H264_MAX_THREADS, h->mb_height); else max_slices = H264_MAX_THREADS; av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices %d," " reducing to %d\n", nb_slices, max_slices); nb_slices = max_slices; } h->slice_context_count = nb_slices; if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) { ret = ff_h264_context_init(h); if (ret < 0) { av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n"); goto fail; } } else { for (i = 1; i < h->slice_context_count; i++) { H264Context *c; c = h->thread_context[i] = av_mallocz(sizeof(H264Context)); if (!c) { ret = AVERROR(ENOMEM); goto fail; } c->avctx = h->avctx; if (CONFIG_ERROR_RESILIENCE) { c->mecc = h->mecc; } c->vdsp = h->vdsp; c->h264dsp = h->h264dsp; c->h264qpel = h->h264qpel; c->h264chroma = h->h264chroma; c->sps = h->sps; c->pps = h->pps; c->pixel_shift = h->pixel_shift; c->cur_chroma_format_idc = h->cur_chroma_format_idc; c->width = h->width; c->height = h->height; c->linesize = h->linesize; c->uvlinesize = h->uvlinesize; c->chroma_x_shift = h->chroma_x_shift; c->chroma_y_shift = h->chroma_y_shift; c->qscale = h->qscale; c->droppable = h->droppable; c->data_partitioning = h->data_partitioning; c->low_delay = h->low_delay; c->mb_width = h->mb_width; c->mb_height = h->mb_height; c->mb_stride = h->mb_stride; c->mb_num = h->mb_num; c->flags = h->flags; c->workaround_bugs = h->workaround_bugs; c->pict_type = h->pict_type; init_scan_tables(c); clone_tables(c, h, i); c->context_initialized = 1; } for (i = 0; i < h->slice_context_count; i++) if ((ret = ff_h264_context_init(h->thread_context[i])) < 0) { av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n"); goto fail; } } h->context_initialized = 1; return 0; fail: ff_h264_free_tables(h, 0); h->context_initialized = 0; return ret; } static enum AVPixelFormat non_j_pixfmt(enum AVPixelFormat a) { switch (a) { case AV_PIX_FMT_YUVJ420P: return AV_PIX_FMT_YUV420P; case AV_PIX_FMT_YUVJ422P: return AV_PIX_FMT_YUV422P; case AV_PIX_FMT_YUVJ444P: return AV_PIX_FMT_YUV444P; default: return a; } } /** * Decode a slice header. * This will (re)intialize the decoder and call h264_frame_start() as needed. * * @param h h264context * @param h0 h264 master context (differs from 'h' when doing sliced based * parallel decoding) * * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded */ int ff_h264_decode_slice_header(H264Context *h, H264Context *h0) { unsigned int first_mb_in_slice; unsigned int pps_id; int ret; unsigned int slice_type, tmp, i, j; int last_pic_structure, last_pic_droppable; int must_reinit; int needs_reinit = 0; int field_pic_flag, bottom_field_flag; h->qpel_put = h->h264qpel.put_h264_qpel_pixels_tab; h->qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab; first_mb_in_slice = get_ue_golomb_long(&h->gb); if (first_mb_in_slice == 0) { // FIXME better field boundary detection if (h0->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) { ff_h264_field_end(h, 1); } h0->current_slice = 0; if (!h0->first_field) { if (h->cur_pic_ptr && !h->droppable) { ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, h->picture_structure == PICT_BOTTOM_FIELD); } h->cur_pic_ptr = NULL; } } slice_type = get_ue_golomb_31(&h->gb); if (slice_type > 9) { av_log(h->avctx, AV_LOG_ERROR, "slice type %d too large at %d %d\n", slice_type, h->mb_x, h->mb_y); return AVERROR_INVALIDDATA; } if (slice_type > 4) { slice_type -= 5; h->slice_type_fixed = 1; } else h->slice_type_fixed = 0; slice_type = golomb_to_pict_type[slice_type]; h->slice_type = slice_type; h->slice_type_nos = slice_type & 3; if (h->nal_unit_type == NAL_IDR_SLICE && h->slice_type_nos != AV_PICTURE_TYPE_I) { av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n"); return AVERROR_INVALIDDATA; } if ( (h->avctx->skip_frame >= AVDISCARD_NONREF && !h->nal_ref_idc) || (h->avctx->skip_frame >= AVDISCARD_BIDIR && h->slice_type_nos == AV_PICTURE_TYPE_B) || (h->avctx->skip_frame >= AVDISCARD_NONINTRA && h->slice_type_nos != AV_PICTURE_TYPE_I) || (h->avctx->skip_frame >= AVDISCARD_NONKEY && h->nal_unit_type != NAL_IDR_SLICE) || h->avctx->skip_frame >= AVDISCARD_ALL) { return SLICE_SKIPED; } // to make a few old functions happy, it's wrong though h->pict_type = h->slice_type; pps_id = get_ue_golomb(&h->gb); if (pps_id >= MAX_PPS_COUNT) { av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", pps_id); return AVERROR_INVALIDDATA; } if (!h0->pps_buffers[pps_id]) { av_log(h->avctx, AV_LOG_ERROR, "non-existing PPS %u referenced\n", pps_id); return AVERROR_INVALIDDATA; } if (h0->au_pps_id >= 0 && pps_id != h0->au_pps_id) { av_log(h->avctx, AV_LOG_ERROR, "PPS change from %d to %d forbidden\n", h0->au_pps_id, pps_id); return AVERROR_INVALIDDATA; } h->pps = *h0->pps_buffers[pps_id]; if (!h0->sps_buffers[h->pps.sps_id]) { av_log(h->avctx, AV_LOG_ERROR, "non-existing SPS %u referenced\n", h->pps.sps_id); return AVERROR_INVALIDDATA; } if (h->pps.sps_id != h->sps.sps_id || h->pps.sps_id != h->current_sps_id || h0->sps_buffers[h->pps.sps_id]->new) { h->sps = *h0->sps_buffers[h->pps.sps_id]; if (h->mb_width != h->sps.mb_width || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma || h->cur_chroma_format_idc != h->sps.chroma_format_idc ) needs_reinit = 1; if (h->bit_depth_luma != h->sps.bit_depth_luma || h->chroma_format_idc != h->sps.chroma_format_idc) { h->bit_depth_luma = h->sps.bit_depth_luma; h->chroma_format_idc = h->sps.chroma_format_idc; needs_reinit = 1; } if ((ret = ff_h264_set_parameter_from_sps(h)) < 0) return ret; } h->avctx->profile = ff_h264_get_profile(&h->sps); h->avctx->level = h->sps.level_idc; h->avctx->refs = h->sps.ref_frame_count; must_reinit = (h->context_initialized && ( 16*h->sps.mb_width != h->avctx->coded_width || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma || h->cur_chroma_format_idc != h->sps.chroma_format_idc || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio) || h->mb_width != h->sps.mb_width || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) )); if (non_j_pixfmt(h0->avctx->pix_fmt) != non_j_pixfmt(get_pixel_format(h0, 0))) must_reinit = 1; h->mb_width = h->sps.mb_width; h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag); h->mb_num = h->mb_width * h->mb_height; h->mb_stride = h->mb_width + 1; h->b_stride = h->mb_width * 4; h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p h->width = 16 * h->mb_width; h->height = 16 * h->mb_height; ret = init_dimensions(h); if (ret < 0) return ret; if (h->sps.video_signal_type_present_flag) { h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; if (h->sps.colour_description_present_flag) { if (h->avctx->colorspace != h->sps.colorspace) needs_reinit = 1; h->avctx->color_primaries = h->sps.color_primaries; h->avctx->color_trc = h->sps.color_trc; h->avctx->colorspace = h->sps.colorspace; } } if (h->context_initialized && (must_reinit || needs_reinit)) { if (h != h0) { av_log(h->avctx, AV_LOG_ERROR, "changing width %d -> %d / height %d -> %d on " "slice %d\n", h->width, h->avctx->coded_width, h->height, h->avctx->coded_height, h0->current_slice + 1); return AVERROR_INVALIDDATA; } ff_h264_flush_change(h); if ((ret = get_pixel_format(h, 1)) < 0) return ret; h->avctx->pix_fmt = ret; av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, " "pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt)); if ((ret = h264_slice_header_init(h, 1)) < 0) { av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed\n"); return ret; } } if (!h->context_initialized) { if (h != h0) { av_log(h->avctx, AV_LOG_ERROR, "Cannot (re-)initialize context during parallel decoding.\n"); return AVERROR_PATCHWELCOME; } if ((ret = get_pixel_format(h, 1)) < 0) return ret; h->avctx->pix_fmt = ret; if ((ret = h264_slice_header_init(h, 0)) < 0) { av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed\n"); return ret; } } if (h == h0 && h->dequant_coeff_pps != pps_id) { h->dequant_coeff_pps = pps_id; h264_init_dequant_tables(h); } h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num); h->mb_mbaff = 0; h->mb_aff_frame = 0; last_pic_structure = h0->picture_structure; last_pic_droppable = h0->droppable; h->droppable = h->nal_ref_idc == 0; if (h->sps.frame_mbs_only_flag) { h->picture_structure = PICT_FRAME; } else { if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) { av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n"); return -1; } field_pic_flag = get_bits1(&h->gb); if (field_pic_flag) { bottom_field_flag = get_bits1(&h->gb); h->picture_structure = PICT_TOP_FIELD + bottom_field_flag; } else { h->picture_structure = PICT_FRAME; h->mb_aff_frame = h->sps.mb_aff; } } h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME; if (h0->current_slice != 0) { if (last_pic_structure != h->picture_structure || last_pic_droppable != h->droppable) { av_log(h->avctx, AV_LOG_ERROR, "Changing field mode (%d -> %d) between slices is not allowed\n", last_pic_structure, h->picture_structure); h->picture_structure = last_pic_structure; h->droppable = last_pic_droppable; return AVERROR_INVALIDDATA; } else if (!h0->cur_pic_ptr) { av_log(h->avctx, AV_LOG_ERROR, "unset cur_pic_ptr on slice %d\n", h0->current_slice + 1); return AVERROR_INVALIDDATA; } } else { /* Shorten frame num gaps so we don't have to allocate reference * frames just to throw them away */ if (h->frame_num != h->prev_frame_num) { int unwrap_prev_frame_num = h->prev_frame_num; int max_frame_num = 1 << h->sps.log2_max_frame_num; if (unwrap_prev_frame_num > h->frame_num) unwrap_prev_frame_num -= max_frame_num; if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) { unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1; if (unwrap_prev_frame_num < 0) unwrap_prev_frame_num += max_frame_num; h->prev_frame_num = unwrap_prev_frame_num; } } /* See if we have a decoded first field looking for a pair... * Here, we're using that to see if we should mark previously * decode frames as "finished". * We have to do that before the "dummy" in-between frame allocation, * since that can modify h->cur_pic_ptr. */ if (h0->first_field) { assert(h0->cur_pic_ptr); assert(h0->cur_pic_ptr->f.buf[0]); assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF); /* Mark old field/frame as completed */ if (h0->cur_pic_ptr->tf.owner == h0->avctx) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, last_pic_structure == PICT_BOTTOM_FIELD); } /* figure out if we have a complementary field pair */ if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) { /* Previous field is unmatched. Don't display it, but let it * remain for reference if marked as such. */ if (last_pic_structure != PICT_FRAME) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, last_pic_structure == PICT_TOP_FIELD); } } else { if (h0->cur_pic_ptr->frame_num != h->frame_num) { /* This and previous field were reference, but had * different frame_nums. Consider this field first in * pair. Throw away previous field except for reference * purposes. */ if (last_pic_structure != PICT_FRAME) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, last_pic_structure == PICT_TOP_FIELD); } } else { /* Second field in complementary pair */ if (!((last_pic_structure == PICT_TOP_FIELD && h->picture_structure == PICT_BOTTOM_FIELD) || (last_pic_structure == PICT_BOTTOM_FIELD && h->picture_structure == PICT_TOP_FIELD))) { av_log(h->avctx, AV_LOG_ERROR, "Invalid field mode combination %d/%d\n", last_pic_structure, h->picture_structure); h->picture_structure = last_pic_structure; h->droppable = last_pic_droppable; return AVERROR_INVALIDDATA; } else if (last_pic_droppable != h->droppable) { avpriv_request_sample(h->avctx, "Found reference and non-reference fields in the same frame, which"); h->picture_structure = last_pic_structure; h->droppable = last_pic_droppable; return AVERROR_PATCHWELCOME; } } } } while (h->frame_num != h->prev_frame_num && !h0->first_field && h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) { H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL; av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num); if (!h->sps.gaps_in_frame_num_allowed_flag) for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++) h->last_pocs[i] = INT_MIN; ret = h264_frame_start(h); if (ret < 0) { h0->first_field = 0; return ret; } h->prev_frame_num++; h->prev_frame_num %= 1 << h->sps.log2_max_frame_num; h->cur_pic_ptr->frame_num = h->prev_frame_num; h->cur_pic_ptr->invalid_gap = !h->sps.gaps_in_frame_num_allowed_flag; ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0); ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1); ret = ff_generate_sliding_window_mmcos(h, 1); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) return ret; ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) return ret; /* Error concealment: If a ref is missing, copy the previous ref * in its place. * FIXME: Avoiding a memcpy would be nice, but ref handling makes * many assumptions about there being no actual duplicates. * FIXME: This does not copy padding for out-of-frame motion * vectors. Given we are concealing a lost frame, this probably * is not noticeable by comparison, but it should be fixed. */ if (h->short_ref_count) { if (prev) { av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize, (const uint8_t **)prev->f.data, prev->f.linesize, h->avctx->pix_fmt, h->mb_width * 16, h->mb_height * 16); h->short_ref[0]->poc = prev->poc + 2; } h->short_ref[0]->frame_num = h->prev_frame_num; } } /* See if we have a decoded first field looking for a pair... * We're using that to see whether to continue decoding in that * frame, or to allocate a new one. */ if (h0->first_field) { assert(h0->cur_pic_ptr); assert(h0->cur_pic_ptr->f.buf[0]); assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF); /* figure out if we have a complementary field pair */ if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) { /* Previous field is unmatched. Don't display it, but let it * remain for reference if marked as such. */ h0->cur_pic_ptr = NULL; h0->first_field = FIELD_PICTURE(h); } else { if (h0->cur_pic_ptr->frame_num != h->frame_num) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, h0->picture_structure==PICT_BOTTOM_FIELD); /* This and the previous field had different frame_nums. * Consider this field first in pair. Throw away previous * one except for reference purposes. */ h0->first_field = 1; h0->cur_pic_ptr = NULL; } else { /* Second field in complementary pair */ h0->first_field = 0; } } } else { /* Frame or first field in a potentially complementary pair */ h0->first_field = FIELD_PICTURE(h); } if (!FIELD_PICTURE(h) || h0->first_field) { if (h264_frame_start(h) < 0) { h0->first_field = 0; return AVERROR_INVALIDDATA; } } else { release_unused_pictures(h, 0); } /* Some macroblocks can be accessed before they're available in case * of lost slices, MBAFF or threading. */ if (FIELD_PICTURE(h)) { for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++) memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table)); } else { memset(h->slice_table, -1, (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table)); } h0->last_slice_type = -1; } if (h != h0 && (ret = clone_slice(h, h0)) < 0) return ret; /* can't be in alloc_tables because linesize isn't known there. * FIXME: redo bipred weight to not require extra buffer? */ for (i = 0; i < h->slice_context_count; i++) if (h->thread_context[i]) { ret = alloc_scratch_buffers(h->thread_context[i], h->linesize); if (ret < 0) return ret; } h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup av_assert1(h->mb_num == h->mb_width * h->mb_height); if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num || first_mb_in_slice >= h->mb_num) { av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n"); return AVERROR_INVALIDDATA; } h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width; h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) << FIELD_OR_MBAFF_PICTURE(h); if (h->picture_structure == PICT_BOTTOM_FIELD) h->resync_mb_y = h->mb_y = h->mb_y + 1; av_assert1(h->mb_y < h->mb_height); if (h->picture_structure == PICT_FRAME) { h->curr_pic_num = h->frame_num; h->max_pic_num = 1 << h->sps.log2_max_frame_num; } else { h->curr_pic_num = 2 * h->frame_num + 1; h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1); } if (h->nal_unit_type == NAL_IDR_SLICE) get_ue_golomb(&h->gb); /* idr_pic_id */ if (h->sps.poc_type == 0) { h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb); if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME) h->delta_poc_bottom = get_se_golomb(&h->gb); } if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) { h->delta_poc[0] = get_se_golomb(&h->gb); if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME) h->delta_poc[1] = get_se_golomb(&h->gb); } ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc); if (h->pps.redundant_pic_cnt_present) h->redundant_pic_count = get_ue_golomb(&h->gb); ret = ff_set_ref_count(h); if (ret < 0) return ret; if (slice_type != AV_PICTURE_TYPE_I && (h0->current_slice == 0 || slice_type != h0->last_slice_type || memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) { ff_h264_fill_default_ref_list(h); } if (h->slice_type_nos != AV_PICTURE_TYPE_I) { ret = ff_h264_decode_ref_pic_list_reordering(h); if (ret < 0) { h->ref_count[1] = h->ref_count[0] = 0; return ret; } } if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) || (h->pps.weighted_bipred_idc == 1 && h->slice_type_nos == AV_PICTURE_TYPE_B)) ff_pred_weight_table(h); else if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) { implicit_weight_table(h, -1); } else { h->use_weight = 0; for (i = 0; i < 2; i++) { h->luma_weight_flag[i] = 0; h->chroma_weight_flag[i] = 0; } } // If frame-mt is enabled, only update mmco tables for the first slice // in a field. Subsequent slices can temporarily clobber h->mmco_index // or h->mmco, which will cause ref list mix-ups and decoding errors // further down the line. This may break decoding if the first slice is // corrupt, thus we only do this if frame-mt is enabled. if (h->nal_ref_idc) { ret = ff_h264_decode_ref_pic_marking(h0, &h->gb, !(h->avctx->active_thread_type & FF_THREAD_FRAME) || h0->current_slice == 0); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) return AVERROR_INVALIDDATA; } if (FRAME_MBAFF(h)) { ff_h264_fill_mbaff_ref_list(h); if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) { implicit_weight_table(h, 0); implicit_weight_table(h, 1); } } if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred) ff_h264_direct_dist_scale_factor(h); ff_h264_direct_ref_list_init(h); if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) { tmp = get_ue_golomb_31(&h->gb); if (tmp > 2) { av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp); return AVERROR_INVALIDDATA; } h->cabac_init_idc = tmp; } h->last_qscale_diff = 0; tmp = h->pps.init_qp + get_se_golomb(&h->gb); if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) { av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp); return AVERROR_INVALIDDATA; } h->qscale = tmp; h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale); h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale); // FIXME qscale / qp ... stuff if (h->slice_type == AV_PICTURE_TYPE_SP) get_bits1(&h->gb); /* sp_for_switch_flag */ if (h->slice_type == AV_PICTURE_TYPE_SP || h->slice_type == AV_PICTURE_TYPE_SI) get_se_golomb(&h->gb); /* slice_qs_delta */ h->deblocking_filter = 1; h->slice_alpha_c0_offset = 0; h->slice_beta_offset = 0; if (h->pps.deblocking_filter_parameters_present) { tmp = get_ue_golomb_31(&h->gb); if (tmp > 2) { av_log(h->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp); return AVERROR_INVALIDDATA; } h->deblocking_filter = tmp; if (h->deblocking_filter < 2) h->deblocking_filter ^= 1; // 1<->0 if (h->deblocking_filter) { h->slice_alpha_c0_offset = get_se_golomb(&h->gb) * 2; h->slice_beta_offset = get_se_golomb(&h->gb) * 2; if (h->slice_alpha_c0_offset > 12 || h->slice_alpha_c0_offset < -12 || h->slice_beta_offset > 12 || h->slice_beta_offset < -12) { av_log(h->avctx, AV_LOG_ERROR, "deblocking filter parameters %d %d out of range\n", h->slice_alpha_c0_offset, h->slice_beta_offset); return AVERROR_INVALIDDATA; } } } if (h->avctx->skip_loop_filter >= AVDISCARD_ALL || (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->nal_unit_type != NAL_IDR_SLICE) || (h->avctx->skip_loop_filter >= AVDISCARD_NONINTRA && h->slice_type_nos != AV_PICTURE_TYPE_I) || (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR && h->slice_type_nos == AV_PICTURE_TYPE_B) || (h->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0)) h->deblocking_filter = 0; if (h->deblocking_filter == 1 && h0->max_contexts > 1) { if (h->avctx->flags2 & CODEC_FLAG2_FAST) { /* Cheat slightly for speed: * Do not bother to deblock across slices. */ h->deblocking_filter = 2; } else { h0->max_contexts = 1; if (!h0->single_decode_warning) { av_log(h->avctx, AV_LOG_INFO, "Cannot parallelize slice decoding with deblocking filter type 1, decoding such frames in sequential order\n" "To parallelize slice decoding you need video encoded with disable_deblocking_filter_idc set to 2 (deblock only edges that do not cross slices).\n" "Setting the flags2 libavcodec option to +fast (-flags2 +fast) will disable deblocking across slices and enable parallel slice decoding " "but will generate non-standard-compliant output.\n"); h0->single_decode_warning = 1; } if (h != h0) { av_log(h->avctx, AV_LOG_ERROR, "Deblocking switched inside frame.\n"); return SLICE_SINGLETHREAD; } } } h->qp_thresh = 15 - FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) - FFMAX3(0, h->pps.chroma_qp_index_offset[0], h->pps.chroma_qp_index_offset[1]) + 6 * (h->sps.bit_depth_luma - 8); h0->last_slice_type = slice_type; memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count)); h->slice_num = ++h0->current_slice; if (h->slice_num) h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y; if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y && h->slice_num >= MAX_SLICES) { //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", h->slice_num, MAX_SLICES); } for (j = 0; j < 2; j++) { int id_list[16]; int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j]; for (i = 0; i < 16; i++) { id_list[i] = 60; if (j < h->list_count && i < h->ref_count[j] && h->ref_list[j][i].f.buf[0]) { int k; AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer; for (k = 0; k < h->short_ref_count; k++) if (h->short_ref[k]->f.buf[0]->buffer == buf) { id_list[i] = k; break; } for (k = 0; k < h->long_ref_count; k++) if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) { id_list[i] = h->short_ref_count + k; break; } } } ref2frm[0] = ref2frm[1] = -1; for (i = 0; i < 16; i++) ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3); ref2frm[18 + 0] = ref2frm[18 + 1] = -1; for (i = 16; i < 48; i++) ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] + (h->ref_list[j][i].reference & 3); } #if CONFIG_ERROR_RESILIENCE if (h->ref_count[0]) ff_h264_set_erpic(&h->er.last_pic, &h->ref_list[0][0]); if (h->ref_count[1]) ff_h264_set_erpic(&h->er.next_pic, &h->ref_list[1][0]); #endif h->er.ref_count = h->ref_count[0]; h0->au_pps_id = pps_id; h->sps.new = h0->sps_buffers[h->pps.sps_id]->new = 0; h->current_sps_id = h->pps.sps_id; if (h->avctx->debug & FF_DEBUG_PICT_INFO) { av_log(h->avctx, AV_LOG_DEBUG, "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n", h->slice_num, (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"), first_mb_in_slice, av_get_picture_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "", pps_id, h->frame_num, h->cur_pic_ptr->field_poc[0], h->cur_pic_ptr->field_poc[1], h->ref_count[0], h->ref_count[1], h->qscale, h->deblocking_filter, h->slice_alpha_c0_offset, h->slice_beta_offset, h->use_weight, h->use_weight == 1 && h->use_weight_chroma ? "c" : "", h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""); } return 0; } int ff_h264_get_slice_type(const H264Context *h) { switch (h->slice_type) { case AV_PICTURE_TYPE_P: return 0; case AV_PICTURE_TYPE_B: return 1; case AV_PICTURE_TYPE_I: return 2; case AV_PICTURE_TYPE_SP: return 3; case AV_PICTURE_TYPE_SI: return 4; default: return AVERROR_INVALIDDATA; } } static av_always_inline void fill_filter_caches_inter(H264Context *h, int mb_type, int top_xy, int left_xy[LEFT_MBS], int top_type, int left_type[LEFT_MBS], int mb_xy, int list) { int b_stride = h->b_stride; int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]]; int8_t *ref_cache = &h->ref_cache[list][scan8[0]]; if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) { if (USES_LIST(top_type, list)) { const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride; const int b8_xy = 4 * top_xy + 2; int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2)); AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]); ref_cache[0 - 1 * 8] = ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]]; ref_cache[2 - 1 * 8] = ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]]; } else { AV_ZERO128(mv_dst - 1 * 8); AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u); } if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) { if (USES_LIST(left_type[LTOP], list)) { const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3; const int b8_xy = 4 * left_xy[LTOP] + 1; int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2)); AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]); AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]); AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]); AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]); ref_cache[-1 + 0] = ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]]; ref_cache[-1 + 16] = ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]]; } else { AV_ZERO32(mv_dst - 1 + 0); AV_ZERO32(mv_dst - 1 + 8); AV_ZERO32(mv_dst - 1 + 16); AV_ZERO32(mv_dst - 1 + 24); ref_cache[-1 + 0] = ref_cache[-1 + 8] = ref_cache[-1 + 16] = ref_cache[-1 + 24] = LIST_NOT_USED; } } } if (!USES_LIST(mb_type, list)) { fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4); AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u); AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u); AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u); AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u); return; } { int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy]; int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2)); uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101; uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101; AV_WN32A(&ref_cache[0 * 8], ref01); AV_WN32A(&ref_cache[1 * 8], ref01); AV_WN32A(&ref_cache[2 * 8], ref23); AV_WN32A(&ref_cache[3 * 8], ref23); } { int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride]; AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride); AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride); AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride); AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride); } } /** * * @return non zero if the loop filter can be skipped */ static int fill_filter_caches(H264Context *h, int mb_type) { const int mb_xy = h->mb_xy; int top_xy, left_xy[LEFT_MBS]; int top_type, left_type[LEFT_MBS]; uint8_t *nnz; uint8_t *nnz_cache; top_xy = mb_xy - (h->mb_stride << MB_FIELD(h)); /* Wow, what a mess, why didn't they simplify the interlacing & intra * stuff, I can't imagine that these complex rules are worth it. */ left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1; if (FRAME_MBAFF(h)) { const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]); const int curr_mb_field_flag = IS_INTERLACED(mb_type); if (h->mb_y & 1) { if (left_mb_field_flag != curr_mb_field_flag) left_xy[LTOP] -= h->mb_stride; } else { if (curr_mb_field_flag) top_xy += h->mb_stride & (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1); if (left_mb_field_flag != curr_mb_field_flag) left_xy[LBOT] += h->mb_stride; } } h->top_mb_xy = top_xy; h->left_mb_xy[LTOP] = left_xy[LTOP]; h->left_mb_xy[LBOT] = left_xy[LBOT]; { /* For sufficiently low qp, filtering wouldn't do anything. * This is a conservative estimate: could also check beta_offset * and more accurate chroma_qp. */ int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice int qp = h->cur_pic.qscale_table[mb_xy]; if (qp <= qp_thresh && (left_xy[LTOP] < 0 || ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) && (top_xy < 0 || ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) { if (!FRAME_MBAFF(h)) return 1; if ((left_xy[LTOP] < 0 || ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) && (top_xy < h->mb_stride || ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh)) return 1; } } top_type = h->cur_pic.mb_type[top_xy]; left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]]; left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]]; if (h->deblocking_filter == 2) { if (h->slice_table[top_xy] != h->slice_num) top_type = 0; if (h->slice_table[left_xy[LBOT]] != h->slice_num) left_type[LTOP] = left_type[LBOT] = 0; } else { if (h->slice_table[top_xy] == 0xFFFF) top_type = 0; if (h->slice_table[left_xy[LBOT]] == 0xFFFF) left_type[LTOP] = left_type[LBOT] = 0; } h->top_type = top_type; h->left_type[LTOP] = left_type[LTOP]; h->left_type[LBOT] = left_type[LBOT]; if (IS_INTRA(mb_type)) return 0; fill_filter_caches_inter(h, mb_type, top_xy, left_xy, top_type, left_type, mb_xy, 0); if (h->list_count == 2) fill_filter_caches_inter(h, mb_type, top_xy, left_xy, top_type, left_type, mb_xy, 1); nnz = h->non_zero_count[mb_xy]; nnz_cache = h->non_zero_count_cache; AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]); AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]); AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]); AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]); h->cbp = h->cbp_table[mb_xy]; if (top_type) { nnz = h->non_zero_count[top_xy]; AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]); } if (left_type[LTOP]) { nnz = h->non_zero_count[left_xy[LTOP]]; nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4]; nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4]; nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4]; nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4]; } /* CAVLC 8x8dct requires NNZ values for residual decoding that differ * from what the loop filter needs */ if (!CABAC(h) && h->pps.transform_8x8_mode) { if (IS_8x8DCT(top_type)) { nnz_cache[4 + 8 * 0] = nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12; nnz_cache[6 + 8 * 0] = nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12; } if (IS_8x8DCT(left_type[LTOP])) { nnz_cache[3 + 8 * 1] = nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF } if (IS_8x8DCT(left_type[LBOT])) { nnz_cache[3 + 8 * 3] = nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF } if (IS_8x8DCT(mb_type)) { nnz_cache[scan8[0]] = nnz_cache[scan8[1]] = nnz_cache[scan8[2]] = nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12; nnz_cache[scan8[0 + 4]] = nnz_cache[scan8[1 + 4]] = nnz_cache[scan8[2 + 4]] = nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12; nnz_cache[scan8[0 + 8]] = nnz_cache[scan8[1 + 8]] = nnz_cache[scan8[2 + 8]] = nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12; nnz_cache[scan8[0 + 12]] = nnz_cache[scan8[1 + 12]] = nnz_cache[scan8[2 + 12]] = nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12; } } return 0; } static void loop_filter(H264Context *h, int start_x, int end_x) { uint8_t *dest_y, *dest_cb, *dest_cr; int linesize, uvlinesize, mb_x, mb_y; const int end_mb_y = h->mb_y + FRAME_MBAFF(h); const int old_slice_type = h->slice_type; const int pixel_shift = h->pixel_shift; const int block_h = 16 >> h->chroma_y_shift; if (h->deblocking_filter) { for (mb_x = start_x; mb_x < end_x; mb_x++) for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) { int mb_xy, mb_type; mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride; h->slice_num = h->slice_table[mb_xy]; mb_type = h->cur_pic.mb_type[mb_xy]; h->list_count = h->list_counts[mb_xy]; if (FRAME_MBAFF(h)) h->mb_mbaff = h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type); h->mb_x = mb_x; h->mb_y = mb_y; dest_y = h->cur_pic.f.data[0] + ((mb_x << pixel_shift) + mb_y * h->linesize) * 16; dest_cb = h->cur_pic.f.data[1] + (mb_x << pixel_shift) * (8 << CHROMA444(h)) + mb_y * h->uvlinesize * block_h; dest_cr = h->cur_pic.f.data[2] + (mb_x << pixel_shift) * (8 << CHROMA444(h)) + mb_y * h->uvlinesize * block_h; // FIXME simplify above if (MB_FIELD(h)) { linesize = h->mb_linesize = h->linesize * 2; uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2; if (mb_y & 1) { // FIXME move out of this function? dest_y -= h->linesize * 15; dest_cb -= h->uvlinesize * (block_h - 1); dest_cr -= h->uvlinesize * (block_h - 1); } } else { linesize = h->mb_linesize = h->linesize; uvlinesize = h->mb_uvlinesize = h->uvlinesize; } backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0); if (fill_filter_caches(h, mb_type)) continue; h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]); h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]); if (FRAME_MBAFF(h)) { ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize); } else { ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize); } } } h->slice_type = old_slice_type; h->mb_x = end_x; h->mb_y = end_mb_y - FRAME_MBAFF(h); h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale); h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale); } static void predict_field_decoding_flag(H264Context *h) { const int mb_xy = h->mb_x + h->mb_y * h->mb_stride; int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ? h->cur_pic.mb_type[mb_xy - 1] : (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ? h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0; h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0; } /** * Draw edges and report progress for the last MB row. */ static void decode_finish_row(H264Context *h) { int top = 16 * (h->mb_y >> FIELD_PICTURE(h)); int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h); int height = 16 << FRAME_MBAFF(h); int deblock_border = (16 + 4) << FRAME_MBAFF(h); if (h->deblocking_filter) { if ((top + height) >= pic_height) height += deblock_border; top -= deblock_border; } if (top >= pic_height || (top + height) < 0) return; height = FFMIN(height, pic_height - top); if (top < 0) { height = top + height; top = 0; } ff_h264_draw_horiz_band(h, top, height); if (h->droppable || h->er.error_occurred) return; ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1, h->picture_structure == PICT_BOTTOM_FIELD); } static void er_add_slice(H264Context *h, int startx, int starty, int endx, int endy, int status) { if (CONFIG_ERROR_RESILIENCE) { ERContext *er = &h->er; ff_er_add_slice(er, startx, starty, endx, endy, status); } } static int decode_slice(struct AVCodecContext *avctx, void *arg) { H264Context *h = *(void **)arg; int lf_x_start = h->mb_x; h->mb_skip_run = -1; av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * h->linesize * ((scan8[15] - scan8[0]) >> 3)); h->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME || avctx->codec_id != AV_CODEC_ID_H264 || (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY)); if (!(h->avctx->active_thread_type & FF_THREAD_SLICE) && h->picture_structure == PICT_FRAME && h->er.error_status_table) { const int start_i = av_clip(h->resync_mb_x + h->resync_mb_y * h->mb_width, 0, h->mb_num - 1); if (start_i) { int prev_status = h->er.error_status_table[h->er.mb_index2xy[start_i - 1]]; prev_status &= ~ VP_START; if (prev_status != (ER_MV_END | ER_DC_END | ER_AC_END)) h->er.error_occurred = 1; } } if (h->pps.cabac) { /* realign */ align_get_bits(&h->gb); /* init cabac */ ff_init_cabac_decoder(&h->cabac, h->gb.buffer + get_bits_count(&h->gb) / 8, (get_bits_left(&h->gb) + 7) / 8); ff_h264_init_cabac_states(h); for (;;) { // START_TIMER int ret = ff_h264_decode_mb_cabac(h); int eos; // STOP_TIMER("decode_mb_cabac") if (ret >= 0) ff_h264_hl_decode_mb(h); // FIXME optimal? or let mb_decode decode 16x32 ? if (ret >= 0 && FRAME_MBAFF(h)) { h->mb_y++; ret = ff_h264_decode_mb_cabac(h); if (ret >= 0) ff_h264_hl_decode_mb(h); h->mb_y--; } eos = get_cabac_terminate(&h->cabac); if ((h->workaround_bugs & FF_BUG_TRUNCATED) && h->cabac.bytestream > h->cabac.bytestream_end + 2) { er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1, h->mb_y, ER_MB_END); if (h->mb_x >= lf_x_start) loop_filter(h, lf_x_start, h->mb_x + 1); return 0; } if (h->cabac.bytestream > h->cabac.bytestream_end + 2 ) av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %"PTRDIFF_SPECIFIER"\n", h->cabac.bytestream_end - h->cabac.bytestream); if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) { av_log(h->avctx, AV_LOG_ERROR, "error while decoding MB %d %d, bytestream %"PTRDIFF_SPECIFIER"\n", h->mb_x, h->mb_y, h->cabac.bytestream_end - h->cabac.bytestream); er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x, h->mb_y, ER_MB_ERROR); return AVERROR_INVALIDDATA; } if (++h->mb_x >= h->mb_width) { loop_filter(h, lf_x_start, h->mb_x); h->mb_x = lf_x_start = 0; decode_finish_row(h); ++h->mb_y; if (FIELD_OR_MBAFF_PICTURE(h)) { ++h->mb_y; if (FRAME_MBAFF(h) && h->mb_y < h->mb_height) predict_field_decoding_flag(h); } } if (eos || h->mb_y >= h->mb_height) { tprintf(h->avctx, "slice end %d %d\n", get_bits_count(&h->gb), h->gb.size_in_bits); er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1, h->mb_y, ER_MB_END); if (h->mb_x > lf_x_start) loop_filter(h, lf_x_start, h->mb_x); return 0; } } } else { for (;;) { int ret = ff_h264_decode_mb_cavlc(h); if (ret >= 0) ff_h264_hl_decode_mb(h); // FIXME optimal? or let mb_decode decode 16x32 ? if (ret >= 0 && FRAME_MBAFF(h)) { h->mb_y++; ret = ff_h264_decode_mb_cavlc(h); if (ret >= 0) ff_h264_hl_decode_mb(h); h->mb_y--; } if (ret < 0) { av_log(h->avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", h->mb_x, h->mb_y); er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x, h->mb_y, ER_MB_ERROR); return ret; } if (++h->mb_x >= h->mb_width) { loop_filter(h, lf_x_start, h->mb_x); h->mb_x = lf_x_start = 0; decode_finish_row(h); ++h->mb_y; if (FIELD_OR_MBAFF_PICTURE(h)) { ++h->mb_y; if (FRAME_MBAFF(h) && h->mb_y < h->mb_height) predict_field_decoding_flag(h); } if (h->mb_y >= h->mb_height) { tprintf(h->avctx, "slice end %d %d\n", get_bits_count(&h->gb), h->gb.size_in_bits); if ( get_bits_left(&h->gb) == 0 || get_bits_left(&h->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) { er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1, h->mb_y, ER_MB_END); return 0; } else { er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x, h->mb_y, ER_MB_END); return AVERROR_INVALIDDATA; } } } if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) { tprintf(h->avctx, "slice end %d %d\n", get_bits_count(&h->gb), h->gb.size_in_bits); if (get_bits_left(&h->gb) == 0) { er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1, h->mb_y, ER_MB_END); if (h->mb_x > lf_x_start) loop_filter(h, lf_x_start, h->mb_x); return 0; } else { er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x, h->mb_y, ER_MB_ERROR); return AVERROR_INVALIDDATA; } } } } } /** * Call decode_slice() for each context. * * @param h h264 master context * @param context_count number of contexts to execute */ int ff_h264_execute_decode_slices(H264Context *h, unsigned context_count) { AVCodecContext *const avctx = h->avctx; H264Context *hx; int i; av_assert0(h->mb_y < h->mb_height); if (h->avctx->hwaccel || h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) return 0; if (context_count == 1) { return decode_slice(avctx, &h); } else { av_assert0(context_count > 0); for (i = 1; i < context_count; i++) { hx = h->thread_context[i]; if (CONFIG_ERROR_RESILIENCE) { hx->er.error_count = 0; } hx->x264_build = h->x264_build; } avctx->execute(avctx, decode_slice, h->thread_context, NULL, context_count, sizeof(void *)); /* pull back stuff from slices to master context */ hx = h->thread_context[context_count - 1]; h->mb_x = hx->mb_x; h->mb_y = hx->mb_y; h->droppable = hx->droppable; h->picture_structure = hx->picture_structure; if (CONFIG_ERROR_RESILIENCE) { for (i = 1; i < context_count; i++) h->er.error_count += h->thread_context[i]->er.error_count; } } return 0; }
mxOBS/deb-pkg_trusty_chromium-browser
third_party/ffmpeg/libavcodec/h264_slice.c
C
bsd-3-clause
99,699
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-31 14:26 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('news', '0010_auto_20170530_1509'), ] operations = [ migrations.AddField( model_name='corpus', name='date_ended', field=models.DateField(blank=True, null=True, verbose_name='date ended'), ), migrations.AlterField( model_name='corpus', name='date_started', field=models.DateField(verbose_name='date started'), ), ]
GeorgiaTechDHLab/TOME
news/migrations/0011_auto_20170531_1426.py
Python
bsd-3-clause
658
require 'baf/cli' require 'forwardable' require 'logger' require 'optparse' require 'rbconfig' require 'uh' require 'uh/wm/env_logging' require 'uh/wm/actions_handler' require 'uh/wm/cli' require 'uh/wm/client' require 'uh/wm/dispatcher' require 'uh/wm/env' require 'uh/wm/launcher' require 'uh/wm/logger_formatter' require 'uh/wm/manager' require 'uh/wm/run_control' require 'uh/wm/runner' require 'uh/wm/version' require 'uh/wm/workers' require 'uh/wm/workers/base' require 'uh/wm/workers/blocking' require 'uh/wm/workers/kqueue' unless RbConfig::CONFIG['host_os'] =~ /linux/i require 'uh/wm/workers/mux' require 'uh/wm/x_event_logger' module Uh module WM Error = Class.new(StandardError) RuntimeError = Class.new(RuntimeError) ArgumentError = Class.new(Error) RunControlEvaluationError = Class.new(RuntimeError) RunControlArgumentError = Class.new(ArgumentError) class OtherWMRunningError < RuntimeError def initialize *_ super 'another window manager is already running' end end end end
tjouan/uh-wm
lib/uh/wm.rb
Ruby
bsd-3-clause
1,094
package expo.modules.medialibrary; import android.content.Context; import android.os.AsyncTask; import android.provider.MediaStore; import android.text.TextUtils; import org.unimodules.core.Promise; import static expo.modules.medialibrary.MediaLibraryUtils.deleteAssets; class DeleteAssets extends AsyncTask<Void, Void, Void> { private final Context mContext; private final String[] mAssetsId; private final Promise mPromise; DeleteAssets(Context context, String[] assetsId, Promise promise) { mContext = context; mAssetsId = assetsId; mPromise = promise; } @Override protected Void doInBackground(Void... params) { final String selection = MediaStore.Images.Media._ID + " IN (" + TextUtils.join(",", mAssetsId) + " )"; final String[] selectionArgs = null; deleteAssets(mContext, selection, selectionArgs, mPromise); return null; } }
exponent/exponent
packages/expo-media-library/android/src/main/java/expo/modules/medialibrary/DeleteAssets.java
Java
bsd-3-clause
885
## 作用 用gulp实现webpac的部分功能,gulp的底层、webpack的方便易用两不误 * 通过配置gbuilder.config.js文件实现任务的编译、执行 ##GITHUB源码地址: https://github.com/happyhour7/gbuilder.git ##基本说明: gbuilder最简单的地方在于:如果有人配置好了环境后,自己只需要安装gbuilder、配置好的gbuilder.config.js以及执行npm install即可。就算没有配置好,也不需要自己写gulp.task,gulp.watch之类的大量重复代码,也不用手动require各种gulp支持包。 ##静态资源项目初始化:jbuilder.config.js、package.json,初始化的package.json中包含了尽量多的支持不同开发技术的与处理器 ```bash $ gbuilder :init $ npm run win-setup[linux-setup] ``` ##gbuilder.config.js配置文件 ```js "use strict"; var localPath = process.cwd(); //当前路径 var buildPath = ""; //静态文件输出目录 var buildPathCss=""; var gBuilderConfig = { tasks: { "main-js": { modules: [{ path: "./js/home/login.jsx"[, name: "main"] }, { path: "./js/home/login.jsx", name: "findPwd" }],//不加name配置意为将文件直接打包,不需要require模块名即可使用 buildTo: buildPath, exportFileName: "index.js", compress: false, loaders: ["js", "react"] }, "cssTaskName":{ modules: ['./stylus/usercenternew.styl'], //css文件集 type:"stylus", //文件类型支持:stylus,css,postcss,less buildTo: buildPathCss, //编译到的路径 compress: false, //是否压缩 loaders: ["css","autoprefixer","rucksack"] //postcss,processers } }, watches: { "main-watch": [ {src: ['./js/home/*.js', './js/home/**/*.js'],task: "main-js"} ] } }; module.exports = gBuilderConfig; ``` ## 安装 将developerjs安装到本地计算机 ```bash $ npm install -g gbuilder ``` ## 重新编译 gbuilder采用es6编写,使用babel进行编译 ```bash $ npm run build ``` ## 关于css预编译 目前支持的语法:stylus、less、css 目前支持的postcss插件:autoprefixer、rucksack、precss ###0.1.25版本无法支持postcss插件配置,会在后续版本中体现。 ## 更新记录 2016-12-19 0.1.18版本:实现单一js编译任务、js的watcher任务配置; 2016-12-19 0.1.19版本:前版基础上更新了readme文件; 2016-12-19 0.1.25版本:前版基础上增加了css预编译功能,支持stylus,css,postcss,less; 2016-12-19 0.1.33版本:前版基础上解决了windows平台上路径错误问题; 2016-12-19 0.1.34版本:前版基础上解决了precss编译bug; 2016-12-19 0.1.36版本:前版基础上解决了配置文件配置错误; 2017-1-3 0.1.48版本:前版基础上增加了支持直接压缩文件名而不加模块名的打包方式 2017-1-4 0.1.49版本:前版基础上删除了对iview组件对依赖,所有iview组件放到前端项目中处理 2017-1-4 0.1.50版本:前版基础上增加了stone开发模式,(vue+angularjs1.0的各种抄袭简化)😄 ## License [BSD]快快来贡献😄(LICENSE)
happyhour7/gbuilder
README.md
Markdown
bsd-3-clause
3,344
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Orchard.UI.Navigation; using Orchard.Localization; using Zveen.MultiMenu.Services; using System.Diagnostics; namespace Zveen.MultiMenu { public class AdminMenu : INavigationProvider { private readonly IMultiMenuService _multiMenuService; public AdminMenu(IMultiMenuService multiMenuService) { _multiMenuService = multiMenuService; } public Localizer T { get; set; } public string MenuName { get { return "admin"; } } public void GetNavigation(NavigationBuilder builder) { builder.AddImageSet("multi-menu").Add(T("Multi Menu"), "5", menu => menu.Add(T("Create New"), "5.1", item => item.Action("Create", "MultiMenuAdmin", new { area = "Zveen.MultiMenu" }))); Int32 i = 2; foreach (var menuPart in _multiMenuService.FetchMenus()) { builder.Add(T("Multi Menu"), "5", menu => menu.Add(T(menuPart.Title), "5." + i++.ToString(), item => item.Action("List", "MultiMenuAdmin", new { area = "Zveen.MultiMenu", idMultiMenu = menuPart.Id }))); } } } }
dminik/voda
Modules/Zveen.MultiMenu/AdminMenu.cs
C#
bsd-3-clause
1,218
<?php /** * Garp_Model_Validator_Email * Check if a value looks like a valid email address * @author Harmen Janssen | grrr.nl * @modifiedby $LastChangedBy: $ * @version $Revision: $ * @package Garp * @subpackage Validator * @lastmodified $Date: $ */ class Garp_Model_Validator_Email extends Garp_Model_Validator_Abstract { /** * The regular expression used to validate email addresses * @var String */ const EMAIL_REGEXP = '/^|\s([0-9a-zA-Z-_+]([-.\w]*[0-9a-zA-Z-_+])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$|\s/'; /** * Columns to check for emptiness * @var Array */ protected $_fields = array(); /** * Setup the validation environment * @param Array $config Configuration options * @return Void */ protected function _setup($config) { $this->_fields = $config; } /** * Validate wether the given columns are not empty * @param Array $data The data to validate * @param Boolean $onlyIfAvailable Wether to skip validation on fields that are not in the array * @return Void * @throws Garp_Model_Validator_Exception */ public function validate(array $data, Garp_Model_Db $model, $onlyIfAvailable = true) { $theColumns = $this->_fields; $regexp = self::EMAIL_REGEXP; $validate = function($c) use ($data, $onlyIfAvailable, $regexp) { if ( $onlyIfAvailable && ( !array_key_exists($c, $data) || empty($data[$c]) ) ) { return; } if (empty($data[$c]) || !preg_match($regexp, $data[$c])) { $value = !empty($data[$c]) ? $data[$c] : ''; $error = sprintf(__("'%value%' is not a valid email address in the basic format local-part@hostname"), $value); throw new Garp_Model_Validator_Email_Exception($error); } }; array_walk($theColumns, $validate); } }
grrr-amsterdam/golem
garp/library/Garp/Model/Validator/Email.php
PHP
bsd-3-clause
1,775
<?php namespace suralc\yii2\PureWidgets; class PureAssetConfig { const PURE_VERSION_DEFAULT = '0.4.2'; const CDN_NONE = false; const CDN_DEFAULT = self::CDN_NONE; const CDN_YAHOO = '//yui.yahooapis.com/pure/{version}/pure{min}.css'; const CDN_CDNJS = '//cdnjs.cloudflare.com/ajax/libs/pure/{version}/pure{min}.css'; const CDN_MAXCDN = '//oss.maxcdn.com/libs/pure/{version}/pure{min}.css'; const CDN_STATICFILE = 'http://cdn.staticfile.org/pure/{version}/pure{min}.css'; /** * Version to load * This is only relevant, if you use the yahoo-cdn * @var string */ public static $pureVersion = self::PURE_VERSION_DEFAULT; /** * Use the yahoo-cdn instead of the supplied files * @var bool|string */ public static $useCDN = self::CDN_DEFAULT; public static $useMinified = true; public static $disableAssetLoading = false; }
suralc/Yii2PureWidgets
src/PureAssetConfig.php
PHP
bsd-3-clause
907
import sys from . import ( utils, env, defs, context, layers, parser, preprocessor, loader, analyzer, generator) LAYERS = ( (parser.Parser, "parse"), (preprocessor.Preprocessor, "transform_ast"), (loader.Loader, "expand_ast"), (analyzer.Analyzer, "expand_ast"), (generator.Generator, "expand_ast") ) def _get_context_args_from_settings(string, settings): return { "main_file_hash": utils.get_string_hash(string), "main_file_name": settings["main_file_name"], "module_paths": settings["module_paths"], "loaded_modules": settings["loaded_modules"], "test_mode_on": settings["test_mode_on"], "env": env.Env() } def _update_context_args(): return {**context.modified_context_args(), **{"env": env.Env()}} def compile_string(string, **settings): context_args = _get_context_args_from_settings(string, settings) current_ast = string for layer_cls, method_name in LAYERS: if settings["stop_before"] == layer_cls: return current_ast with context.new_context(**context_args): layer = layer_cls() if method_name == "parse": current_ast = layer.parse(current_ast) else: new_ast = getattr(layers, method_name)( current_ast, registry=layer.get_registry()) if new_ast is not None: current_ast = list(new_ast) if settings["stop_after"] == layer_cls: return current_ast context_args = _update_context_args() return "\n".join(current_ast) #return current_ast def compile_file(in_file, **settings): result = compile_string( utils.read_file(in_file), main_file_name=in_file.split("/")[-1].split(".")[0], **settings) if settings["print_ast"]: for node in result: print(node) sys.exit(0) return result
adrian-lang/margolith
solyanka/solyanka/__init__.py
Python
bsd-3-clause
1,936
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Acl * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Acl.php 24594 2012-01-05 21:27:01Z matthew $ */ /** * @see Zend_Acl_Resource_Interface */ require_once 'Zend/Acl/Resource/Interface.php'; /** * @see Zend_Acl_Role_Registry */ require_once 'Zend/Acl/Role/Registry.php'; /** * @see Zend_Acl_Assert_Interface */ require_once 'Zend/Acl/Assert/Interface.php'; /** * @see Zend_Acl_Role */ require_once 'Zend/Acl/Role.php'; /** * @see Zend_Acl_Resource */ require_once 'Zend/Acl/Resource.php'; /** * @category Zend * @package Zend_Acl * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Acl { /** * Rule type: allow */ const TYPE_ALLOW = 'TYPE_ALLOW'; /** * Rule type: deny */ const TYPE_DENY = 'TYPE_DENY'; /** * Rule operation: add */ const OP_ADD = 'OP_ADD'; /** * Rule operation: remove */ const OP_REMOVE = 'OP_REMOVE'; /** * Role registry * * @var Zend_Acl_Role_Registry */ protected $_roleRegistry = null; /** * Resource tree * * @var array */ protected $_resources = array(); /** * @var Zend_Acl_Role_Interface */ protected $_isAllowedRole = null; /** * @var Zend_Acl_Resource_Interface */ protected $_isAllowedResource = null; /** * @var String */ protected $_isAllowedPrivilege = null; /** * ACL rules; whitelist (deny everything to all) by default * * @var array */ protected $_rules = array( 'allResources' => array( 'allRoles' => array( 'allPrivileges' => array( 'type' => self::TYPE_DENY, 'assert' => null ), 'byPrivilegeId' => array() ), 'byRoleId' => array() ), 'byResourceId' => array() ); /** * Adds a Role having an identifier unique to the registry * * The $parents parameter may be a reference to, or the string identifier for, * a Role existing in the registry, or $parents may be passed as an array of * these - mixing string identifiers and objects is ok - to indicate the Roles * from which the newly added Role will directly inherit. * * In order to resolve potential ambiguities with conflicting rules inherited * from different parents, the most recently added parent takes precedence over * parents that were previously added. In other words, the first parent added * will have the least priority, and the last parent added will have the * highest priority. * * @param Zend_Acl_Role_Interface $role * @param Zend_Acl_Role_Interface|string|array $parents * @uses Zend_Acl_Role_Registry::add() * @return Zend_Acl Provides a fluent interface */ public function addRole($role, $parents = null) { if (is_string($role)) { $role = new Zend_Acl_Role($role); } if (!$role instanceof Zend_Acl_Role_Interface) { require_once 'Zend/Acl/Exception.php'; throw new Zend_Acl_Exception('addRole() expects $role to be of type Zend_Acl_Role_Interface'); } $this->_getRoleRegistry()->add($role, $parents); return $this; } /** * Returns the identified Role * * The $role parameter can either be a Role or Role identifier. * * @param Zend_Acl_Role_Interface|string $role * @uses Zend_Acl_Role_Registry::get() * @return Zend_Acl_Role_Interface */ public function getRole($role) { return $this->_getRoleRegistry()->get($role); } /** * Returns true if and only if the Role exists in the registry * * The $role parameter can either be a Role or a Role identifier. * * @param Zend_Acl_Role_Interface|string $role * @uses Zend_Acl_Role_Registry::has() * @return boolean */ public function hasRole($role) { return $this->_getRoleRegistry()->has($role); } /** * Returns true if and only if $role inherits from $inherit * * Both parameters may be either a Role or a Role identifier. If * $onlyParents is true, then $role must inherit directly from * $inherit in order to return true. By default, this method looks * through the entire inheritance DAG to determine whether $role * inherits from $inherit through its ancestor Roles. * * @param Zend_Acl_Role_Interface|string $role * @param Zend_Acl_Role_Interface|string $inherit * @param boolean $onlyParents * @uses Zend_Acl_Role_Registry::inherits() * @return boolean */ public function inheritsRole($role, $inherit, $onlyParents = false) { return $this->_getRoleRegistry()->inherits($role, $inherit, $onlyParents); } /** * Removes the Role from the registry * * The $role parameter can either be a Role or a Role identifier. * * @param Zend_Acl_Role_Interface|string $role * @uses Zend_Acl_Role_Registry::remove() * @return Zend_Acl Provides a fluent interface */ public function removeRole($role) { $this->_getRoleRegistry()->remove($role); if ($role instanceof Zend_Acl_Role_Interface) { $roleId = $role->getRoleId(); } else { $roleId = $role; } foreach ($this->_rules['allResources']['byRoleId'] as $roleIdCurrent => $rules) { if ($roleId === $roleIdCurrent) { unset($this->_rules['allResources']['byRoleId'][$roleIdCurrent]); } } foreach ($this->_rules['byResourceId'] as $resourceIdCurrent => $visitor) { if (array_key_exists('byRoleId', $visitor)) { foreach ($visitor['byRoleId'] as $roleIdCurrent => $rules) { if ($roleId === $roleIdCurrent) { unset($this->_rules['byResourceId'][$resourceIdCurrent]['byRoleId'][$roleIdCurrent]); } } } } return $this; } /** * Removes all Roles from the registry * * @uses Zend_Acl_Role_Registry::removeAll() * @return Zend_Acl Provides a fluent interface */ public function removeRoleAll() { $this->_getRoleRegistry()->removeAll(); foreach ($this->_rules['allResources']['byRoleId'] as $roleIdCurrent => $rules) { unset($this->_rules['allResources']['byRoleId'][$roleIdCurrent]); } foreach ($this->_rules['byResourceId'] as $resourceIdCurrent => $visitor) { foreach ($visitor['byRoleId'] as $roleIdCurrent => $rules) { unset($this->_rules['byResourceId'][$resourceIdCurrent]['byRoleId'][$roleIdCurrent]); } } return $this; } /** * Adds a Resource having an identifier unique to the ACL * * The $parent parameter may be a reference to, or the string identifier for, * the existing Resource from which the newly added Resource will inherit. * * @param Zend_Acl_Resource_Interface|string $resource * @param Zend_Acl_Resource_Interface|string $parent * @throws Zend_Acl_Exception * @return Zend_Acl Provides a fluent interface */ public function addResource($resource, $parent = null) { if (is_string($resource)) { $resource = new Zend_Acl_Resource($resource); } if (!$resource instanceof Zend_Acl_Resource_Interface) { require_once 'Zend/Acl/Exception.php'; throw new Zend_Acl_Exception('addResource() expects $resource to be of type Zend_Acl_Resource_Interface'); } $resourceId = $resource->getResourceId(); if ($this->has($resourceId)) { require_once 'Zend/Acl/Exception.php'; throw new Zend_Acl_Exception("Resource id '$resourceId' already exists in the ACL"); } $resourceParent = null; if (null !== $parent) { try { if ($parent instanceof Zend_Acl_Resource_Interface) { $resourceParentId = $parent->getResourceId(); } else { $resourceParentId = $parent; } $resourceParent = $this->get($resourceParentId); } catch (Zend_Acl_Exception $e) { require_once 'Zend/Acl/Exception.php'; throw new Zend_Acl_Exception("Parent Resource id '$resourceParentId' does not exist", 0, $e); } $this->_resources[$resourceParentId]['children'][$resourceId] = $resource; } $this->_resources[$resourceId] = array( 'instance' => $resource, 'parent' => $resourceParent, 'children' => array() ); return $this; } /** * Adds a Resource having an identifier unique to the ACL * * The $parent parameter may be a reference to, or the string identifier for, * the existing Resource from which the newly added Resource will inherit. * * @deprecated in version 1.9.1 and will be available till 2.0. New code * should use addResource() instead. * * @param Zend_Acl_Resource_Interface $resource * @param Zend_Acl_Resource_Interface|string $parent * @throws Zend_Acl_Exception * @return Zend_Acl Provides a fluent interface */ public function add(Zend_Acl_Resource_Interface $resource, $parent = null) { return $this->addResource($resource, $parent); } /** * Returns the identified Resource * * The $resource parameter can either be a Resource or a Resource identifier. * * @param Zend_Acl_Resource_Interface|string $resource * @throws Zend_Acl_Exception * @return Zend_Acl_Resource_Interface */ public function get($resource) { if ($resource instanceof Zend_Acl_Resource_Interface) { $resourceId = $resource->getResourceId(); } else { $resourceId = (string) $resource; } if (!$this->has($resource)) { require_once 'Zend/Acl/Exception.php'; throw new Zend_Acl_Exception("Resource '$resourceId' not found"); } return $this->_resources[$resourceId]['instance']; } /** * Returns true if and only if the Resource exists in the ACL * * The $resource parameter can either be a Resource or a Resource identifier. * * @param Zend_Acl_Resource_Interface|string $resource * @return boolean */ public function has($resource) { if ($resource instanceof Zend_Acl_Resource_Interface) { $resourceId = $resource->getResourceId(); } else { $resourceId = (string) $resource; } return isset($this->_resources[$resourceId]); } /** * Returns true if and only if $resource inherits from $inherit * * Both parameters may be either a Resource or a Resource identifier. If * $onlyParent is true, then $resource must inherit directly from * $inherit in order to return true. By default, this method looks * through the entire inheritance tree to determine whether $resource * inherits from $inherit through its ancestor Resources. * * @param Zend_Acl_Resource_Interface|string $resource * @param Zend_Acl_Resource_Interface|string $inherit * @param boolean $onlyParent * @throws Zend_Acl_Resource_Registry_Exception * @return boolean */ public function inherits($resource, $inherit, $onlyParent = false) { try { $resourceId = $this->get($resource)->getResourceId(); $inheritId = $this->get($inherit)->getResourceId(); } catch (Zend_Acl_Exception $e) { require_once 'Zend/Acl/Exception.php'; throw new Zend_Acl_Exception($e->getMessage(), $e->getCode(), $e); } if (null !== $this->_resources[$resourceId]['parent']) { $parentId = $this->_resources[$resourceId]['parent']->getResourceId(); if ($inheritId === $parentId) { return true; } else if ($onlyParent) { return false; } } else { return false; } while (null !== $this->_resources[$parentId]['parent']) { $parentId = $this->_resources[$parentId]['parent']->getResourceId(); if ($inheritId === $parentId) { return true; } } return false; } /** * Removes a Resource and all of its children * * The $resource parameter can either be a Resource or a Resource identifier. * * @param Zend_Acl_Resource_Interface|string $resource * @throws Zend_Acl_Exception * @return Zend_Acl Provides a fluent interface */ public function remove($resource) { try { $resourceId = $this->get($resource)->getResourceId(); } catch (Zend_Acl_Exception $e) { require_once 'Zend/Acl/Exception.php'; throw new Zend_Acl_Exception($e->getMessage(), $e->getCode(), $e); } $resourcesRemoved = array($resourceId); if (null !== ($resourceParent = $this->_resources[$resourceId]['parent'])) { unset($this->_resources[$resourceParent->getResourceId()]['children'][$resourceId]); } foreach ($this->_resources[$resourceId]['children'] as $childId => $child) { $this->remove($childId); $resourcesRemoved[] = $childId; } foreach ($resourcesRemoved as $resourceIdRemoved) { foreach ($this->_rules['byResourceId'] as $resourceIdCurrent => $rules) { if ($resourceIdRemoved === $resourceIdCurrent) { unset($this->_rules['byResourceId'][$resourceIdCurrent]); } } } unset($this->_resources[$resourceId]); return $this; } /** * Removes all Resources * * @return Zend_Acl Provides a fluent interface */ public function removeAll() { foreach ($this->_resources as $resourceId => $resource) { foreach ($this->_rules['byResourceId'] as $resourceIdCurrent => $rules) { if ($resourceId === $resourceIdCurrent) { unset($this->_rules['byResourceId'][$resourceIdCurrent]); } } } $this->_resources = array(); return $this; } /** * Adds an "allow" rule to the ACL * * @param Zend_Acl_Role_Interface|string|array $roles * @param Zend_Acl_Resource_Interface|string|array $resources * @param string|array $privileges * @param Zend_Acl_Assert_Interface $assert * @uses Zend_Acl::setRule() * @return Zend_Acl Provides a fluent interface */ public function allow($roles = null, $resources = null, $privileges = null, Zend_Acl_Assert_Interface $assert = null) { return $this->setRule(self::OP_ADD, self::TYPE_ALLOW, $roles, $resources, $privileges, $assert); } /** * Adds a "deny" rule to the ACL * * @param Zend_Acl_Role_Interface|string|array $roles * @param Zend_Acl_Resource_Interface|string|array $resources * @param string|array $privileges * @param Zend_Acl_Assert_Interface $assert * @uses Zend_Acl::setRule() * @return Zend_Acl Provides a fluent interface */ public function deny($roles = null, $resources = null, $privileges = null, Zend_Acl_Assert_Interface $assert = null) { return $this->setRule(self::OP_ADD, self::TYPE_DENY, $roles, $resources, $privileges, $assert); } /** * Removes "allow" permissions from the ACL * * @param Zend_Acl_Role_Interface|string|array $roles * @param Zend_Acl_Resource_Interface|string|array $resources * @param string|array $privileges * @uses Zend_Acl::setRule() * @return Zend_Acl Provides a fluent interface */ public function removeAllow($roles = null, $resources = null, $privileges = null) { return $this->setRule(self::OP_REMOVE, self::TYPE_ALLOW, $roles, $resources, $privileges); } /** * Removes "deny" restrictions from the ACL * * @param Zend_Acl_Role_Interface|string|array $roles * @param Zend_Acl_Resource_Interface|string|array $resources * @param string|array $privileges * @uses Zend_Acl::setRule() * @return Zend_Acl Provides a fluent interface */ public function removeDeny($roles = null, $resources = null, $privileges = null) { return $this->setRule(self::OP_REMOVE, self::TYPE_DENY, $roles, $resources, $privileges); } /** * Performs operations on ACL rules * * The $operation parameter may be either OP_ADD or OP_REMOVE, depending on whether the * user wants to add or remove a rule, respectively: * * OP_ADD specifics: * * A rule is added that would allow one or more Roles access to [certain $privileges * upon] the specified Resource(s). * * OP_REMOVE specifics: * * The rule is removed only in the context of the given Roles, Resources, and privileges. * Existing rules to which the remove operation does not apply would remain in the * ACL. * * The $type parameter may be either TYPE_ALLOW or TYPE_DENY, depending on whether the * rule is intended to allow or deny permission, respectively. * * The $roles and $resources parameters may be references to, or the string identifiers for, * existing Resources/Roles, or they may be passed as arrays of these - mixing string identifiers * and objects is ok - to indicate the Resources and Roles to which the rule applies. If either * $roles or $resources is null, then the rule applies to all Roles or all Resources, respectively. * Both may be null in order to work with the default rule of the ACL. * * The $privileges parameter may be used to further specify that the rule applies only * to certain privileges upon the Resource(s) in question. This may be specified to be a single * privilege with a string, and multiple privileges may be specified as an array of strings. * * If $assert is provided, then its assert() method must return true in order for * the rule to apply. If $assert is provided with $roles, $resources, and $privileges all * equal to null, then a rule having a type of: * * TYPE_ALLOW will imply a type of TYPE_DENY, and * * TYPE_DENY will imply a type of TYPE_ALLOW * * when the rule's assertion fails. This is because the ACL needs to provide expected * behavior when an assertion upon the default ACL rule fails. * * @param string $operation * @param string $type * @param Zend_Acl_Role_Interface|string|array $roles * @param Zend_Acl_Resource_Interface|string|array $resources * @param string|array $privileges * @param Zend_Acl_Assert_Interface $assert * @throws Zend_Acl_Exception * @uses Zend_Acl_Role_Registry::get() * @uses Zend_Acl::get() * @return Zend_Acl Provides a fluent interface */ public function setRule($operation, $type, $roles = null, $resources = null, $privileges = null, Zend_Acl_Assert_Interface $assert = null) { // ensure that the rule type is valid; normalize input to uppercase $type = strtoupper($type); if (self::TYPE_ALLOW !== $type && self::TYPE_DENY !== $type) { require_once 'Zend/Acl/Exception.php'; throw new Zend_Acl_Exception("Unsupported rule type; must be either '" . self::TYPE_ALLOW . "' or '" . self::TYPE_DENY . "'"); } // ensure that all specified Roles exist; normalize input to array of Role objects or null if (!is_array($roles)) { $roles = array($roles); } else if (0 === count($roles)) { $roles = array(null); } $rolesTemp = $roles; $roles = array(); foreach ($rolesTemp as $role) { if (null !== $role) { $roles[] = $this->_getRoleRegistry()->get($role); } else { $roles[] = null; } } unset($rolesTemp); // ensure that all specified Resources exist; normalize input to array of Resource objects or null if ($resources !== null) { if (!is_array($resources)) { $resources = array($resources); } else if (0 === count($resources)) { $resources = array(null); } $resourcesTemp = $resources; $resources = array(); foreach ($resourcesTemp as $resource) { if (null !== $resource) { $resources[] = $this->get($resource); } else { $resources[] = null; } } unset($resourcesTemp, $resource); } else { $allResources = array(); // this might be used later if resource iteration is required foreach ($this->_resources as $rTarget) { $allResources[] = $rTarget['instance']; } unset($rTarget); } // normalize privileges to array if (null === $privileges) { $privileges = array(); } else if (!is_array($privileges)) { $privileges = array($privileges); } switch ($operation) { // add to the rules case self::OP_ADD: if ($resources !== null) { // this block will iterate the provided resources foreach ($resources as $resource) { foreach ($roles as $role) { $rules =& $this->_getRules($resource, $role, true); if (0 === count($privileges)) { $rules['allPrivileges']['type'] = $type; $rules['allPrivileges']['assert'] = $assert; if (!isset($rules['byPrivilegeId'])) { $rules['byPrivilegeId'] = array(); } } else { foreach ($privileges as $privilege) { $rules['byPrivilegeId'][$privilege]['type'] = $type; $rules['byPrivilegeId'][$privilege]['assert'] = $assert; } } } } } else { // this block will apply to all resources in a global rule foreach ($roles as $role) { $rules =& $this->_getRules(null, $role, true); if (0 === count($privileges)) { $rules['allPrivileges']['type'] = $type; $rules['allPrivileges']['assert'] = $assert; } else { foreach ($privileges as $privilege) { $rules['byPrivilegeId'][$privilege]['type'] = $type; $rules['byPrivilegeId'][$privilege]['assert'] = $assert; } } } } break; // remove from the rules case self::OP_REMOVE: if ($resources !== null) { // this block will iterate the provided resources foreach ($resources as $resource) { foreach ($roles as $role) { $rules =& $this->_getRules($resource, $role); if (null === $rules) { continue; } if (0 === count($privileges)) { if (null === $resource && null === $role) { if ($type === $rules['allPrivileges']['type']) { $rules = array( 'allPrivileges' => array( 'type' => self::TYPE_DENY, 'assert' => null ), 'byPrivilegeId' => array() ); } continue; } if (isset($rules['allPrivileges']['type']) && $type === $rules['allPrivileges']['type']) { unset($rules['allPrivileges']); } } else { foreach ($privileges as $privilege) { if (isset($rules['byPrivilegeId'][$privilege]) && $type === $rules['byPrivilegeId'][$privilege]['type']) { unset($rules['byPrivilegeId'][$privilege]); } } } } } } else { // this block will apply to all resources in a global rule foreach ($roles as $role) { /** * since null (all resources) was passed to this setRule() call, we need * clean up all the rules for the global allResources, as well as the indivually * set resources (per privilege as well) */ foreach (array_merge(array(null), $allResources) as $resource) { $rules =& $this->_getRules($resource, $role, true); if (null === $rules) { continue; } if (0 === count($privileges)) { if (null === $role) { if ($type === $rules['allPrivileges']['type']) { $rules = array( 'allPrivileges' => array( 'type' => self::TYPE_DENY, 'assert' => null ), 'byPrivilegeId' => array() ); } continue; } if (isset($rules['allPrivileges']['type']) && $type === $rules['allPrivileges']['type']) { unset($rules['allPrivileges']); } } else { foreach ($privileges as $privilege) { if (isset($rules['byPrivilegeId'][$privilege]) && $type === $rules['byPrivilegeId'][$privilege]['type']) { unset($rules['byPrivilegeId'][$privilege]); } } } } } } break; default: require_once 'Zend/Acl/Exception.php'; throw new Zend_Acl_Exception("Unsupported operation; must be either '" . self::OP_ADD . "' or '" . self::OP_REMOVE . "'"); } return $this; } /** * Returns true if and only if the Role has access to the Resource * * The $role and $resource parameters may be references to, or the string identifiers for, * an existing Resource and Role combination. * * If either $role or $resource is null, then the query applies to all Roles or all Resources, * respectively. Both may be null to query whether the ACL has a "blacklist" rule * (allow everything to all). By default, Zend_Acl creates a "whitelist" rule (deny * everything to all), and this method would return false unless this default has * been overridden (i.e., by executing $acl->allow()). * * If a $privilege is not provided, then this method returns false if and only if the * Role is denied access to at least one privilege upon the Resource. In other words, this * method returns true if and only if the Role is allowed all privileges on the Resource. * * This method checks Role inheritance using a depth-first traversal of the Role registry. * The highest priority parent (i.e., the parent most recently added) is checked first, * and its respective parents are checked similarly before the lower-priority parents of * the Role are checked. * * @param Zend_Acl_Role_Interface|string $role * @param Zend_Acl_Resource_Interface|string $resource * @param string $privilege * @uses Zend_Acl::get() * @uses Zend_Acl_Role_Registry::get() * @return boolean */ public function isAllowed($role = null, $resource = null, $privilege = null) { // reset role & resource to null $this->_isAllowedRole = null; $this->_isAllowedResource = null; $this->_isAllowedPrivilege = null; if (null !== $role) { // keep track of originally called role $this->_isAllowedRole = $role; $role = $this->_getRoleRegistry()->get($role); if (!$this->_isAllowedRole instanceof Zend_Acl_Role_Interface) { $this->_isAllowedRole = $role; } } if (null !== $resource) { // keep track of originally called resource $this->_isAllowedResource = $resource; $resource = $this->get($resource); if (!$this->_isAllowedResource instanceof Zend_Acl_Resource_Interface) { $this->_isAllowedResource = $resource; } } if (null === $privilege) { // query on all privileges do { // depth-first search on $role if it is not 'allRoles' pseudo-parent if (null !== $role && null !== ($result = $this->_roleDFSAllPrivileges($role, $resource, $privilege))) { return $result; } // look for rule on 'allRoles' psuedo-parent if (null !== ($rules = $this->_getRules($resource, null))) { foreach ($rules['byPrivilegeId'] as $privilege => $rule) { if (self::TYPE_DENY === ($ruleTypeOnePrivilege = $this->_getRuleType($resource, null, $privilege))) { return false; } } if (null !== ($ruleTypeAllPrivileges = $this->_getRuleType($resource, null, null))) { return self::TYPE_ALLOW === $ruleTypeAllPrivileges; } } // try next Resource $resource = $this->_resources[$resource->getResourceId()]['parent']; } while (true); // loop terminates at 'allResources' pseudo-parent } else { $this->_isAllowedPrivilege = $privilege; // query on one privilege do { // depth-first search on $role if it is not 'allRoles' pseudo-parent if (null !== $role && null !== ($result = $this->_roleDFSOnePrivilege($role, $resource, $privilege))) { return $result; } // look for rule on 'allRoles' pseudo-parent if (null !== ($ruleType = $this->_getRuleType($resource, null, $privilege))) { return self::TYPE_ALLOW === $ruleType; } else if (null !== ($ruleTypeAllPrivileges = $this->_getRuleType($resource, null, null))) { return self::TYPE_ALLOW === $ruleTypeAllPrivileges; } // try next Resource $resource = $this->_resources[$resource->getResourceId()]['parent']; } while (true); // loop terminates at 'allResources' pseudo-parent } } /** * Returns the Role registry for this ACL * * If no Role registry has been created yet, a new default Role registry * is created and returned. * * @return Zend_Acl_Role_Registry */ protected function _getRoleRegistry() { if (null === $this->_roleRegistry) { $this->_roleRegistry = new Zend_Acl_Role_Registry(); } return $this->_roleRegistry; } /** * Performs a depth-first search of the Role DAG, starting at $role, in order to find a rule * allowing/denying $role access to all privileges upon $resource * * This method returns true if a rule is found and allows access. If a rule exists and denies access, * then this method returns false. If no applicable rule is found, then this method returns null. * * @param Zend_Acl_Role_Interface $role * @param Zend_Acl_Resource_Interface $resource * @return boolean|null */ protected function _roleDFSAllPrivileges(Zend_Acl_Role_Interface $role, Zend_Acl_Resource_Interface $resource = null) { $dfs = array( 'visited' => array(), 'stack' => array() ); if (null !== ($result = $this->_roleDFSVisitAllPrivileges($role, $resource, $dfs))) { return $result; } while (null !== ($role = array_pop($dfs['stack']))) { if (!isset($dfs['visited'][$role->getRoleId()])) { if (null !== ($result = $this->_roleDFSVisitAllPrivileges($role, $resource, $dfs))) { return $result; } } } return null; } /** * Visits an $role in order to look for a rule allowing/denying $role access to all privileges upon $resource * * This method returns true if a rule is found and allows access. If a rule exists and denies access, * then this method returns false. If no applicable rule is found, then this method returns null. * * This method is used by the internal depth-first search algorithm and may modify the DFS data structure. * * @param Zend_Acl_Role_Interface $role * @param Zend_Acl_Resource_Interface $resource * @param array $dfs * @return boolean|null * @throws Zend_Acl_Exception */ protected function _roleDFSVisitAllPrivileges(Zend_Acl_Role_Interface $role, Zend_Acl_Resource_Interface $resource = null, &$dfs = null) { if (null === $dfs) { /** * @see Zend_Acl_Exception */ require_once 'Zend/Acl/Exception.php'; throw new Zend_Acl_Exception('$dfs parameter may not be null'); } if (null !== ($rules = $this->_getRules($resource, $role))) { foreach ($rules['byPrivilegeId'] as $privilege => $rule) { if (self::TYPE_DENY === ($ruleTypeOnePrivilege = $this->_getRuleType($resource, $role, $privilege))) { return false; } } if (null !== ($ruleTypeAllPrivileges = $this->_getRuleType($resource, $role, null))) { return self::TYPE_ALLOW === $ruleTypeAllPrivileges; } } $dfs['visited'][$role->getRoleId()] = true; foreach ($this->_getRoleRegistry()->getParents($role) as $roleParentId => $roleParent) { $dfs['stack'][] = $roleParent; } return null; } /** * Performs a depth-first search of the Role DAG, starting at $role, in order to find a rule * allowing/denying $role access to a $privilege upon $resource * * This method returns true if a rule is found and allows access. If a rule exists and denies access, * then this method returns false. If no applicable rule is found, then this method returns null. * * @param Zend_Acl_Role_Interface $role * @param Zend_Acl_Resource_Interface $resource * @param string $privilege * @return boolean|null * @throws Zend_Acl_Exception */ protected function _roleDFSOnePrivilege(Zend_Acl_Role_Interface $role, Zend_Acl_Resource_Interface $resource = null, $privilege = null) { if (null === $privilege) { /** * @see Zend_Acl_Exception */ require_once 'Zend/Acl/Exception.php'; throw new Zend_Acl_Exception('$privilege parameter may not be null'); } $dfs = array( 'visited' => array(), 'stack' => array() ); if (null !== ($result = $this->_roleDFSVisitOnePrivilege($role, $resource, $privilege, $dfs))) { return $result; } while (null !== ($role = array_pop($dfs['stack']))) { if (!isset($dfs['visited'][$role->getRoleId()])) { if (null !== ($result = $this->_roleDFSVisitOnePrivilege($role, $resource, $privilege, $dfs))) { return $result; } } } return null; } /** * Visits an $role in order to look for a rule allowing/denying $role access to a $privilege upon $resource * * This method returns true if a rule is found and allows access. If a rule exists and denies access, * then this method returns false. If no applicable rule is found, then this method returns null. * * This method is used by the internal depth-first search algorithm and may modify the DFS data structure. * * @param Zend_Acl_Role_Interface $role * @param Zend_Acl_Resource_Interface $resource * @param string $privilege * @param array $dfs * @return boolean|null * @throws Zend_Acl_Exception */ protected function _roleDFSVisitOnePrivilege(Zend_Acl_Role_Interface $role, Zend_Acl_Resource_Interface $resource = null, $privilege = null, &$dfs = null) { if (null === $privilege) { /** * @see Zend_Acl_Exception */ require_once 'Zend/Acl/Exception.php'; throw new Zend_Acl_Exception('$privilege parameter may not be null'); } if (null === $dfs) { /** * @see Zend_Acl_Exception */ require_once 'Zend/Acl/Exception.php'; throw new Zend_Acl_Exception('$dfs parameter may not be null'); } if (null !== ($ruleTypeOnePrivilege = $this->_getRuleType($resource, $role, $privilege))) { return self::TYPE_ALLOW === $ruleTypeOnePrivilege; } else if (null !== ($ruleTypeAllPrivileges = $this->_getRuleType($resource, $role, null))) { return self::TYPE_ALLOW === $ruleTypeAllPrivileges; } $dfs['visited'][$role->getRoleId()] = true; foreach ($this->_getRoleRegistry()->getParents($role) as $roleParentId => $roleParent) { $dfs['stack'][] = $roleParent; } return null; } /** * Returns the rule type associated with the specified Resource, Role, and privilege * combination. * * If a rule does not exist or its attached assertion fails, which means that * the rule is not applicable, then this method returns null. Otherwise, the * rule type applies and is returned as either TYPE_ALLOW or TYPE_DENY. * * If $resource or $role is null, then this means that the rule must apply to * all Resources or Roles, respectively. * * If $privilege is null, then the rule must apply to all privileges. * * If all three parameters are null, then the default ACL rule type is returned, * based on whether its assertion method passes. * * @param Zend_Acl_Resource_Interface $resource * @param Zend_Acl_Role_Interface $role * @param string $privilege * @return string|null */ protected function _getRuleType(Zend_Acl_Resource_Interface $resource = null, Zend_Acl_Role_Interface $role = null, $privilege = null) { // get the rules for the $resource and $role if (null === ($rules = $this->_getRules($resource, $role))) { return null; } // follow $privilege if (null === $privilege) { if (isset($rules['allPrivileges'])) { $rule = $rules['allPrivileges']; } else { return null; } } else if (!isset($rules['byPrivilegeId'][$privilege])) { return null; } else { $rule = $rules['byPrivilegeId'][$privilege]; } // check assertion first if ($rule['assert']) { $assertion = $rule['assert']; $assertionValue = $assertion->assert( $this, ($this->_isAllowedRole instanceof Zend_Acl_Role_Interface) ? $this->_isAllowedRole : $role, ($this->_isAllowedResource instanceof Zend_Acl_Resource_Interface) ? $this->_isAllowedResource : $resource, $this->_isAllowedPrivilege ); } if (null === $rule['assert'] || $assertionValue) { return $rule['type']; } else if (null !== $resource || null !== $role || null !== $privilege) { return null; } else if (self::TYPE_ALLOW === $rule['type']) { return self::TYPE_DENY; } else { return self::TYPE_ALLOW; } } /** * Returns the rules associated with a Resource and a Role, or null if no such rules exist * * If either $resource or $role is null, this means that the rules returned are for all Resources or all Roles, * respectively. Both can be null to return the default rule set for all Resources and all Roles. * * If the $create parameter is true, then a rule set is first created and then returned to the caller. * * @param Zend_Acl_Resource_Interface $resource * @param Zend_Acl_Role_Interface $role * @param boolean $create * @return array|null */ protected function &_getRules(Zend_Acl_Resource_Interface $resource = null, Zend_Acl_Role_Interface $role = null, $create = false) { // create a reference to null $null = null; $nullRef =& $null; // follow $resource do { if (null === $resource) { $visitor =& $this->_rules['allResources']; break; } $resourceId = $resource->getResourceId(); if (!isset($this->_rules['byResourceId'][$resourceId])) { if (!$create) { return $nullRef; } $this->_rules['byResourceId'][$resourceId] = array(); } $visitor =& $this->_rules['byResourceId'][$resourceId]; } while (false); // follow $role if (null === $role) { if (!isset($visitor['allRoles'])) { if (!$create) { return $nullRef; } $visitor['allRoles']['byPrivilegeId'] = array(); } return $visitor['allRoles']; } $roleId = $role->getRoleId(); if (!isset($visitor['byRoleId'][$roleId])) { if (!$create) { return $nullRef; } $visitor['byRoleId'][$roleId]['byPrivilegeId'] = array(); $visitor['byRoleId'][$roleId]['allPrivileges'] = array('type' => null, 'assert' => null); } return $visitor['byRoleId'][$roleId]; } /** * @return array of registered roles (Deprecated) * @deprecated Deprecated since version 1.10 (December 2009) */ public function getRegisteredRoles() { trigger_error('The method getRegisteredRoles() was deprecated as of ' . 'version 1.0, and may be removed. You\'re encouraged ' . 'to use getRoles() instead.'); return $this->_getRoleRegistry()->getRoles(); } /** * Returns an array of registered roles. * * Note that this method does not return instances of registered roles, * but only the role identifiers. * * @return array of registered roles */ public function getRoles() { return array_keys($this->_getRoleRegistry()->getRoles()); } /** * @return array of registered resources */ public function getResources() { return array_keys($this->_resources); } }
monzee/zf-1.x
library/Zend/Acl.php
PHP
bsd-3-clause
47,316
TOOLCHAIN_PREFIX=prizm- CC=$(TOOLCHAIN_PREFIX)gcc AS=$(TOOLCHAIN_PREFIX)as AR=$(TOOLCHAIN_PREFIX)ar CFLAGS=-c -ffunction-sections -fdata-sections -Os -Lr -I../include -flto -std=c99 -Wall -Wextra ARFLAGS=rs VPATH=syscalls SHSOURCES=$(wildcard syscalls/*.S) $(wildcard misc/*.S) CSOURCES=$(wildcard misc/*.c) #CXXSOURCES=$(wildcard misc/*.cpp) OBJECTS=$(SHSOURCES:.S=.o) $(CSOURCES:.c=.o) $(CXXSOURCES:.cpp=.o) LIBRARY=../lib/libfxcg.a all: $(SOURCES) $(LIBRARY) $(LIBRARY): $(OBJECTS) $(AR) $(ARFLAGS) $@ $(OBJECTS) .S.o: $(CC) $(CFLAGS) $< -o $@ .c.o: $(CC) $(CFLAGS) $< -o $@ .cpp.o: $(CC) $(CFLAGS) $< -o $@ clean: rm $(OBJECTS) $(LIBRARY)
Forty-Bot/libfxcg
libfxcg/Makefile
Makefile
bsd-3-clause
658
class CreateAuthenticationMethods < ActiveRecord::Migration def change create_table :spree_authentication_methods do |t| t.string :environment t.string :provider t.string :api_key t.string :api_secret t.boolean :active t.timestamps end end end
Johann-dotgee/spree_social
db/migrate/20120123163222_create_authentication_methods.rb
Ruby
bsd-3-clause
306
{{+bindTo:partials.standard_nacl_article}} <h1>Interfaces</h1> <div id="doxygen-ref"> {{- dummy div to appease doxygen -}} <div> <!-- Generated by Doxygen 1.7.6.1 --> </div> <!--header--> <div class="contents"> <h2> Data Structures</h2><table class="memberdecls"> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___audio__1__1.html">PPB_Audio</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_Audio</code> interface contains pointers to several functions for handling audio resources. <a href="struct_p_p_b___audio__1__1.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___audio_config__1__1.html">PPB_AudioConfig</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_AudioConfig</code> interface contains pointers to several functions for establishing your audio configuration within the browser. <a href="struct_p_p_b___audio_config__1__1.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___audio_frame__0__1.html">PPB_AudioFrame</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___console__1__0.html">PPB_Console</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___core__1__0.html">PPB_Core</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_Core</code> interface contains pointers to functions related to memory management, time, and threads on the browser. <a href="struct_p_p_b___core__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___file_i_o__1__1.html">PPB_FileIO</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_FileIO</code> struct is used to operate on a regular file (PP_FileType_Regular). <a href="struct_p_p_b___file_i_o__1__1.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___file_mapping__0__1.html">PPB_FileMapping</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">PPB_FileMapping contains functions for mapping and unmapping files into and out of memory. <a href="struct_p_p_b___file_mapping__0__1.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___file_ref__1__2.html">PPB_FileRef</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_FileRef</code> struct represents a "weak pointer" to a file in a file system. <a href="struct_p_p_b___file_ref__1__2.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___file_system__1__0.html">PPB_FileSystem</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_FileSystem</code> struct identifies the file system type associated with a file. <a href="struct_p_p_b___file_system__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___fullscreen__1__0.html">PPB_Fullscreen</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_Fullscreen</code> interface is implemented by the browser. <a href="struct_p_p_b___fullscreen__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___gamepad__1__0.html">PPB_Gamepad</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_Gamepad</code> interface allows retrieving data from gamepad/joystick devices that are connected to the system. <a href="struct_p_p_b___gamepad__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___graphics2_d__1__1.html">PPB_Graphics2D</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight"><code>PPB_Graphics2D</code> defines the interface for a 2D graphics context. <a href="struct_p_p_b___graphics2_d__1__1.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___graphics3_d__1__0.html">PPB_Graphics3D</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight"><code>PPB_Graphics3D</code> defines the interface for a 3D graphics context. <a href="struct_p_p_b___graphics3_d__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___host_resolver__1__0.html">PPB_HostResolver</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_HostResolver</code> interface supports host name resolution. <a href="struct_p_p_b___host_resolver__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___image_data__1__0.html">PPB_ImageData</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_ImageData</code> interface contains pointers to several functions for determining the browser's treatment of image data. <a href="struct_p_p_b___image_data__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___input_event__1__0.html">PPB_InputEvent</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_InputEvent</code> interface contains pointers to several functions related to generic input events on the browser. <a href="struct_p_p_b___input_event__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___mouse_input_event__1__1.html">PPB_MouseInputEvent</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_MouseInputEvent</code> interface contains pointers to several functions related to mouse input events. <a href="struct_p_p_b___mouse_input_event__1__1.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___wheel_input_event__1__0.html">PPB_WheelInputEvent</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_WheelIputEvent</code> interface contains pointers to several functions related to wheel input events. <a href="struct_p_p_b___wheel_input_event__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___keyboard_input_event__1__2.html">PPB_KeyboardInputEvent</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_KeyboardInputEvent</code> interface contains pointers to several functions related to keyboard input events. <a href="struct_p_p_b___keyboard_input_event__1__2.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___touch_input_event__1__0.html">PPB_TouchInputEvent</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_TouchInputEvent</code> interface contains pointers to several functions related to touch events. <a href="struct_p_p_b___touch_input_event__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___i_m_e_input_event__1__0.html">PPB_IMEInputEvent</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___instance__1__0.html">PPB_Instance</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The PPB_Instance interface contains pointers to functions related to the module instance on a web page. <a href="struct_p_p_b___instance__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___media_stream_audio_track__0__1.html">PPB_MediaStreamAudioTrack</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___media_stream_video_track__0__1.html">PPB_MediaStreamVideoTrack</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___message_loop__1__0.html">PPB_MessageLoop</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">A message loop allows PPAPI calls to be issued on a thread. <a href="struct_p_p_b___message_loop__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___messaging__1__0.html">PPB_Messaging</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_Messaging</code> interface is implemented by the browser and is related to sending messages to JavaScript message event listeners on the DOM element associated with specific module instance. <a href="struct_p_p_b___messaging__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___mouse_cursor__1__0.html">PPB_MouseCursor</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_MouseCursor</code> allows setting the mouse cursor. <a href="struct_p_p_b___mouse_cursor__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___mouse_lock__1__0.html">PPB_MouseLock</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_MouseLock</code> interface is implemented by the browser. <a href="struct_p_p_b___mouse_lock__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___net_address__1__0.html">PPB_NetAddress</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_NetAddress</code> interface provides operations on network addresses. <a href="struct_p_p_b___net_address__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___network_list__1__0.html">PPB_NetworkList</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_NetworkList</code> is used to represent a list of network interfaces and their configuration. <a href="struct_p_p_b___network_list__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___network_monitor__1__0.html">PPB_NetworkMonitor</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_NetworkMonitor</code> allows to get network interfaces configuration and monitor network configuration changes. <a href="struct_p_p_b___network_monitor__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___network_proxy__1__0.html">PPB_NetworkProxy</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">This interface provides a way to determine the appropriate proxy settings for a given URL. <a href="struct_p_p_b___network_proxy__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___t_c_p_socket__1__1.html">PPB_TCPSocket</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_TCPSocket</code> interface provides TCP socket operations. <a href="struct_p_p_b___t_c_p_socket__1__1.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___text_input_controller__1__0.html">PPB_TextInputController</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight"><code>PPB_TextInputController</code> provides a set of functions for giving hints to the browser about the text input status of plugins, and functions for controlling input method editors (IMEs). <a href="struct_p_p_b___text_input_controller__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___u_d_p_socket__1__0.html">PPB_UDPSocket</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_UDPSocket</code> interface provides UDP socket operations. <a href="struct_p_p_b___u_d_p_socket__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___u_r_l_loader__1__0.html">PPB_URLLoader</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <b>PPB_URLLoader</b> interface contains pointers to functions for loading URLs. <a href="struct_p_p_b___u_r_l_loader__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___u_r_l_request_info__1__0.html">PPB_URLRequestInfo</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_URLRequestInfo</code> interface is used to create and handle URL requests. <a href="struct_p_p_b___u_r_l_request_info__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___u_r_l_response_info__1__0.html">PPB_URLResponseInfo</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The PPB_URLResponseInfo interface contains APIs for examining URL responses. <a href="struct_p_p_b___u_r_l_response_info__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___var__1__1.html">PPB_Var</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">PPB_Var API. <a href="struct_p_p_b___var__1__1.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___var_array__1__0.html">PPB_VarArray</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___var_array_buffer__1__0.html">PPB_VarArrayBuffer</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_VarArrayBuffer</code> interface provides a way to interact with JavaScript ArrayBuffers, which represent a contiguous sequence of bytes. <a href="struct_p_p_b___var_array_buffer__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___var_dictionary__1__0.html">PPB_VarDictionary</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">A dictionary var contains key-value pairs with unique keys. <a href="struct_p_p_b___var_dictionary__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___video_frame__0__1.html">PPB_VideoFrame</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___view__1__1.html">PPB_View</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight"><code>PPB_View</code> represents the state of the view of an instance. <a href="struct_p_p_b___view__1__1.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_b___web_socket__1__0.html">PPB_WebSocket</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPB_WebSocket</code> interface provides bi-directional, full-duplex, communications over a single TCP socket. <a href="struct_p_p_b___web_socket__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_p___graphics3_d__1__0.html">PPP_Graphics3D</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight"><code>PPP_Graphics3D</code> defines the notification interface for a 3D graphics context. <a href="struct_p_p_p___graphics3_d__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_p___input_event__0__1.html">PPP_InputEvent</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_p___instance__1__1.html">PPP_Instance</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPP_Instance</code> interface contains pointers to a series of functions that you must implement in your module. <a href="struct_p_p_p___instance__1__1.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_p___messaging__1__0.html">PPP_Messaging</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPP_Messaging</code> interface contains pointers to functions that you must implement to handle postMessage events on the associated DOM element. <a href="struct_p_p_p___messaging__1__0.html#details">More...</a><br /></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="struct_p_p_p___mouse_lock__1__0.html">PPP_MouseLock</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">The <code>PPP_MouseLock</code> interface contains a function that you must implement to receive mouse lock events from the browser. <a href="struct_p_p_p___mouse_lock__1__0.html#details">More...</a><br /></td></tr> </table><h2> Typedefs</h2><table class="memberdecls"> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___audio__1__1.html">PPB_Audio</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gaa420ab6e5eec1d780700bb505fe7d7f5">PPB_Audio</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___audio_config__1__1.html">PPB_AudioConfig</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga6c784ebe92dee70d03a685298a8b8345">PPB_AudioConfig</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___console__1__0.html">PPB_Console</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gab38f2ca92926b53d58d1cf2ce6320ebb">PPB_Console</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___core__1__0.html">PPB_Core</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga34a986157c49afcad3537479bc5361e9">PPB_Core</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___file_i_o__1__1.html">PPB_FileIO</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga7b7a4f4317a5af9982ba79d60f04db69">PPB_FileIO</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___file_system__1__0.html">PPB_FileSystem</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gae5ad593b6aff864c6bd0acc09d6cc5e9">PPB_FileSystem</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___fullscreen__1__0.html">PPB_Fullscreen</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga965dcf552ef79d1a41e0c24db2cf5c3c">PPB_Fullscreen</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___gamepad__1__0.html">PPB_Gamepad</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga57baea75086a666a92489da807f16f2a">PPB_Gamepad</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___graphics2_d__1__1.html">PPB_Graphics2D</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gaf9f8348d3315d8bb014b401f733ebdb6">PPB_Graphics2D</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___graphics3_d__1__0.html">PPB_Graphics3D</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga2865870b49481aae8ed416c06c58a7c0">PPB_Graphics3D</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___host_resolver__1__0.html">PPB_HostResolver</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga72b9bd04eeace0c69f4e454b7cc4e440">PPB_HostResolver</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___image_data__1__0.html">PPB_ImageData</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga17e05bbe7da0d6d7b61b6f78c5913c37">PPB_ImageData</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___input_event__1__0.html">PPB_InputEvent</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gac221fa16a0d0daa0bf171a477b465396">PPB_InputEvent</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <br class="typebreak" /> <a class="el" href="struct_p_p_b___mouse_input_event__1__1.html">PPB_MouseInputEvent</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga3fcedb0e992eebaf7d9b1b60aacceafc">PPB_MouseInputEvent</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <br class="typebreak" /> <a class="el" href="struct_p_p_b___wheel_input_event__1__0.html">PPB_WheelInputEvent</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gaaefb7f24240d14faa56dfdba8c116889">PPB_WheelInputEvent</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <br class="typebreak" /> <a class="el" href="struct_p_p_b___keyboard_input_event__1__2.html">PPB_KeyboardInputEvent</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga65db91594ac92762680dc3cdff4f14c1">PPB_KeyboardInputEvent</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <br class="typebreak" /> <a class="el" href="struct_p_p_b___touch_input_event__1__0.html">PPB_TouchInputEvent</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga3d25b1582fc1e6b94f53ecfb21422d6c">PPB_TouchInputEvent</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <br class="typebreak" /> <a class="el" href="struct_p_p_b___i_m_e_input_event__1__0.html">PPB_IMEInputEvent</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gaaa0c327650de77066ea8e2ec8f5589c5">PPB_IMEInputEvent</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___instance__1__0.html">PPB_Instance</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gaf2ed3cc24968d8681b52cf70eae066ca">PPB_Instance</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___message_loop__1__0.html">PPB_MessageLoop</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gae3eb3482b0fb57fb6a4eb05c07908788">PPB_MessageLoop</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___messaging__1__0.html">PPB_Messaging</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gac53fe3a3b5941f8b3608349f58ee24f0">PPB_Messaging</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___mouse_cursor__1__0.html">PPB_MouseCursor</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gae583d9ea6381e1e4cb7b462c35c5d1de">PPB_MouseCursor</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___mouse_lock__1__0.html">PPB_MouseLock</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga9d5fa32b9c90b100400161025fda2617">PPB_MouseLock</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___net_address__1__0.html">PPB_NetAddress</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gad6c325ff5a0a74f318a680971d0a7c52">PPB_NetAddress</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___network_list__1__0.html">PPB_NetworkList</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga675af1709086b2a750d28da442c41f8a">PPB_NetworkList</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <br class="typebreak" /> <a class="el" href="struct_p_p_b___network_monitor__1__0.html">PPB_NetworkMonitor</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga873d8c5cd49f7b3c8ad5b4caabd1e8e6">PPB_NetworkMonitor</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___network_proxy__1__0.html">PPB_NetworkProxy</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gaf8338a682417267c8525446ef1de85b1">PPB_NetworkProxy</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___t_c_p_socket__1__1.html">PPB_TCPSocket</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga0f72e14a6cf9631bd733ded1f8ba4d9f">PPB_TCPSocket</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <br class="typebreak" /> <a class="el" href="struct_p_p_b___text_input_controller__1__0.html">PPB_TextInputController</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gab387085f6044f3a0b1631d119d22a942">PPB_TextInputController</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___u_d_p_socket__1__0.html">PPB_UDPSocket</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gaf04d893ccf01c5d1cfcadee5fcc869d1">PPB_UDPSocket</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___u_r_l_loader__1__0.html">PPB_URLLoader</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga307f562a9e41991de7c80b75cd7f379c">PPB_URLLoader</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <br class="typebreak" /> <a class="el" href="struct_p_p_b___u_r_l_request_info__1__0.html">PPB_URLRequestInfo</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gad60387934d9e235d3d145ee5a1fb4e74">PPB_URLRequestInfo</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <br class="typebreak" /> <a class="el" href="struct_p_p_b___u_r_l_response_info__1__0.html">PPB_URLResponseInfo</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gad63e57584aea115126b6922b141cf745">PPB_URLResponseInfo</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___var__1__1.html">PPB_Var</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga7363a88a6e5058841915641c1b2923ad">PPB_Var</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___var_array__1__0.html">PPB_VarArray</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gaad75327f1ecc75e58c2805fc4740d3c6">PPB_VarArray</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <br class="typebreak" /> <a class="el" href="struct_p_p_b___var_array_buffer__1__0.html">PPB_VarArrayBuffer</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gab26d5bb032f5438d02faf5bdf7b208cb">PPB_VarArrayBuffer</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <br class="typebreak" /> <a class="el" href="struct_p_p_b___var_dictionary__1__0.html">PPB_VarDictionary</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga69826004b5c32232c9639090f3e1db2e">PPB_VarDictionary</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___view__1__1.html">PPB_View</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gaccc39c5c499011d13be37e23868a04f3">PPB_View</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_b___web_socket__1__0.html">PPB_WebSocket</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gad0e152d14cefb0b480228f3fc7070faf">PPB_WebSocket</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_p___graphics3_d__1__0.html">PPP_Graphics3D</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gab9b763d2ae6ef08a8f18069728f418eb">PPP_Graphics3D</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_p___input_event__0__1.html">PPP_InputEvent</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga9c2577b1c089f77e1e467d74bd97a940">PPP_InputEvent</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_p___instance__1__1.html">PPP_Instance</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga3397638d116e4171368bf18fcb91ef11">PPP_Instance</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_p___messaging__1__0.html">PPP_Messaging</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#ga1b4374f30360ab34679a159083db7e4d">PPP_Messaging</a></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef struct <a class="el" href="struct_p_p_p___mouse_lock__1__0.html">PPP_MouseLock</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___interfaces.html#gae600e8f5b6005b02378e6eb9f51b11cb">PPP_MouseLock</a></td></tr> </table> <hr /><h2>Typedef Documentation</h2> <a class="anchor" id="gaa420ab6e5eec1d780700bb505fe7d7f5"></a><!-- doxytag: member="ppb_audio.h::PPB_Audio" ref="gaa420ab6e5eec1d780700bb505fe7d7f5" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___audio__1__1.html">PPB_Audio</a> <a class="el" href="group___interfaces.html#gaa420ab6e5eec1d780700bb505fe7d7f5">PPB_Audio</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga6c784ebe92dee70d03a685298a8b8345"></a><!-- doxytag: member="ppb_audio_config.h::PPB_AudioConfig" ref="ga6c784ebe92dee70d03a685298a8b8345" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___audio_config__1__1.html">PPB_AudioConfig</a> <a class="el" href="group___interfaces.html#ga6c784ebe92dee70d03a685298a8b8345">PPB_AudioConfig</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gab38f2ca92926b53d58d1cf2ce6320ebb"></a><!-- doxytag: member="ppb_console.h::PPB_Console" ref="gab38f2ca92926b53d58d1cf2ce6320ebb" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___console__1__0.html">PPB_Console</a> <a class="el" href="group___interfaces.html#gab38f2ca92926b53d58d1cf2ce6320ebb">PPB_Console</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga34a986157c49afcad3537479bc5361e9"></a><!-- doxytag: member="ppb_core.h::PPB_Core" ref="ga34a986157c49afcad3537479bc5361e9" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___core__1__0.html">PPB_Core</a> <a class="el" href="group___interfaces.html#ga34a986157c49afcad3537479bc5361e9">PPB_Core</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga7b7a4f4317a5af9982ba79d60f04db69"></a><!-- doxytag: member="ppb_file_io.h::PPB_FileIO" ref="ga7b7a4f4317a5af9982ba79d60f04db69" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___file_i_o__1__1.html">PPB_FileIO</a> <a class="el" href="group___interfaces.html#ga7b7a4f4317a5af9982ba79d60f04db69">PPB_FileIO</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gae5ad593b6aff864c6bd0acc09d6cc5e9"></a><!-- doxytag: member="ppb_file_system.h::PPB_FileSystem" ref="gae5ad593b6aff864c6bd0acc09d6cc5e9" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___file_system__1__0.html">PPB_FileSystem</a> <a class="el" href="group___interfaces.html#gae5ad593b6aff864c6bd0acc09d6cc5e9">PPB_FileSystem</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga965dcf552ef79d1a41e0c24db2cf5c3c"></a><!-- doxytag: member="ppb_fullscreen.h::PPB_Fullscreen" ref="ga965dcf552ef79d1a41e0c24db2cf5c3c" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___fullscreen__1__0.html">PPB_Fullscreen</a> <a class="el" href="group___interfaces.html#ga965dcf552ef79d1a41e0c24db2cf5c3c">PPB_Fullscreen</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga57baea75086a666a92489da807f16f2a"></a><!-- doxytag: member="ppb_gamepad.h::PPB_Gamepad" ref="ga57baea75086a666a92489da807f16f2a" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___gamepad__1__0.html">PPB_Gamepad</a> <a class="el" href="group___interfaces.html#ga57baea75086a666a92489da807f16f2a">PPB_Gamepad</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gaf9f8348d3315d8bb014b401f733ebdb6"></a><!-- doxytag: member="ppb_graphics_2d.h::PPB_Graphics2D" ref="gaf9f8348d3315d8bb014b401f733ebdb6" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___graphics2_d__1__1.html">PPB_Graphics2D</a> <a class="el" href="group___interfaces.html#gaf9f8348d3315d8bb014b401f733ebdb6">PPB_Graphics2D</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga2865870b49481aae8ed416c06c58a7c0"></a><!-- doxytag: member="ppb_graphics_3d.h::PPB_Graphics3D" ref="ga2865870b49481aae8ed416c06c58a7c0" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___graphics3_d__1__0.html">PPB_Graphics3D</a> <a class="el" href="group___interfaces.html#ga2865870b49481aae8ed416c06c58a7c0">PPB_Graphics3D</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga72b9bd04eeace0c69f4e454b7cc4e440"></a><!-- doxytag: member="ppb_host_resolver.h::PPB_HostResolver" ref="ga72b9bd04eeace0c69f4e454b7cc4e440" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___host_resolver__1__0.html">PPB_HostResolver</a> <a class="el" href="group___interfaces.html#ga72b9bd04eeace0c69f4e454b7cc4e440">PPB_HostResolver</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga17e05bbe7da0d6d7b61b6f78c5913c37"></a><!-- doxytag: member="ppb_image_data.h::PPB_ImageData" ref="ga17e05bbe7da0d6d7b61b6f78c5913c37" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___image_data__1__0.html">PPB_ImageData</a> <a class="el" href="group___interfaces.html#ga17e05bbe7da0d6d7b61b6f78c5913c37">PPB_ImageData</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gaaa0c327650de77066ea8e2ec8f5589c5"></a><!-- doxytag: member="ppb_input_event.h::PPB_IMEInputEvent" ref="gaaa0c327650de77066ea8e2ec8f5589c5" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___i_m_e_input_event__1__0.html">PPB_IMEInputEvent</a> <a class="el" href="group___interfaces.html#gaaa0c327650de77066ea8e2ec8f5589c5">PPB_IMEInputEvent</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gac221fa16a0d0daa0bf171a477b465396"></a><!-- doxytag: member="ppb_input_event.h::PPB_InputEvent" ref="gac221fa16a0d0daa0bf171a477b465396" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___input_event__1__0.html">PPB_InputEvent</a> <a class="el" href="group___interfaces.html#gac221fa16a0d0daa0bf171a477b465396">PPB_InputEvent</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gaf2ed3cc24968d8681b52cf70eae066ca"></a><!-- doxytag: member="ppb_instance.h::PPB_Instance" ref="gaf2ed3cc24968d8681b52cf70eae066ca" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___instance__1__0.html">PPB_Instance</a> <a class="el" href="group___interfaces.html#gaf2ed3cc24968d8681b52cf70eae066ca">PPB_Instance</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga65db91594ac92762680dc3cdff4f14c1"></a><!-- doxytag: member="ppb_input_event.h::PPB_KeyboardInputEvent" ref="ga65db91594ac92762680dc3cdff4f14c1" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___keyboard_input_event__1__2.html">PPB_KeyboardInputEvent</a> <a class="el" href="group___interfaces.html#ga65db91594ac92762680dc3cdff4f14c1">PPB_KeyboardInputEvent</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gae3eb3482b0fb57fb6a4eb05c07908788"></a><!-- doxytag: member="ppb_message_loop.h::PPB_MessageLoop" ref="gae3eb3482b0fb57fb6a4eb05c07908788" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___message_loop__1__0.html">PPB_MessageLoop</a> <a class="el" href="group___interfaces.html#gae3eb3482b0fb57fb6a4eb05c07908788">PPB_MessageLoop</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gac53fe3a3b5941f8b3608349f58ee24f0"></a><!-- doxytag: member="ppb_messaging.h::PPB_Messaging" ref="gac53fe3a3b5941f8b3608349f58ee24f0" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___messaging__1__0.html">PPB_Messaging</a> <a class="el" href="group___interfaces.html#gac53fe3a3b5941f8b3608349f58ee24f0">PPB_Messaging</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gae583d9ea6381e1e4cb7b462c35c5d1de"></a><!-- doxytag: member="ppb_mouse_cursor.h::PPB_MouseCursor" ref="gae583d9ea6381e1e4cb7b462c35c5d1de" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___mouse_cursor__1__0.html">PPB_MouseCursor</a> <a class="el" href="group___interfaces.html#gae583d9ea6381e1e4cb7b462c35c5d1de">PPB_MouseCursor</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga3fcedb0e992eebaf7d9b1b60aacceafc"></a><!-- doxytag: member="ppb_input_event.h::PPB_MouseInputEvent" ref="ga3fcedb0e992eebaf7d9b1b60aacceafc" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___mouse_input_event__1__1.html">PPB_MouseInputEvent</a> <a class="el" href="group___interfaces.html#ga3fcedb0e992eebaf7d9b1b60aacceafc">PPB_MouseInputEvent</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga9d5fa32b9c90b100400161025fda2617"></a><!-- doxytag: member="ppb_mouse_lock.h::PPB_MouseLock" ref="ga9d5fa32b9c90b100400161025fda2617" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___mouse_lock__1__0.html">PPB_MouseLock</a> <a class="el" href="group___interfaces.html#ga9d5fa32b9c90b100400161025fda2617">PPB_MouseLock</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gad6c325ff5a0a74f318a680971d0a7c52"></a><!-- doxytag: member="ppb_net_address.h::PPB_NetAddress" ref="gad6c325ff5a0a74f318a680971d0a7c52" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___net_address__1__0.html">PPB_NetAddress</a> <a class="el" href="group___interfaces.html#gad6c325ff5a0a74f318a680971d0a7c52">PPB_NetAddress</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga675af1709086b2a750d28da442c41f8a"></a><!-- doxytag: member="ppb_network_list.h::PPB_NetworkList" ref="ga675af1709086b2a750d28da442c41f8a" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___network_list__1__0.html">PPB_NetworkList</a> <a class="el" href="group___interfaces.html#ga675af1709086b2a750d28da442c41f8a">PPB_NetworkList</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga873d8c5cd49f7b3c8ad5b4caabd1e8e6"></a><!-- doxytag: member="ppb_network_monitor.h::PPB_NetworkMonitor" ref="ga873d8c5cd49f7b3c8ad5b4caabd1e8e6" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___network_monitor__1__0.html">PPB_NetworkMonitor</a> <a class="el" href="group___interfaces.html#ga873d8c5cd49f7b3c8ad5b4caabd1e8e6">PPB_NetworkMonitor</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gaf8338a682417267c8525446ef1de85b1"></a><!-- doxytag: member="ppb_network_proxy.h::PPB_NetworkProxy" ref="gaf8338a682417267c8525446ef1de85b1" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___network_proxy__1__0.html">PPB_NetworkProxy</a> <a class="el" href="group___interfaces.html#gaf8338a682417267c8525446ef1de85b1">PPB_NetworkProxy</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga0f72e14a6cf9631bd733ded1f8ba4d9f"></a><!-- doxytag: member="ppb_tcp_socket.h::PPB_TCPSocket" ref="ga0f72e14a6cf9631bd733ded1f8ba4d9f" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___t_c_p_socket__1__1.html">PPB_TCPSocket</a> <a class="el" href="group___interfaces.html#ga0f72e14a6cf9631bd733ded1f8ba4d9f">PPB_TCPSocket</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gab387085f6044f3a0b1631d119d22a942"></a><!-- doxytag: member="ppb_text_input_controller.h::PPB_TextInputController" ref="gab387085f6044f3a0b1631d119d22a942" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___text_input_controller__1__0.html">PPB_TextInputController</a> <a class="el" href="group___interfaces.html#gab387085f6044f3a0b1631d119d22a942">PPB_TextInputController</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga3d25b1582fc1e6b94f53ecfb21422d6c"></a><!-- doxytag: member="ppb_input_event.h::PPB_TouchInputEvent" ref="ga3d25b1582fc1e6b94f53ecfb21422d6c" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___touch_input_event__1__0.html">PPB_TouchInputEvent</a> <a class="el" href="group___interfaces.html#ga3d25b1582fc1e6b94f53ecfb21422d6c">PPB_TouchInputEvent</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gaf04d893ccf01c5d1cfcadee5fcc869d1"></a><!-- doxytag: member="ppb_udp_socket.h::PPB_UDPSocket" ref="gaf04d893ccf01c5d1cfcadee5fcc869d1" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___u_d_p_socket__1__0.html">PPB_UDPSocket</a> <a class="el" href="group___interfaces.html#gaf04d893ccf01c5d1cfcadee5fcc869d1">PPB_UDPSocket</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga307f562a9e41991de7c80b75cd7f379c"></a><!-- doxytag: member="ppb_url_loader.h::PPB_URLLoader" ref="ga307f562a9e41991de7c80b75cd7f379c" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___u_r_l_loader__1__0.html">PPB_URLLoader</a> <a class="el" href="group___interfaces.html#ga307f562a9e41991de7c80b75cd7f379c">PPB_URLLoader</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gad60387934d9e235d3d145ee5a1fb4e74"></a><!-- doxytag: member="ppb_url_request_info.h::PPB_URLRequestInfo" ref="gad60387934d9e235d3d145ee5a1fb4e74" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___u_r_l_request_info__1__0.html">PPB_URLRequestInfo</a> <a class="el" href="group___interfaces.html#gad60387934d9e235d3d145ee5a1fb4e74">PPB_URLRequestInfo</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gad63e57584aea115126b6922b141cf745"></a><!-- doxytag: member="ppb_url_response_info.h::PPB_URLResponseInfo" ref="gad63e57584aea115126b6922b141cf745" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___u_r_l_response_info__1__0.html">PPB_URLResponseInfo</a> <a class="el" href="group___interfaces.html#gad63e57584aea115126b6922b141cf745">PPB_URLResponseInfo</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga7363a88a6e5058841915641c1b2923ad"></a><!-- doxytag: member="ppb_var.h::PPB_Var" ref="ga7363a88a6e5058841915641c1b2923ad" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___var__1__1.html">PPB_Var</a> <a class="el" href="group___interfaces.html#ga7363a88a6e5058841915641c1b2923ad">PPB_Var</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gaad75327f1ecc75e58c2805fc4740d3c6"></a><!-- doxytag: member="ppb_var_array.h::PPB_VarArray" ref="gaad75327f1ecc75e58c2805fc4740d3c6" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___var_array__1__0.html">PPB_VarArray</a> <a class="el" href="group___interfaces.html#gaad75327f1ecc75e58c2805fc4740d3c6">PPB_VarArray</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gab26d5bb032f5438d02faf5bdf7b208cb"></a><!-- doxytag: member="ppb_var_array_buffer.h::PPB_VarArrayBuffer" ref="gab26d5bb032f5438d02faf5bdf7b208cb" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___var_array_buffer__1__0.html">PPB_VarArrayBuffer</a> <a class="el" href="group___interfaces.html#gab26d5bb032f5438d02faf5bdf7b208cb">PPB_VarArrayBuffer</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga69826004b5c32232c9639090f3e1db2e"></a><!-- doxytag: member="ppb_var_dictionary.h::PPB_VarDictionary" ref="ga69826004b5c32232c9639090f3e1db2e" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___var_dictionary__1__0.html">PPB_VarDictionary</a> <a class="el" href="group___interfaces.html#ga69826004b5c32232c9639090f3e1db2e">PPB_VarDictionary</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gaccc39c5c499011d13be37e23868a04f3"></a><!-- doxytag: member="ppb_view.h::PPB_View" ref="gaccc39c5c499011d13be37e23868a04f3" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___view__1__1.html">PPB_View</a> <a class="el" href="group___interfaces.html#gaccc39c5c499011d13be37e23868a04f3">PPB_View</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gad0e152d14cefb0b480228f3fc7070faf"></a><!-- doxytag: member="ppb_websocket.h::PPB_WebSocket" ref="gad0e152d14cefb0b480228f3fc7070faf" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___web_socket__1__0.html">PPB_WebSocket</a> <a class="el" href="group___interfaces.html#gad0e152d14cefb0b480228f3fc7070faf">PPB_WebSocket</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gaaefb7f24240d14faa56dfdba8c116889"></a><!-- doxytag: member="ppb_input_event.h::PPB_WheelInputEvent" ref="gaaefb7f24240d14faa56dfdba8c116889" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_b___wheel_input_event__1__0.html">PPB_WheelInputEvent</a> <a class="el" href="group___interfaces.html#gaaefb7f24240d14faa56dfdba8c116889">PPB_WheelInputEvent</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gab9b763d2ae6ef08a8f18069728f418eb"></a><!-- doxytag: member="ppp_graphics_3d.h::PPP_Graphics3D" ref="gab9b763d2ae6ef08a8f18069728f418eb" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_p___graphics3_d__1__0.html">PPP_Graphics3D</a> <a class="el" href="group___interfaces.html#gab9b763d2ae6ef08a8f18069728f418eb">PPP_Graphics3D</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga9c2577b1c089f77e1e467d74bd97a940"></a><!-- doxytag: member="ppp_input_event.h::PPP_InputEvent" ref="ga9c2577b1c089f77e1e467d74bd97a940" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_p___input_event__0__1.html">PPP_InputEvent</a> <a class="el" href="group___interfaces.html#ga9c2577b1c089f77e1e467d74bd97a940">PPP_InputEvent</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga3397638d116e4171368bf18fcb91ef11"></a><!-- doxytag: member="ppp_instance.h::PPP_Instance" ref="ga3397638d116e4171368bf18fcb91ef11" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_p___instance__1__1.html">PPP_Instance</a> <a class="el" href="group___interfaces.html#ga3397638d116e4171368bf18fcb91ef11">PPP_Instance</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="ga1b4374f30360ab34679a159083db7e4d"></a><!-- doxytag: member="ppp_messaging.h::PPP_Messaging" ref="ga1b4374f30360ab34679a159083db7e4d" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_p___messaging__1__0.html">PPP_Messaging</a> <a class="el" href="group___interfaces.html#ga1b4374f30360ab34679a159083db7e4d">PPP_Messaging</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="gae600e8f5b6005b02378e6eb9f51b11cb"></a><!-- doxytag: member="ppp_mouse_lock.h::PPP_MouseLock" ref="gae600e8f5b6005b02378e6eb9f51b11cb" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_p_p_p___mouse_lock__1__0.html">PPP_MouseLock</a> <a class="el" href="group___interfaces.html#gae600e8f5b6005b02378e6eb9f51b11cb">PPP_MouseLock</a></td> </tr> </table> </div> <div class="memdoc"> </div> </div> </div><!-- contents --> </div> {{/partials.standard_nacl_article}}
ChromiumWebApps/chromium
native_client_sdk/doc_generated/pepper_dev/c/group___interfaces.html
HTML
bsd-3-clause
57,875
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @generated by scripts/bump-oss-version.js */ #pragma once #include <cstdint> #include <string_view> namespace ABI42_0_0facebook::ABI42_0_0React { constexpr struct { int32_t Major = 0; int32_t Minor = 63; int32_t Patch = 2; std::string_view Prerelease = ""; } reactNativeVersion; } // namespace ABI42_0_0facebook::ABI42_0_0React
exponentjs/exponent
ios/versioned-react-native/ABI42_0_0/ReactNative/ReactCommon/cxxreact/ABI42_0_0ReactNativeVersion.h
C
bsd-3-clause
533
var DataSelector = require("logic/model/data-selector").DataSelector; /** * Backward compatibility support for logic/service/data-selector after that * class has been moved to logic/model/data-selector. * * @class * @extends external:Montage * @todo Deprecate. */ exports.DataSelector = DataSelector.specialize();
montagestudio/montage-data
logic/service/data-selector.js
JavaScript
bsd-3-clause
322
<?php use yii\db\Migration; /** * Handles the creation of table `activity_category`. */ class m170220_094103_create_activity_category_table extends Migration { /** * @inheritdoc */ public function up() { $this->createTable('activity_category', [ 'id' => $this->primaryKey(), 'activity_id' => $this->integer()->notNull(), 'category_id' => $this->integer()->notNull(), ]); } /** * @inheritdoc */ public function down() { $this->dropTable('activity_category'); } }
StefNijenhuis/yii-test
console/migrations/m170220_094103_create_activity_category_table.php
PHP
bsd-3-clause
579
<?php use yii\helpers\Html; use yii\helpers\Url; use yii\widgets\DetailView; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model app\models\Cancion */ $artista = $model->idCancion->idAlbum->idArtista; ?> <div class="cancion-view"> <div class="col-sm-6 col-md-4"> <div class="thumbnail text-center" style="background:url('<?= $model->idCancion->idAlbum->getImageUrl()?>');background-size: cover;background-repeat: no-repeat;background-position: center;"> <a href="<?= Url::to(['/canciones/view', 'id' => $model->idCancion->id]) ?>"> <div class="caption cancion-view-profile"> <h3 class="rosa"><?= $model->idCancion->nombre ?></h3> <p class="rosa"><?=$artista->nombre?></p> </div> </a> </div> </div> </div>
joludelgar/bestlyrics
views/letras/profile.php
PHP
bsd-3-clause
824
require 'spec_helper' describe Chatter do before do @chatter = Factory(:chatter) end context 'validations' do it 'uniqueness of phone' do attr = Factory.attributes_for(:chatter) Chatter.create!(attr) @invalid_chatter = Chatter.create(attr) @invalid_chatter.should_not be_valid end end context 'deletes' do it 'deletes text sessions' do Factory(:text_session, :chatter => @chatter) lambda {@chatter.destroy}.should change(TextSession, :count).by(-1) end end end
danmelton/chatreach
spec/models/chatter_spec.rb
Ruby
bsd-3-clause
537
# -*- coding: utf-8 -*- from bda.plone.discount import UUID_PLONE_ROOT from bda.plone.discount.tests import Discount_INTEGRATION_TESTING from bda.plone.discount.tests import set_browserlayer from plone.uuid.interfaces import IUUID import unittest2 as unittest class TestDiscount(unittest.TestCase): layer = Discount_INTEGRATION_TESTING def setUp(self): self.portal = self.layer['portal'] self.request = self.layer['request'] set_browserlayer(self.request) def test_plone_root_uuid(self): self.assertEquals(IUUID(self.portal), UUID_PLONE_ROOT)
TheVirtualLtd/bda.plone.discount
src/bda/plone/discount/tests/test_discount.py
Python
bsd-3-clause
592
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.10"/> <title>Wyatt-STM: WSTM::WChannel&lt; Data_t &gt; Class Template Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Wyatt-STM &#160;<span id="projectnumber">1.0.0</span> </div> <div id="projectbrief">Software transactional memory system developed at Wyatt Technology</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.10 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespace_w_s_t_m.html">WSTM</a></li><li class="navelem"><a class="el" href="class_w_s_t_m_1_1_w_channel.html">WChannel</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-types">Public Types</a> &#124; <a href="#pub-methods">Public Member Functions</a> &#124; <a href="#friends">Friends</a> &#124; <a href="class_w_s_t_m_1_1_w_channel-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">WSTM::WChannel&lt; Data_t &gt; Class Template Reference<div class="ingroups"><a class="el" href="group___channel.html">Multi-cast Channels</a></div></div> </div> </div><!--header--> <div class="contents"> <p>The write end of a transactional multi-cast channel. <a href="class_w_s_t_m_1_1_w_channel.html#details">More...</a></p> <p><code>#include &lt;<a class="el" href="channel_8h_source.html">channel.h</a>&gt;</code></p> <div class="dynheader"> Inheritance diagram for WSTM::WChannel&lt; Data_t &gt;:</div> <div class="dyncontent"> <div class="center"> <img src="class_w_s_t_m_1_1_w_channel.png" usemap="#WSTM::WChannel&lt; Data_t &gt;_map" alt=""/> <map id="WSTM::WChannel&lt; Data_t &gt;_map" name="WSTM::WChannel&lt; Data_t &gt;_map"> </map> </div></div> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-types"></a> Public Types</h2></td></tr> <tr class="memitem:abd107a26fe4bde3b68e8b7af87a235f9"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="abd107a26fe4bde3b68e8b7af87a235f9"></a> using&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_w_s_t_m_1_1_w_channel.html#abd107a26fe4bde3b68e8b7af87a235f9">Data</a> = Data_t</td></tr> <tr class="memdesc:abd107a26fe4bde3b68e8b7af87a235f9"><td class="mdescLeft">&#160;</td><td class="mdescRight">The type of data sent through the channel. <br /></td></tr> <tr class="separator:abd107a26fe4bde3b68e8b7af87a235f9"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a6d12c7808a3f2d953f61ce94bf5edf36"><td class="memItemLeft" align="right" valign="top">using&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_w_s_t_m_1_1_w_channel.html#a6d12c7808a3f2d953f61ce94bf5edf36">WReaderInitFunc</a> = std::function&lt; Data_t(<a class="el" href="class_w_s_t_m_1_1_w_atomic.html">WAtomic</a> &amp;)&gt;</td></tr> <tr class="memdesc:a6d12c7808a3f2d953f61ce94bf5edf36"><td class="mdescLeft">&#160;</td><td class="mdescRight">Intial message generation function. <a href="#a6d12c7808a3f2d953f61ce94bf5edf36">More...</a><br /></td></tr> <tr class="separator:a6d12c7808a3f2d953f61ce94bf5edf36"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a150f3f40aa8d88f3515794ac5066f18a"><td class="memItemLeft" align="right" valign="top">using&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_w_s_t_m_1_1_w_channel.html#a150f3f40aa8d88f3515794ac5066f18a">WWriteSignal</a> = boost::signals2::signal&lt; void()&gt;</td></tr> <tr class="memdesc:a150f3f40aa8d88f3515794ac5066f18a"><td class="mdescLeft">&#160;</td><td class="mdescRight">Signal emitted when the channel is written to. <a href="#a150f3f40aa8d88f3515794ac5066f18a">More...</a><br /></td></tr> <tr class="separator:a150f3f40aa8d88f3515794ac5066f18a"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:aa0ef9da779746135a92ec9e335c893bc"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_w_s_t_m_1_1_w_channel.html#aa0ef9da779746135a92ec9e335c893bc">WChannel</a> (<a class="el" href="class_w_s_t_m_1_1_w_channel.html#a6d12c7808a3f2d953f61ce94bf5edf36">WReaderInitFunc</a> m_readerInit=<a class="el" href="class_w_s_t_m_1_1_w_channel.html#a6d12c7808a3f2d953f61ce94bf5edf36">WReaderInitFunc</a>())</td></tr> <tr class="memdesc:aa0ef9da779746135a92ec9e335c893bc"><td class="mdescLeft">&#160;</td><td class="mdescRight">Creates an empty channel. <a href="#aa0ef9da779746135a92ec9e335c893bc">More...</a><br /></td></tr> <tr class="separator:aa0ef9da779746135a92ec9e335c893bc"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a19a50aec1253c74f28093d6f35dc853f"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_w_s_t_m_1_1_w_channel.html#a19a50aec1253c74f28093d6f35dc853f">SetReaderInitFunc</a> (<a class="el" href="class_w_s_t_m_1_1_w_channel.html#a6d12c7808a3f2d953f61ce94bf5edf36">WReaderInitFunc</a> readerInit)</td></tr> <tr class="memdesc:a19a50aec1253c74f28093d6f35dc853f"><td class="mdescLeft">&#160;</td><td class="mdescRight">Sets the reader initialization function for this channel replacing any existing reader initialization function. <a href="#a19a50aec1253c74f28093d6f35dc853f">More...</a><br /></td></tr> <tr class="separator:a19a50aec1253c74f28093d6f35dc853f"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a5ef2ae7785c3fc9fd979cef7fdc3ea05"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_w_s_t_m_1_1_w_channel.html#a5ef2ae7785c3fc9fd979cef7fdc3ea05">Write</a> (const <a class="el" href="class_w_s_t_m_1_1_w_channel.html#abd107a26fe4bde3b68e8b7af87a235f9">Data</a> &amp;data, <a class="el" href="class_w_s_t_m_1_1_w_atomic.html">WAtomic</a> &amp;at)</td></tr> <tr class="memdesc:a5ef2ae7785c3fc9fd979cef7fdc3ea05"><td class="mdescLeft">&#160;</td><td class="mdescRight">Writes a message to the channel. <a href="#a5ef2ae7785c3fc9fd979cef7fdc3ea05">More...</a><br /></td></tr> <tr class="separator:a5ef2ae7785c3fc9fd979cef7fdc3ea05"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a989445aae77943e93c08901b5c5f8a6a"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_w_s_t_m_1_1_w_channel.html#a989445aae77943e93c08901b5c5f8a6a">Write</a> (const <a class="el" href="class_w_s_t_m_1_1_w_channel.html#abd107a26fe4bde3b68e8b7af87a235f9">Data</a> &amp;data)</td></tr> <tr class="memdesc:a989445aae77943e93c08901b5c5f8a6a"><td class="mdescLeft">&#160;</td><td class="mdescRight">Writes a message to the channel. <a href="#a989445aae77943e93c08901b5c5f8a6a">More...</a><br /></td></tr> <tr class="separator:a989445aae77943e93c08901b5c5f8a6a"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a181dd845e2f95f3600b28b766ffd4ae4"><td class="memTemplParams" colspan="2">template&lt;typename Handler_t &gt; </td></tr> <tr class="memitem:a181dd845e2f95f3600b28b766ffd4ae4"><td class="memTemplItemLeft" align="right" valign="top">auto&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="class_w_s_t_m_1_1_w_channel.html#a181dd845e2f95f3600b28b766ffd4ae4">ConnectToWriteSignal</a> (Handler_t &amp;&amp;h)</td></tr> <tr class="memdesc:a181dd845e2f95f3600b28b766ffd4ae4"><td class="mdescLeft">&#160;</td><td class="mdescRight">Connects a handler to the channels write signal. <a href="#a181dd845e2f95f3600b28b766ffd4ae4">More...</a><br /></td></tr> <tr class="separator:a181dd845e2f95f3600b28b766ffd4ae4"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr><td colspan="2"><div class="groupHeader"></div></td></tr> <tr class="memitem:a98e7bce663cccfaee70b89e9051389b7"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_w_s_t_m_1_1_w_channel.html#a98e7bce663cccfaee70b89e9051389b7">WChannel</a> (<a class="el" href="class_w_s_t_m_1_1_w_channel.html">WChannel</a> &amp;&amp;c)</td></tr> <tr class="memdesc:a98e7bce663cccfaee70b89e9051389b7"><td class="mdescLeft">&#160;</td><td class="mdescRight">Moves the logical channel from the given <a class="el" href="class_w_s_t_m_1_1_w_channel.html" title="The write end of a transactional multi-cast channel. ">WChannel</a> object so that this object owns it. <a href="#a98e7bce663cccfaee70b89e9051389b7">More...</a><br /></td></tr> <tr class="separator:a98e7bce663cccfaee70b89e9051389b7"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a080a7ef123fd63de2c90830ebb39e1d4"><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_w_s_t_m_1_1_w_channel.html">WChannel</a> &amp;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_w_s_t_m_1_1_w_channel.html#a080a7ef123fd63de2c90830ebb39e1d4">operator=</a> (<a class="el" href="class_w_s_t_m_1_1_w_channel.html">WChannel</a> &amp;&amp;c)</td></tr> <tr class="memdesc:a080a7ef123fd63de2c90830ebb39e1d4"><td class="mdescLeft">&#160;</td><td class="mdescRight">Moves the logical channel from the given <a class="el" href="class_w_s_t_m_1_1_w_channel.html" title="The write end of a transactional multi-cast channel. ">WChannel</a> object so that this object owns it. <a href="#a080a7ef123fd63de2c90830ebb39e1d4">More...</a><br /></td></tr> <tr class="separator:a080a7ef123fd63de2c90830ebb39e1d4"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="friends"></a> Friends</h2></td></tr> <tr class="memitem:a83455c66e46732ab089b8c71753b1b71"><td class="memTemplParams" colspan="2"><a class="anchor" id="a83455c66e46732ab089b8c71753b1b71"></a> template&lt;typename &gt; </td></tr> <tr class="memitem:a83455c66e46732ab089b8c71753b1b71"><td class="memTemplItemLeft" align="right" valign="top">class&#160;</td><td class="memTemplItemRight" valign="bottom"><b>WReadOnlyChannel</b></td></tr> <tr class="separator:a83455c66e46732ab089b8c71753b1b71"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:adcaf1fa534ec18b6dd02c90fb0292130"><td class="memTemplParams" colspan="2"><a class="anchor" id="adcaf1fa534ec18b6dd02c90fb0292130"></a> template&lt;typename &gt; </td></tr> <tr class="memitem:adcaf1fa534ec18b6dd02c90fb0292130"><td class="memTemplItemLeft" align="right" valign="top">class&#160;</td><td class="memTemplItemRight" valign="bottom"><b>WChannelWriter</b></td></tr> <tr class="separator:adcaf1fa534ec18b6dd02c90fb0292130"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ad86f9dc1e01e4bbe8011678ba85e26d8"><td class="memTemplParams" colspan="2"><a class="anchor" id="ad86f9dc1e01e4bbe8011678ba85e26d8"></a> template&lt;typename &gt; </td></tr> <tr class="memitem:ad86f9dc1e01e4bbe8011678ba85e26d8"><td class="memTemplItemLeft" align="right" valign="top">class&#160;</td><td class="memTemplItemRight" valign="bottom"><b>WChannelReader</b></td></tr> <tr class="separator:ad86f9dc1e01e4bbe8011678ba85e26d8"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><h3>template&lt;typename Data_t&gt;<br /> class WSTM::WChannel&lt; Data_t &gt;</h3> <p>The write end of a transactional multi-cast channel. </p> <p>Messages are written into the channel using the Write method of this class. The messages are then received by <a class="el" href="class_w_s_t_m_1_1_w_channel_reader.html" title="The read end of a multi-cast channel. ">WChannelReader</a> objects. Write and read operation are protected within STM transactions. One can also create custom initial messages for new readers and register callbacks that are called when a message is written to the channel.</p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">Data_t</td><td>The type of data sent through the channel. This type must be copyable. Normally this should be a std::shared_ptr&lt;const Val_t&gt; where Val_t is the actual data type being sent. Note that all readers of the channel will get the same copy of the data, so if the data is mutable you could run into problems. </td></tr> </table> </dd> </dl> <p>Definition at line <a class="el" href="channel_8h_source.html#l00244">244</a> of file <a class="el" href="channel_8h_source.html">channel.h</a>.</p> </div><h2 class="groupheader">Member Typedef Documentation</h2> <a class="anchor" id="a6d12c7808a3f2d953f61ce94bf5edf36"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename Data_t&gt; </div> <table class="memname"> <tr> <td class="memname">using <a class="el" href="class_w_s_t_m_1_1_w_channel.html">WSTM::WChannel</a>&lt; Data_t &gt;::<a class="el" href="class_w_s_t_m_1_1_w_channel.html#a6d12c7808a3f2d953f61ce94bf5edf36">WReaderInitFunc</a> = std::function&lt;Data_t (<a class="el" href="class_w_s_t_m_1_1_w_atomic.html">WAtomic</a>&amp;)&gt;</td> </tr> </table> </div><div class="memdoc"> <p>Intial message generation function. </p> <p>This function will be called for each <a class="el" href="class_w_s_t_m_1_1_w_channel_reader.html" title="The read end of a multi-cast channel. ">WChannelReader</a> object connected to the channel. It is called within a STM transaction, the <a class="el" href="class_w_s_t_m_1_1_w_atomic.html" title="Functions passed to Atomically must take a reference to one of these objects as their only argument...">WAtomic</a> object is passed in. The returned value is set as the first message that the new <a class="el" href="class_w_s_t_m_1_1_w_channel_reader.html" title="The read end of a multi-cast channel. ">WChannelReader</a> object sees, only the new <a class="el" href="class_w_s_t_m_1_1_w_channel_reader.html" title="The read end of a multi-cast channel. ">WChannelReader</a> object will see this message. </p> <p>Definition at line <a class="el" href="channel_8h_source.html#l00264">264</a> of file <a class="el" href="channel_8h_source.html">channel.h</a>.</p> </div> </div> <a class="anchor" id="a150f3f40aa8d88f3515794ac5066f18a"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename Data_t&gt; </div> <table class="memname"> <tr> <td class="memname">using <a class="el" href="class_w_s_t_m_1_1_w_channel.html">WSTM::WChannel</a>&lt; Data_t &gt;::<a class="el" href="class_w_s_t_m_1_1_w_channel.html#a150f3f40aa8d88f3515794ac5066f18a">WWriteSignal</a> = boost::signals2::signal&lt;void ()&gt;</td> </tr> </table> </div><div class="memdoc"> <p>Signal emitted when the channel is written to. </p> <p>This signal mainly exists so that GUI code can receive window messages when a channel has something in it to read. If you need to wait for a channel to be written to you are better off using <a class="el" href="class_w_s_t_m_1_1_w_channel_reader.html#a4f8b7c5cadf15ce0f0471f9c7d26d4c0" title="Checks for available messages. ">WChannelReader::RetryIfEmpty</a>. </p> <p>Definition at line <a class="el" href="channel_8h_source.html#l00339">339</a> of file <a class="el" href="channel_8h_source.html">channel.h</a>.</p> </div> </div> <h2 class="groupheader">Constructor &amp; Destructor Documentation</h2> <a class="anchor" id="aa0ef9da779746135a92ec9e335c893bc"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename Data_t&gt; </div> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname"><a class="el" href="class_w_s_t_m_1_1_w_channel.html">WSTM::WChannel</a>&lt; Data_t &gt;::<a class="el" href="class_w_s_t_m_1_1_w_channel.html">WChannel</a> </td> <td>(</td> <td class="paramtype"><a class="el" href="class_w_s_t_m_1_1_w_channel.html#a6d12c7808a3f2d953f61ce94bf5edf36">WReaderInitFunc</a>&#160;</td> <td class="paramname"><em>m_readerInit</em> = <code><a class="el" href="class_w_s_t_m_1_1_w_channel.html#a6d12c7808a3f2d953f61ce94bf5edf36">WReaderInitFunc</a>&#160;()</code></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Creates an empty channel. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">m_readerInit</td><td>The reader initialization function. This function generates the first message sent to a new reader. It is called once for each reader that is created from this channel at the time that the reader is being created. If it is invalid then no initial message will be sent to new readers. </td></tr> </table> </dd> </dl> <p>Definition at line <a class="el" href="channel_8h_source.html#l00274">274</a> of file <a class="el" href="channel_8h_source.html">channel.h</a>.</p> </div> </div> <a class="anchor" id="a98e7bce663cccfaee70b89e9051389b7"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename Data_t&gt; </div> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname"><a class="el" href="class_w_s_t_m_1_1_w_channel.html">WSTM::WChannel</a>&lt; Data_t &gt;::<a class="el" href="class_w_s_t_m_1_1_w_channel.html">WChannel</a> </td> <td>(</td> <td class="paramtype"><a class="el" href="class_w_s_t_m_1_1_w_channel.html">WChannel</a>&lt; Data_t &gt; &amp;&amp;&#160;</td> <td class="paramname"><em>c</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Moves the logical channel from the given <a class="el" href="class_w_s_t_m_1_1_w_channel.html" title="The write end of a transactional multi-cast channel. ">WChannel</a> object so that this object owns it. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">c</td><td>The <a class="el" href="class_w_s_t_m_1_1_w_channel.html" title="The write end of a transactional multi-cast channel. ">WChannel</a> object to move from.</td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd>This <a class="el" href="class_w_s_t_m_1_1_w_channel.html" title="The write end of a transactional multi-cast channel. ">WChannel</a> object. </dd></dl> <p>Definition at line <a class="el" href="channel_8h_source.html#l00286">286</a> of file <a class="el" href="channel_8h_source.html">channel.h</a>.</p> </div> </div> <h2 class="groupheader">Member Function Documentation</h2> <a class="anchor" id="a181dd845e2f95f3600b28b766ffd4ae4"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename Data_t&gt; </div> <div class="memtemplate"> template&lt;typename Handler_t &gt; </div> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">auto <a class="el" href="class_w_s_t_m_1_1_w_channel.html">WSTM::WChannel</a>&lt; Data_t &gt;::ConnectToWriteSignal </td> <td>(</td> <td class="paramtype">Handler_t &amp;&amp;&#160;</td> <td class="paramname"><em>h</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Connects a handler to the channels write signal. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">h</td><td>The signal handler to connect.</td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd>The boost::signals2::connection object for the established connection.</dd></dl> <dl class="section see"><dt>See also</dt><dd><a class="el" href="class_w_s_t_m_1_1_w_channel.html#a150f3f40aa8d88f3515794ac5066f18a" title="Signal emitted when the channel is written to. ">WWriteSignal</a> </dd></dl> <p>Definition at line <a class="el" href="channel_8h_source.html#l00351">351</a> of file <a class="el" href="channel_8h_source.html">channel.h</a>.</p> </div> </div> <a class="anchor" id="a080a7ef123fd63de2c90830ebb39e1d4"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename Data_t&gt; </div> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname"><a class="el" href="class_w_s_t_m_1_1_w_channel.html">WChannel</a>&amp; <a class="el" href="class_w_s_t_m_1_1_w_channel.html">WSTM::WChannel</a>&lt; Data_t &gt;::operator= </td> <td>(</td> <td class="paramtype"><a class="el" href="class_w_s_t_m_1_1_w_channel.html">WChannel</a>&lt; Data_t &gt; &amp;&amp;&#160;</td> <td class="paramname"><em>c</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Moves the logical channel from the given <a class="el" href="class_w_s_t_m_1_1_w_channel.html" title="The write end of a transactional multi-cast channel. ">WChannel</a> object so that this object owns it. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">c</td><td>The <a class="el" href="class_w_s_t_m_1_1_w_channel.html" title="The write end of a transactional multi-cast channel. ">WChannel</a> object to move from.</td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd>This <a class="el" href="class_w_s_t_m_1_1_w_channel.html" title="The write end of a transactional multi-cast channel. ">WChannel</a> object. </dd></dl> <p>Definition at line <a class="el" href="channel_8h_source.html#l00290">290</a> of file <a class="el" href="channel_8h_source.html">channel.h</a>.</p> </div> </div> <a class="anchor" id="a19a50aec1253c74f28093d6f35dc853f"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename Data_t&gt; </div> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">void <a class="el" href="class_w_s_t_m_1_1_w_channel.html">WSTM::WChannel</a>&lt; Data_t &gt;::SetReaderInitFunc </td> <td>(</td> <td class="paramtype"><a class="el" href="class_w_s_t_m_1_1_w_channel.html#a6d12c7808a3f2d953f61ce94bf5edf36">WReaderInitFunc</a>&#160;</td> <td class="paramname"><em>readerInit</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Sets the reader initialization function for this channel replacing any existing reader initialization function. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">readerInit</td><td>The reader initialization function. This function generates the first message sent to a new reader. It is called once for each reader that is created from this channel at the time that the reader is being created. If it is invalid then no initial message will be sent to new readers. </td></tr> </table> </dd> </dl> <p>Definition at line <a class="el" href="channel_8h_source.html#l00306">306</a> of file <a class="el" href="channel_8h_source.html">channel.h</a>.</p> </div> </div> <a class="anchor" id="a5ef2ae7785c3fc9fd979cef7fdc3ea05"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename Data_t&gt; </div> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">void <a class="el" href="class_w_s_t_m_1_1_w_channel.html">WSTM::WChannel</a>&lt; Data_t &gt;::Write </td> <td>(</td> <td class="paramtype">const <a class="el" href="class_w_s_t_m_1_1_w_channel.html#abd107a26fe4bde3b68e8b7af87a235f9">Data</a> &amp;&#160;</td> <td class="paramname"><em>data</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype"><a class="el" href="class_w_s_t_m_1_1_w_atomic.html">WAtomic</a> &amp;&#160;</td> <td class="paramname"><em>at</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Writes a message to the channel. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">data</td><td>The message to write.</td></tr> <tr><td class="paramname">at</td><td>The transaction to write the message within. </td></tr> </table> </dd> </dl> <p>Definition at line <a class="el" href="channel_8h_source.html#l00318">318</a> of file <a class="el" href="channel_8h_source.html">channel.h</a>.</p> </div> </div> <a class="anchor" id="a989445aae77943e93c08901b5c5f8a6a"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename Data_t&gt; </div> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">void <a class="el" href="class_w_s_t_m_1_1_w_channel.html">WSTM::WChannel</a>&lt; Data_t &gt;::Write </td> <td>(</td> <td class="paramtype">const <a class="el" href="class_w_s_t_m_1_1_w_channel.html#abd107a26fe4bde3b68e8b7af87a235f9">Data</a> &amp;&#160;</td> <td class="paramname"><em>data</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Writes a message to the channel. </p> <p>This version creates its own transaction to do the write operation within.</p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">data</td><td>The message to write. </td></tr> </table> </dd> </dl> <p>Definition at line <a class="el" href="channel_8h_source.html#l00329">329</a> of file <a class="el" href="channel_8h_source.html">channel.h</a>.</p> </div> </div> <hr/>The documentation for this class was generated from the following file:<ul> <li>C:/projects/Wyatt-STM/wstm/<a class="el" href="channel_8h_source.html">channel.h</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.10 </small></address> </body> </html>
bretthall/Wyatt-STM
doc/ref/html/class_w_s_t_m_1_1_w_channel.html
HTML
bsd-3-clause
30,830
class CreateSpreeCmsLayouts < ActiveRecord::Migration def change create_table :spree_cms_layouts do |t| t.string :name t.text :template t.timestamps null: false end end end
hoangnghiem/spree_tutu_cms
db/migrate/20150918023316_create_spree_cms_layouts.rb
Ruby
bsd-3-clause
204